Skip to content

Commit

Permalink
if constexpr shortcut for CancellationToken::merge(x)
Browse files Browse the repository at this point in the history
Summary: This takes the `merge1` microbench (stacked) from 74ns to 24ns without regressing anything. This is helpful for generic programs, where the pack MIGHT have 1 element, and there's no reason to shortcut this on the client side.

Reviewed By: Orvid

Differential Revision: D65044520

fbshipit-source-id: e2f91bbc69439d5759d79d8a5391f5ba3e0239ed
  • Loading branch information
Alexey Spiridonov authored and facebook-github-bot committed Oct 30, 2024
1 parent df4cfee commit 9173e45
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
17 changes: 11 additions & 6 deletions folly/CancellationToken-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -448,12 +448,17 @@ std::pair<CancellationSource, std::tuple<Data...>*> CancellationSource::create(

template <typename... Ts>
inline CancellationToken CancellationToken::merge(Ts&&... tokens) {
bool canBeCancelled = detail::variadicDisjunction(tokens.canBeCancelled()...);
return canBeCancelled
? CancellationToken(
detail::FixedMergingCancellationState<sizeof...(Ts)>::create(
std::forward<Ts>(tokens)...))
: CancellationToken();
if constexpr (sizeof...(Ts) == 1) {
return (tokens, ...);
} else {
bool canBeCancelled =
detail::variadicDisjunction(tokens.canBeCancelled()...);
return canBeCancelled
? CancellationToken(
detail::FixedMergingCancellationState<sizeof...(Ts)>::create(
std::forward<Ts>(tokens)...))
: CancellationToken();
}
}

} // namespace folly
6 changes: 6 additions & 0 deletions folly/test/CancellationTokenTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,12 @@ TEST(CancellationTokenTest, MergedToken) {
EXPECT_FALSE(token.canBeCancelled());
}

TEST(CancellationTokenTest, Merging1TokenIsEfficient) {
CancellationSource src;
CancellationToken tok = src.getToken();
EXPECT_TRUE(tok == CancellationToken::merge(tok));
}

TEST(CancellationTokenTest, TokenWithData) {
struct Guard {
int& counter;
Expand Down

0 comments on commit 9173e45

Please sign in to comment.