diff options
author | clang-format 12.0.1 <> | 2023-02-10 04:44:29 -0800 |
---|---|---|
committer | Evergreen Agent <no-reply@evergreen.mongodb.com> | 2023-02-11 08:00:01 +0000 |
commit | f63255ee677ecae5896d6f35dd712ed60ae8c39a (patch) | |
tree | 97ffffa8d6f9e1a131aeb1ccc1d42f133f8407fd /src/mongo/util | |
parent | 375366e3f317d18717df24f861b09c4d2f8fb27f (diff) | |
download | mongo-f63255ee677ecae5896d6f35dd712ed60ae8c39a.tar.gz |
SERVER-72197 Run clang-format 12.0.1 on the codebase
Signed-off-by: Ryan Egesdahl <ryan.egesdahl@mongodb.com>
Diffstat (limited to 'src/mongo/util')
49 files changed, 634 insertions, 479 deletions
diff --git a/src/mongo/util/background.cpp b/src/mongo/util/background.cpp index ce5c3f86a9a..c3c48aceaa6 100644 --- a/src/mongo/util/background.cpp +++ b/src/mongo/util/background.cpp @@ -185,7 +185,9 @@ void BackgroundJob::go() { // If the job is already 'done', for instance because it was cancelled or already // finished, ignore additional requests to run the job. if (_status->state == NotStarted) { - stdx::thread{[this] { jobBody(); }}.detach(); + stdx::thread{[this] { + jobBody(); + }}.detach(); _status->state = Running; } } diff --git a/src/mongo/util/base64.cpp b/src/mongo/util/base64.cpp index 9747d6915fb..b0063374d12 100644 --- a/src/mongo/util/base64.cpp +++ b/src/mongo/util/base64.cpp @@ -51,8 +51,12 @@ void encodeImpl(Writer&& write, StringData in) { static_assert(Mode::kEncodeTable.size() == 64, "Invalid encoding table"); const char* data = in.rawData(); std::size_t size = in.size(); - auto readOctet = [&data] { return static_cast<std::uint8_t>(*data++); }; - auto encodeSextet = [](unsigned x) { return Mode::kEncodeTable[x & 0b11'1111]; }; + auto readOctet = [&data] { + return static_cast<std::uint8_t>(*data++); + }; + auto encodeSextet = [](unsigned x) { + return Mode::kEncodeTable[x & 0b11'1111]; + }; std::array<char, 512> buf; std::array<char, 512>::iterator p; @@ -229,7 +233,9 @@ bool Base64Impl<Standard>::validate(StringData s) { return true; } - auto const unwindTerminator = [](auto it) { return (*(it - 1) == '=') ? (it - 1) : it; }; + auto const unwindTerminator = [](auto it) { + return (*(it - 1) == '=') ? (it - 1) : it; + }; auto const e = unwindTerminator(unwindTerminator(std::end(s))); return e == std::find_if(std::begin(s), e, [](const char ch) { return !valid<Standard>(ch); }); @@ -241,7 +247,9 @@ bool Base64Impl<URL>::validate(StringData s) { return true; } - auto const unwindTerminator = [](auto it) { return (*(it - 1) == '=') ? (it - 1) : it; }; + auto const unwindTerminator = [](auto it) { + return (*(it - 1) == '=') ? (it - 1) : it; + }; auto e = std::end(s); switch (s.size() % 4) { diff --git a/src/mongo/util/clock_source_mock_test.cpp b/src/mongo/util/clock_source_mock_test.cpp index 3729c4fb9b3..40442b5a0da 100644 --- a/src/mongo/util/clock_source_mock_test.cpp +++ b/src/mongo/util/clock_source_mock_test.cpp @@ -44,7 +44,9 @@ TEST(ClockSourceMockTest, ExpiredAlarmExecutesWhenSet) { ClockSourceMock cs; int alarmFiredCount = 0; const Date_t alarmDate = cs.now(); - const auto alarmAction = [&] { ++alarmFiredCount; }; + const auto alarmAction = [&] { + ++alarmFiredCount; + }; cs.setAlarm(alarmDate, alarmAction); ASSERT_EQ(1, alarmFiredCount) << cs.now(); alarmFiredCount = 0; @@ -58,7 +60,9 @@ TEST(ClockSourceMockTest, AlarmExecutesAfterExpirationUsingAdvance) { ClockSourceMock cs; int alarmFiredCount = 0; const Date_t alarmDate = cs.now() + Seconds{10}; - const auto alarmAction = [&] { ++alarmFiredCount; }; + const auto alarmAction = [&] { + ++alarmFiredCount; + }; cs.setAlarm(alarmDate, alarmAction); ASSERT_EQ(0, alarmFiredCount) << cs.now(); cs.advance(Seconds{8}); @@ -76,7 +80,9 @@ TEST(ClockSourceMockTest, AlarmExecutesAfterExpirationUsingReset) { int alarmFiredCount = 0; const Date_t startDate = cs.now(); const Date_t alarmDate = startDate + Seconds{10}; - const auto alarmAction = [&] { ++alarmFiredCount; }; + const auto alarmAction = [&] { + ++alarmFiredCount; + }; cs.setAlarm(alarmDate, alarmAction); ASSERT_EQ(0, alarmFiredCount) << cs.now(); cs.reset(startDate + Seconds{8}); @@ -93,7 +99,9 @@ TEST(ClockSourceMockTest, MultipleAlarmsWithSameDeadlineTriggeredAtSameTime) { ClockSourceMock cs; int alarmFiredCount = 0; const Date_t alarmDate = cs.now() + Seconds{10}; - const auto alarmAction = [&] { ++alarmFiredCount; }; + const auto alarmAction = [&] { + ++alarmFiredCount; + }; cs.setAlarm(alarmDate, alarmAction); cs.setAlarm(alarmDate, alarmAction); ASSERT_EQ(0, alarmFiredCount) << cs.now(); @@ -104,7 +112,9 @@ TEST(ClockSourceMockTest, MultipleAlarmsWithSameDeadlineTriggeredAtSameTime) { TEST(ClockSourceMockTest, MultipleAlarmsWithDifferentDeadlineTriggeredAtSameTime) { ClockSourceMock cs; int alarmFiredCount = 0; - const auto alarmAction = [&] { ++alarmFiredCount; }; + const auto alarmAction = [&] { + ++alarmFiredCount; + }; cs.setAlarm(cs.now() + Seconds{1}, alarmAction); cs.setAlarm(cs.now() + Seconds{10}, alarmAction); ASSERT_EQ(0, alarmFiredCount) << cs.now(); @@ -115,7 +125,9 @@ TEST(ClockSourceMockTest, MultipleAlarmsWithDifferentDeadlineTriggeredAtSameTime TEST(ClockSourceMockTest, MultipleAlarmsWithDifferentDeadlineTriggeredAtDifferentTimes) { ClockSourceMock cs; int alarmFiredCount = 0; - const auto alarmAction = [&] { ++alarmFiredCount; }; + const auto alarmAction = [&] { + ++alarmFiredCount; + }; cs.setAlarm(cs.now() + Seconds{1}, alarmAction); cs.setAlarm(cs.now() + Seconds{10}, alarmAction); ASSERT_EQ(0, alarmFiredCount) << cs.now(); diff --git a/src/mongo/util/cmdline_utils/censor_cmdline.cpp b/src/mongo/util/cmdline_utils/censor_cmdline.cpp index fa1d93d7087..5416be6a215 100644 --- a/src/mongo/util/cmdline_utils/censor_cmdline.cpp +++ b/src/mongo/util/cmdline_utils/censor_cmdline.cpp @@ -139,9 +139,9 @@ void censorBSONObjRecursive(const BSONObj& params, // Object we are cen BSONObjIterator paramsIterator(params); while (paramsIterator.more()) { BSONElement param = paramsIterator.next(); - std::string dottedName = - (parentPath.empty() ? param.fieldName() - : isArray ? parentPath : parentPath + '.' + param.fieldName()); + std::string dottedName = (parentPath.empty() ? param.fieldName() + : isArray ? parentPath + : parentPath + '.' + param.fieldName()); if (param.type() == Array) { BSONObjBuilder subArray(result->subarrayStart(param.fieldName())); censorBSONObjRecursive(param.Obj(), dottedName, true, &subArray); diff --git a/src/mongo/util/concepts.h b/src/mongo/util/concepts.h index 07dbff6c7e5..fcee167037d 100644 --- a/src/mongo/util/concepts.h +++ b/src/mongo/util/concepts.h @@ -171,7 +171,7 @@ // Same as above, but without the default argument since some compilers (correctly) disallow // repeating the default argument on the definition. -#define REQUIRES_OUT_OF_LINE_DEF(...) std::enable_if_t<(__VA_ARGS__), int>> +#define REQUIRES_OUT_OF_LINE_DEF(...) std::enable_if_t<(__VA_ARGS__), int> > // Need the second arg in the template to depend on both a template argument (so it is dependent), // and the current line number (so it can be overloaded). The __VA_ARGS__ expression will generally @@ -186,22 +186,22 @@ // Works by declaring a function template taking `decls` arguments and using expression-SFINAE using // `exprs` on the return type. A bool is defined as true if it is possible to instantiate the // template with the supplied arguments by taking its address. -#define MONGO_MAKE_BOOL_TRAIT(name, tpl_params, tpl_args, decls, /*exprs*/...) \ - template <MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_params> \ - auto make_trait_impl_##name##_fn(MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND decls) \ - ->decltype(__VA_ARGS__); \ - \ - template <typename ALWAYS_VOID, MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_params> \ - constexpr inline bool make_trait_impl_##name##_bool = false; \ - \ - template <MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_params> \ - constexpr inline bool make_trait_impl_##name##_bool< \ - std::void_t<decltype( \ - &make_trait_impl_##name##_fn<MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_args>)>, \ - MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_args> = true; \ - \ - template <MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_params> \ - constexpr inline bool name = \ +#define MONGO_MAKE_BOOL_TRAIT(name, tpl_params, tpl_args, decls, /*exprs*/...) \ + template <MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_params> \ + auto make_trait_impl_##name##_fn(MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND decls) \ + ->decltype(__VA_ARGS__); \ + \ + template <typename ALWAYS_VOID, MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_params> \ + constexpr inline bool make_trait_impl_##name##_bool = false; \ + \ + template <MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_params> \ + constexpr inline bool make_trait_impl_##name##_bool< \ + std::void_t< \ + decltype(&make_trait_impl_##name##_fn<MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_args>)>, \ + MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_args> = true; \ + \ + template <MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_params> \ + constexpr inline bool name = \ make_trait_impl_##name##_bool<void, MONGO_MAKE_BOOL_TRAIT_HELPER_EXPAND tpl_args> #endif diff --git a/src/mongo/util/concurrency/thread_pool.cpp b/src/mongo/util/concurrency/thread_pool.cpp index f4597f27e4d..bc612ef4b43 100644 --- a/src/mongo/util/concurrency/thread_pool.cpp +++ b/src/mongo/util/concurrency/thread_pool.cpp @@ -465,7 +465,9 @@ void ThreadPool::Impl::_consumeTasks() { "minThreads"_attr = _options.minThreads); } - auto wake = [&] { return _state != running || !_pendingTasks.empty(); }; + auto wake = [&] { + return _state != running || !_pendingTasks.empty(); + }; MONGO_IDLE_THREAD_BLOCK; if (waitDeadline) { _workAvailable.wait_until(lk, waitDeadline->toSystemTimePoint(), wake); diff --git a/src/mongo/util/concurrency/thread_pool_test.cpp b/src/mongo/util/concurrency/thread_pool_test.cpp index 4f2a564b91e..a643d1f3a65 100644 --- a/src/mongo/util/concurrency/thread_pool_test.cpp +++ b/src/mongo/util/concurrency/thread_pool_test.cpp @@ -284,7 +284,9 @@ TEST(ThreadPoolTest, JoinAllRetiredThreads) { options.minThreads = 4; options.maxThreads = 8; options.maxIdleThreadAge = Milliseconds(100); - options.onJoinRetiredThread = [&](const stdx::thread& t) { retiredThreads.addAndFetch(1); }; + options.onJoinRetiredThread = [&](const stdx::thread& t) { + retiredThreads.addAndFetch(1); + }; unittest::Barrier barrier(options.maxThreads + 1); ThreadPool pool(options); diff --git a/src/mongo/util/decoration_registry.h b/src/mongo/util/decoration_registry.h index 0fc05a1efdd..4720d5fc9ed 100644 --- a/src/mongo/util/decoration_registry.h +++ b/src/mongo/util/decoration_registry.h @@ -114,7 +114,7 @@ public: auto iter = cbegin(_decorationInfo); - auto cleanupFunction = [&iter, container, this ]() noexcept->void { + auto cleanupFunction = [&iter, container, this]() noexcept -> void { using std::crend; std::for_each(std::make_reverse_iterator(iter), crend(this->_decorationInfo), @@ -149,7 +149,7 @@ public: auto iter = cbegin(_decorationInfo); - auto cleanupFunction = [&iter, container, this ]() noexcept->void { + auto cleanupFunction = [&iter, container, this]() noexcept -> void { using std::crend; std::for_each(std::make_reverse_iterator(iter), crend(this->_decorationInfo), diff --git a/src/mongo/util/dns_name.h b/src/mongo/util/dns_name.h index c1472769f07..6d7f8f82b01 100644 --- a/src/mongo/util/dns_name.h +++ b/src/mongo/util/dns_name.h @@ -315,7 +315,9 @@ public: * case. */ friend bool operator==(const HostName& lhs, const HostName& rhs) { - auto lens = [](const auto& h) { return std::tie(h._fullyQualified, h._nameComponents); }; + auto lens = [](const auto& h) { + return std::tie(h._fullyQualified, h._nameComponents); + }; return lens(lhs) == lens(rhs); } diff --git a/src/mongo/util/dynamic_catch_test.cpp b/src/mongo/util/dynamic_catch_test.cpp index 664d1199a97..b4a0a50523d 100644 --- a/src/mongo/util/dynamic_catch_test.cpp +++ b/src/mongo/util/dynamic_catch_test.cpp @@ -144,10 +144,14 @@ TEST_F(DynamicCatchTest, RealisticScenarios) { } }; #define LOC MONGO_SOURCE_LOCATION() - trial(LOC, [] { throw TestForeignRootException{"oops"}; }, "TestForeignRootException: oops"); - trial(LOC, [] { throw std::out_of_range{"testRange"}; }, "testRange"); - trial(LOC, [] { throw SpecificStdException{"oops"}; }, "SpecificStdException: oops"); - trial(LOC, [] { uasserted(ErrorCodes::UnknownError, "test"); }, "UnknownError.*test"); + trial( + LOC, [] { throw TestForeignRootException{"oops"}; }, "TestForeignRootException: oops"); + trial( + LOC, [] { throw std::out_of_range{"testRange"}; }, "testRange"); + trial( + LOC, [] { throw SpecificStdException{"oops"}; }, "SpecificStdException: oops"); + trial( + LOC, [] { uasserted(ErrorCodes::UnknownError, "test"); }, "UnknownError.*test"); #undef LOC } diff --git a/src/mongo/util/functional.h b/src/mongo/util/functional.h index a680e54a266..c697d267aaa 100644 --- a/src/mongo/util/functional.h +++ b/src/mongo/util/functional.h @@ -291,9 +291,9 @@ struct UFDeductionHelper<Ret (Class::*)(Args...) const&> : stdx::type_identity<R * non-overloaded, non-generic function objects such as lambdas that don't use `auto` arguments. */ template <typename Ret, typename... Args> -unique_function(Ret (*)(Args...))->unique_function<Ret(Args...)>; +unique_function(Ret (*)(Args...)) -> unique_function<Ret(Args...)>; template <typename T, typename Sig = typename UFDeductionHelper<decltype(&T::operator())>::type> -unique_function(T)->unique_function<Sig>; +unique_function(T) -> unique_function<Sig>; template <typename Signature> bool operator==(const unique_function<Signature>& lhs, std::nullptr_t) noexcept { diff --git a/src/mongo/util/functional_test.cpp b/src/mongo/util/functional_test.cpp index eaf43122b0f..c0700ef2e20 100644 --- a/src/mongo/util/functional_test.cpp +++ b/src/mongo/util/functional_test.cpp @@ -104,7 +104,9 @@ TEST(UniqueFunctionTest, construct_simple_unique_function_from_lambda) { // Implicit construction { RunDetection<0> runDetection; - mongo::unique_function<void()> uf = [] { RunDetection<0>::itRan = true; }; + mongo::unique_function<void()> uf = [] { + RunDetection<0>::itRan = true; + }; uf(); @@ -114,7 +116,9 @@ TEST(UniqueFunctionTest, construct_simple_unique_function_from_lambda) { // Explicit construction { RunDetection<0> runDetection; - mongo::unique_function<void()> uf{[] { RunDetection<0>::itRan = true; }}; + mongo::unique_function<void()> uf{[] { + RunDetection<0>::itRan = true; + }}; uf(); @@ -236,7 +240,9 @@ TEST(UniqueFunctionTest, assign_simple_unique_function_from_lambda) { // Implicit construction RunDetection<0> runDetection; mongo::unique_function<void()> uf; - uf = [] { RunDetection<0>::itRan = true; }; + uf = [] { + RunDetection<0>::itRan = true; + }; uf(); @@ -254,9 +260,13 @@ TEST(UniqueFunctionTest, reassign_simple_unique_function_from_lambda) { RunDetection<0> runDetection0; RunDetection<1> runDetection1; - mongo::unique_function<void()> uf = [] { RunDetection<0>::itRan = true; }; + mongo::unique_function<void()> uf = [] { + RunDetection<0>::itRan = true; + }; - uf = [] { RunDetection<1>::itRan = true; }; + uf = [] { + RunDetection<1>::itRan = true; + }; uf(); @@ -267,8 +277,11 @@ TEST(UniqueFunctionTest, reassign_simple_unique_function_from_lambda) { TEST(FunctionRefTest, reassign_simple_function_ref_from_decayed_lambda) { // Implicit construction RunDetection<0> runDetection; - mongo::function_ref<void()> fr = +[] {}; - fr = +[] { RunDetection<0>::itRan = true; }; + mongo::function_ref<void()> fr = +[] { + }; + fr = +[] { + RunDetection<0>::itRan = true; + }; fr(); @@ -293,7 +306,8 @@ TEST(FunctionRefTest, reassign_simple_function_ref_from_function_ref) { TEST(UniqueFunctionTest, accepts_a_functor_that_is_move_only) { struct Checker {}; - mongo::unique_function<void()> uf = [checkerPtr = std::make_unique<Checker>()] {}; + mongo::unique_function<void()> uf = [checkerPtr = std::make_unique<Checker>()] { + }; mongo::unique_function<void()> uf2 = std::move(uf); @@ -363,7 +377,8 @@ TEST(UniqueFunctionTest, comparison_checks) { ASSERT_FALSE(uf != nullptr); ASSERT_FALSE(nullptr != uf); - uf = [] {}; + uf = [] { + }; ASSERT_FALSE(uf == nullptr); ASSERT_FALSE(nullptr == uf); @@ -381,8 +396,12 @@ TEST(UniqueFunctionTest, comparison_checks) { TEST(UniqueFunctionTest, simple_instantiations) { mongo::unique_function<void()> a; - mongo::unique_function<void()> x = []() -> int { return 42; }; - x = []() -> int { return 42; }; + mongo::unique_function<void()> x = []() -> int { + return 42; + }; + x = []() -> int { + return 42; + }; } TEST(FunctionRefTest, simple_instantiations) { @@ -776,7 +795,8 @@ bool accept(T arg, U) { } TEST(UniqueFunctionTest, functionDominanceExample) { - mongo::unique_function<void()> uf = [] {}; + mongo::unique_function<void()> uf = [] { + }; ASSERT_TRUE(accept(std::move(uf), nullptr)); } diff --git a/src/mongo/util/future.h b/src/mongo/util/future.h index 364759962d7..63eddbcbff0 100644 --- a/src/mongo/util/future.h +++ b/src/mongo/util/future.h @@ -203,8 +203,8 @@ public: * * Returns a non-okay status if the interruptible is interrupted. */ - Status waitNoThrow(Interruptible* interruptible = Interruptible::notInterruptible()) const - noexcept { + Status waitNoThrow( + Interruptible* interruptible = Interruptible::notInterruptible()) const noexcept { return _impl.waitNoThrow(interruptible); } @@ -231,8 +231,7 @@ public: return _impl.get(interruptible); } StatusOrStatusWith<T> getNoThrow( - Interruptible* interruptible = Interruptible::notInterruptible()) && - noexcept { + Interruptible* interruptible = Interruptible::notInterruptible()) && noexcept { return std::move(_impl).getNoThrow(interruptible); } StatusOrStatusWith<T> getNoThrow( @@ -284,7 +283,7 @@ private: : _impl(std::move(impl)) {} explicit SemiFuture(Impl&& impl) : _impl(std::move(impl)) {} - operator Impl &&() && { + operator Impl&&() && { return std::move(_impl); } @@ -301,7 +300,7 @@ TEMPLATE(typename T) REQUIRES(!isStatusOrStatusWith<T> && !future_details::isFutureLike<T>) SemiFuture(T)->SemiFuture<T>; template <typename T> -SemiFuture(StatusWith<T>)->SemiFuture<T>; +SemiFuture(StatusWith<T>) -> SemiFuture<T>; /** * Future<T> is a SemiFuture<T> (which is logically a possibly deferred StatusOrStatusWith<T>), @@ -612,7 +611,7 @@ TEMPLATE(typename T) REQUIRES(!isStatusOrStatusWith<T> && !future_details::isFutureLike<T>) Future(T)->Future<T>; template <typename T> -Future(StatusWith<T>)->Future<T>; +Future(StatusWith<T>) -> Future<T>; /** * An ExecutorFuture is like a Future that ensures that all callbacks are run on a supplied @@ -700,16 +699,18 @@ public: // Can't use wrapCB since we don't want to return a future, just schedule a non-chainable // callback. - std::move(this->_impl).getAsync(policy, [ - exec = std::move(_exec), // Unlike wrapCB this can move because we won't need it later. - func = std::forward<Func>(func) - ](StatusOrStatusWith<T> arg) mutable noexcept { - exec->schedule([ func = std::move(func), - arg = std::move(arg) ](Status execStatus) mutable noexcept { - if (execStatus.isOK()) - func(std::move(arg)); - }); - }); + std::move(this->_impl) + .getAsync( + policy, + [exec = std::move( + _exec), // Unlike wrapCB this can move because we won't need it later. + func = std::forward<Func>(func)](StatusOrStatusWith<T> arg) mutable noexcept { + exec->schedule([func = std::move(func), + arg = std::move(arg)](Status execStatus) mutable noexcept { + if (execStatus.isOK()) + func(std::move(arg)); + }); + }); } TEMPLATE(typename Policy, typename Func) @@ -851,9 +852,9 @@ TEMPLATE(typename T) REQUIRES(!isStatusOrStatusWith<T> && !future_details::isFutureLike<T>) ExecutorFuture(ExecutorPtr, T)->ExecutorFuture<T>; template <typename T> -ExecutorFuture(ExecutorPtr, future_details::FutureImpl<T>)->ExecutorFuture<T>; +ExecutorFuture(ExecutorPtr, future_details::FutureImpl<T>) -> ExecutorFuture<T>; template <typename T> -ExecutorFuture(ExecutorPtr, StatusWith<T>)->ExecutorFuture<T>; +ExecutorFuture(ExecutorPtr, StatusWith<T>) -> ExecutorFuture<T>; ExecutorFuture(ExecutorPtr)->ExecutorFuture<void>; /** Constructor tag (see the corresponding `Promise` constructor). */ @@ -1094,8 +1095,8 @@ public: _shared.wait(interruptible); } - Status waitNoThrow(Interruptible* interruptible = Interruptible::notInterruptible()) const - noexcept { + Status waitNoThrow( + Interruptible* interruptible = Interruptible::notInterruptible()) const noexcept { return _shared.waitNoThrow(interruptible); } @@ -1170,7 +1171,7 @@ TEMPLATE(typename T) REQUIRES(!isStatusOrStatusWith<T> && !future_details::isFutureLike<T>) SharedSemiFuture(T)->SharedSemiFuture<T>; template <typename T> -SharedSemiFuture(StatusWith<T>)->SharedSemiFuture<T>; +SharedSemiFuture(StatusWith<T>) -> SharedSemiFuture<T>; /** * This class represents the producer of SharedSemiFutures. @@ -1360,23 +1361,24 @@ auto makeReadyFutureWith(Func&& func) -> Future<FutureContinuationResult<Func&&> template <typename T> template <typename UniqueFunc> auto ExecutorFuture<T>::_wrapCBHelper(ExecutorPtr exec, UniqueFunc&& func) { - return [ exec = std::move(exec), func = std::move(func) ](auto&&... args) mutable noexcept { + return [exec = std::move(exec), func = std::move(func)](auto&&... args) mutable noexcept { using FuncR = typename UniqueFunc::result_type; using BoundArgs = std::tuple<std::decay_t<decltype(args)>...>; Promise<future_details::UnwrappedType<FuncR>> promise{NonNullPromiseTag{}}; auto future = promise.getFuture(); - exec->schedule([ - promise = std::move(promise), - func = std::move(func), - boundArgs = BoundArgs{std::forward<decltype(args)>(args)...} - ](Status execStatus) mutable noexcept { + exec->schedule([promise = std::move(promise), + func = std::move(func), + boundArgs = BoundArgs{std::forward<decltype(args)>(args)...}]( + Status execStatus) mutable noexcept { if (!execStatus.isOK()) { promise.setError(std::move(execStatus)); return; } promise.setWith([&] { - auto closure = [&] { return std::apply(func, std::move(boundArgs)); }; + auto closure = [&] { + return std::apply(func, std::move(boundArgs)); + }; if constexpr (future_details::isFutureLike<FuncR>) { // Cheat and convert to an inline Future since we know we will schedule // further user callbacks onto an executor. @@ -1392,18 +1394,18 @@ auto ExecutorFuture<T>::_wrapCBHelper(ExecutorPtr exec, UniqueFunc&& func) { } template <typename T> - ExecutorFuture<T> SemiFuture<T>::thenRunOn(ExecutorPtr exec) && noexcept { +ExecutorFuture<T> SemiFuture<T>::thenRunOn(ExecutorPtr exec) && noexcept { return ExecutorFuture<T>(std::move(exec), std::move(_impl)); } template <typename T> - Future<T> SemiFuture<T>::unsafeToInlineFuture() && noexcept { +Future<T> SemiFuture<T>::unsafeToInlineFuture() && noexcept { return Future<T>(std::move(_impl)); } namespace future_details { template <typename T> - SharedSemiFuture<FakeVoidToVoid<T>> FutureImpl<T>::share() && noexcept { +SharedSemiFuture<FakeVoidToVoid<T>> FutureImpl<T>::share() && noexcept { invariant(valid()); using Out = SharedSemiFuture<FakeVoidToVoid<T>>; if (_immediate) diff --git a/src/mongo/util/future_impl.h b/src/mongo/util/future_impl.h index ba0b096cf3d..940199e975c 100644 --- a/src/mongo/util/future_impl.h +++ b/src/mongo/util/future_impl.h @@ -796,7 +796,7 @@ public: explicit SharedStateHolder(boost::intrusive_ptr<SharedState<FakeVoid>>&& shared) : _inner(std::move(shared)) {} /*implicit*/ SharedStateHolder(Impl&& shared) : _inner(std::move(shared)) {} - /*implicit*/ operator Impl &&() && { + /*implicit*/ operator Impl&&() && { return std::move(_inner); } @@ -955,15 +955,15 @@ public: [&](Status&& status) { call(func, StatusWith<T>(std::move(status))); }, // on not ready yet: [&] { - _shared->callback = [func = std::forward<Func>(func)](SharedStateBase * - ssb) mutable noexcept { - const auto input = checked_cast<SharedState<T>*>(ssb); - if (input->status.isOK()) { - call(func, StatusWith<T>(std::move(*input->data))); - } else { - call(func, StatusWith<T>(std::move(input->status))); - } - }; + _shared->callback = + [func = std::forward<Func>(func)](SharedStateBase* ssb) mutable noexcept { + const auto input = checked_cast<SharedState<T>*>(ssb); + if (input->status.isOK()) { + call(func, StatusWith<T>(std::move(*input->data))); + } else { + call(func, StatusWith<T>(std::move(input->status))); + } + }; }); } @@ -981,13 +981,14 @@ public: [&](Status&& status) { return FutureImpl<Result>::makeReady(std::move(status)); }, // on not ready yet: [&] { - return makeContinuation<Result>([func = std::forward<Func>(func)]( - SharedState<T> * input, SharedState<Result> * output) mutable noexcept { - if (!input->status.isOK()) - return output->setError(std::move(input->status)); - - output->setFrom(statusCall(func, std::move(*input->data))); - }); + return makeContinuation<Result>( + [func = std::forward<Func>(func)]( + SharedState<T>* input, SharedState<Result>* output) mutable noexcept { + if (!input->status.isOK()) + return output->setError(std::move(input->status)); + + output->setFrom(statusCall(func, std::move(*input->data))); + }); }); } else { using UnwrappedResult = typename Result::value_type; @@ -1006,18 +1007,20 @@ public: }, // on not ready yet: [&] { - return makeContinuation<UnwrappedResult>([func = std::forward<Func>(func)]( - SharedState<T> * input, - SharedState<UnwrappedResult> * output) mutable noexcept { - if (!input->status.isOK()) - return output->setError(std::move(input->status)); + return makeContinuation<UnwrappedResult>( + [func = std::forward<Func>(func)]( + SharedState<T>* input, + SharedState<UnwrappedResult>* output) mutable noexcept { + if (!input->status.isOK()) + return output->setError(std::move(input->status)); - try { - throwingCall(func, std::move(*input->data)).propagateResultTo(output); - } catch (const DBException& ex) { - output->setError(ex.toStatus()); - } - }); + try { + throwingCall(func, std::move(*input->data)) + .propagateResultTo(output); + } catch (const DBException& ex) { + output->setError(ex.toStatus()); + } + }); }); } } @@ -1041,14 +1044,15 @@ public: }, // on not ready yet: [&] { - return makeContinuation<Result>([func = std::forward<Func>(func)]( - SharedState<T> * input, SharedState<Result> * output) mutable noexcept { - if (!input->status.isOK()) - return output->setFrom( - statusCall(func, Wrapper(std::move(input->status)))); - - output->setFrom(statusCall(func, Wrapper(std::move(*input->data)))); - }); + return makeContinuation<Result>( + [func = std::forward<Func>(func)]( + SharedState<T>* input, SharedState<Result>* output) mutable noexcept { + if (!input->status.isOK()) + return output->setFrom( + statusCall(func, Wrapper(std::move(input->status)))); + + output->setFrom(statusCall(func, Wrapper(std::move(*input->data)))); + }); }); } else { using UnwrappedResult = typename Result::value_type; @@ -1073,27 +1077,28 @@ public: }, // on not ready yet: [&] { - return makeContinuation<UnwrappedResult>([func = std::forward<Func>(func)]( - SharedState<T> * input, - SharedState<UnwrappedResult> * output) mutable noexcept { - if (!input->status.isOK()) { + return makeContinuation<UnwrappedResult>( + [func = std::forward<Func>(func)]( + SharedState<T>* input, + SharedState<UnwrappedResult>* output) mutable noexcept { + if (!input->status.isOK()) { + try { + throwingCall(func, Wrapper(std::move(input->status))) + .propagateResultTo(output); + } catch (const DBException& ex) { + output->setError(ex.toStatus()); + } + + return; + } + try { - throwingCall(func, Wrapper(std::move(input->status))) + throwingCall(func, Wrapper(std::move(*input->data))) .propagateResultTo(output); } catch (const DBException& ex) { output->setError(ex.toStatus()); } - - return; - } - - try { - throwingCall(func, Wrapper(std::move(*input->data))) - .propagateResultTo(output); - } catch (const DBException& ex) { - output->setError(ex.toStatus()); - } - }); + }); }); } } @@ -1116,13 +1121,14 @@ public: }, // on not ready yet: [&] { - return makeContinuation<T>([func = std::forward<Func>(func)]( - SharedState<T> * input, SharedState<T> * output) mutable noexcept { - if (input->status.isOK()) - return output->emplaceValue(std::move(*input->data)); - - output->setFrom(statusCall(func, std::move(input->status))); - }); + return makeContinuation<T>( + [func = std::forward<Func>(func)](SharedState<T>* input, + SharedState<T>* output) mutable noexcept { + if (input->status.isOK()) + return output->emplaceValue(std::move(*input->data)); + + output->setFrom(statusCall(func, std::move(input->status))); + }); }); } else { return generalImpl( @@ -1139,7 +1145,8 @@ public: // on not ready yet: [&] { return makeContinuation<T>([func = std::forward<Func>(func)]( - SharedState<T> * input, SharedState<T> * output) mutable noexcept { + SharedState<T>* input, + SharedState<T>* output) mutable noexcept { if (input->status.isOK()) return output->emplaceValue(std::move(*input->data)); @@ -1199,9 +1206,10 @@ public: static_assert(std::is_void<decltype(call(func, std::declval<const T&>()))>::value, "func passed to tap must return void"); - return tapImpl(std::forward<Func>(func), - [](Func && successFunc, const T& val) noexcept { call(successFunc, val); }, - [](Func && failFunc, const Status& status) noexcept {}); + return tapImpl( + std::forward<Func>(func), + [](Func&& successFunc, const T& val) noexcept { call(successFunc, val); }, + [](Func&& failFunc, const Status& status) noexcept {}); } TEMPLATE(typename Policy, typename Func) @@ -1211,8 +1219,9 @@ public: "func passed to tapError must return void"); return tapImpl( - std::forward<Func>(func), [](Func && successFunc, const T& val) noexcept {}, [ - ](Func && failFunc, const Status& status) noexcept { call(failFunc, status); }); + std::forward<Func>(func), + [](Func&& successFunc, const T& val) noexcept {}, + [](Func&& failFunc, const Status& status) noexcept { call(failFunc, status); }); } TEMPLATE(typename Policy, typename Func) @@ -1225,8 +1234,8 @@ public: using Wrapper = StatusOrStatusWith<T>; return tapImpl( std::forward<Func>(func), - [](Func && successFunc, const T& val) noexcept { call(successFunc, Wrapper(val)); }, - [](Func && failFunc, const Status& status) noexcept { + [](Func&& successFunc, const T& val) noexcept { call(successFunc, Wrapper(val)); }, + [](Func&& failFunc, const Status& status) noexcept { call(failFunc, Wrapper(status)); }); } @@ -1254,7 +1263,7 @@ public: } _shared->isJustForContinuation.store(true, std::memory_order_release); - _shared->callback = [](SharedStateBase * ssb) noexcept { + _shared->callback = [](SharedStateBase* ssb) noexcept { const auto input = checked_cast<SharedState<T>*>(ssb); const auto output = checked_cast<SharedState<T>*>(ssb->continuation.get()); output->fillFromMove(std::move(*input)); @@ -1327,16 +1336,17 @@ private: return FutureImpl<T>::makeReady(std::move(status)); }, [&] { - return makeContinuation<T>([ success, fail, cb = std::forward<Callback>(cb) ]( - SharedState<T> * input, SharedState<T> * output) mutable noexcept { - if (input->status.isOK()) { - success(std::forward<Callback>(cb), stdx::as_const(*input->data)); - } else { - fail(std::forward<Callback>(cb), stdx::as_const(input->status)); - } + return makeContinuation<T>( + [success, fail, cb = std::forward<Callback>(cb)]( + SharedState<T>* input, SharedState<T>* output) mutable noexcept { + if (input->status.isOK()) { + success(std::forward<Callback>(cb), stdx::as_const(*input->data)); + } else { + fail(std::forward<Callback>(cb), stdx::as_const(input->status)); + } - output->fillFromMove(std::move(*input)); - }); + output->fillFromMove(std::move(*input)); + }); }); } @@ -1347,12 +1357,12 @@ private: auto continuation = make_intrusive<SharedState<Result>>(); continuation->threadUnsafeIncRefCountTo(2); _shared->continuation.reset(continuation.get(), /*add ref*/ false); - _shared->callback = [onReady = std::forward<OnReady>(onReady)](SharedStateBase * - ssb) mutable noexcept { - const auto input = checked_cast<SharedState<T>*>(ssb); - const auto output = checked_cast<SharedState<Result>*>(ssb->continuation.get()); - onReady(input, output); - }; + _shared->callback = + [onReady = std::forward<OnReady>(onReady)](SharedStateBase* ssb) mutable noexcept { + const auto input = checked_cast<SharedState<T>*>(ssb); + const auto output = checked_cast<SharedState<Result>*>(ssb->continuation.get()); + onReady(input, output); + }; return FutureImpl<Result>(SharedStateHolder<Result>(std::move(continuation))); } @@ -1455,7 +1465,7 @@ private: }; template <typename T> - inline FutureImpl<void> FutureImpl<T>::ignoreValue() && noexcept { +inline FutureImpl<void> FutureImpl<T>::ignoreValue() && noexcept { return std::move(*this).then(destroyDefault, [](auto&&) {}); } diff --git a/src/mongo/util/future_test_shared_future.cpp b/src/mongo/util/future_test_shared_future.cpp index fb0a984efb2..19f494c9c60 100644 --- a/src/mongo/util/future_test_shared_future.cpp +++ b/src/mongo/util/future_test_shared_future.cpp @@ -68,8 +68,7 @@ TEST(SharedFuture, isReady_shared_TSAN_OK) { auto fut = async([&] { done = true; return 1; - }) - .share(); + }).share(); //(void)*const_cast<volatile bool*>(&done); // Data Race! Uncomment to make sure TSAN works. while (!fut.isReady()) { } @@ -298,7 +297,9 @@ public: TEST(SharedFuture, ConcurrentTest_Simple) { SharedPromise<void> promise; auto shared = promise.getFuture(); - JoinThread thread{stdx::thread{[&] { shared.get(); }}}; + JoinThread thread{stdx::thread{[&] { + shared.get(); + }}}; stdx::this_thread::yield(); // Slightly increase the chance of racing. promise.emplaceValue(); } diff --git a/src/mongo/util/future_test_utils.h b/src/mongo/util/future_test_utils.h index ec7bd783030..c1695c3e392 100644 --- a/src/mongo/util/future_test_utils.h +++ b/src/mongo/util/future_test_utils.h @@ -113,8 +113,7 @@ Future<Result> async(Func&& func) { } catch (const DBException& ex) { promise.setError(ex.toStatus()); } - }) - .detach(); + }).detach(); return std::move(pf.future); } diff --git a/src/mongo/util/future_util.h b/src/mongo/util/future_util.h index 33df5e06bcf..5753a3d74e5 100644 --- a/src/mongo/util/future_util.h +++ b/src/mongo/util/future_util.h @@ -127,8 +127,7 @@ private: template <typename BodyCallable, typename ConditionCallable, typename Delay> class [[nodiscard]] AsyncTryUntilWithDelay { public: - explicit AsyncTryUntilWithDelay( - BodyCallable && body, ConditionCallable && condition, Delay delay) + explicit AsyncTryUntilWithDelay(BodyCallable&& body, ConditionCallable&& condition, Delay delay) : _body(std::move(body)), _condition(std::move(condition)), _delay(delay) {} /** @@ -146,7 +145,7 @@ public: * that readies the returned future when the given duration has elapsed or token cancelled. */ template <typename SleepableExecutor> - auto on(SleepableExecutor executor, CancellationToken cancelToken)&& { + auto on(SleepableExecutor executor, CancellationToken cancelToken) && { auto loop = std::make_shared<TryUntilLoopWithDelay<SleepableExecutor>>(std::move(executor), std::move(_body), @@ -278,7 +277,7 @@ private: template <typename BodyCallable, typename ConditionCallable> class [[nodiscard]] AsyncTryUntil { public: - explicit AsyncTryUntil(BodyCallable && body, ConditionCallable && condition) + explicit AsyncTryUntil(BodyCallable&& body, ConditionCallable&& condition) : _body(std::move(body)), _condition(std::move(condition)) {} /** @@ -286,7 +285,7 @@ public: * loop body. */ template <typename DurationType> - auto withDelayBetweenIterations(DurationType delay)&& { + auto withDelayBetweenIterations(DurationType delay) && { return AsyncTryUntilWithDelay( std::move(_body), std::move(_condition), ConstDelay<DurationType>(std::move(delay))); } @@ -296,7 +295,7 @@ public: * executing the loop body. */ template <typename BackoffType> - auto withBackoffBetweenIterations(BackoffType backoff)&& { + auto withBackoffBetweenIterations(BackoffType backoff) && { return AsyncTryUntilWithDelay( std::move(_body), std::move(_condition), BackoffDelay<BackoffType>(std::move(backoff))); } @@ -311,7 +310,7 @@ public: * iteration of the loop body threw an exception or otherwise returned an error status, the * returned ExecutorFuture will contain that error. */ - auto on(ExecutorPtr executor, CancellationToken cancelToken)&& { + auto on(ExecutorPtr executor, CancellationToken cancelToken) && { auto loop = std::make_shared<TryUntilLoop>( std::move(executor), std::move(_body), std::move(_condition), std::move(cancelToken)); // Launch the recursive chain using the helper class. @@ -480,10 +479,10 @@ std::vector<T> variadicArgsToVector(U&&... elems) { template <typename Callable> class [[nodiscard]] AsyncTry { public: - explicit AsyncTry(Callable && callable) : _body(std::move(callable)) {} + explicit AsyncTry(Callable&& callable) : _body(std::move(callable)) {} template <typename Condition> - auto until(Condition && condition)&& { + auto until(Condition&& condition) && { return future_util_details::AsyncTryUntil(std::move(_body), std::move(condition)); } @@ -824,7 +823,7 @@ public: * running the launcher. */ template <typename Launcher> - auto thenWithState(Launcher && launcher) && noexcept { + auto thenWithState(Launcher&& launcher) && noexcept { using namespace future_details; using ReturnType = FutureFor<NormalizedCallResult<Launcher, State*>>; @@ -849,7 +848,7 @@ public: * If an exception would be emitted, it is instead stored in the AsyncState. */ template <typename... Args> - static auto make(Args && ... args) noexcept { + static auto make(Args&&... args) noexcept { try { auto ptr = std::make_unique<State>(std::forward<Args>(args)...); return AsyncState(std::move(ptr)); diff --git a/src/mongo/util/future_util_test.cpp b/src/mongo/util/future_util_test.cpp index 30021ed9be4..ddebedff12e 100644 --- a/src/mongo/util/future_util_test.cpp +++ b/src/mongo/util/future_util_test.cpp @@ -88,9 +88,11 @@ using AsyncTryUntilTest = FutureUtilTest; TEST_F(AsyncTryUntilTest, LoopExecutesOnceWithAlwaysTrueCondition) { auto i = 0; - auto resultFut = AsyncTry([&] { ++i; }) - .until([](Status s) { return true; }) - .on(executor(), CancellationToken::uncancelable()); + auto resultFut = AsyncTry([&] { + ++i; + }).until([](Status s) { + return true; + }).on(executor(), CancellationToken::uncancelable()); resultFut.wait(); ASSERT_EQ(i, 1); @@ -100,9 +102,11 @@ TEST_F(AsyncTryUntilTest, LoopDoesNotExecuteIfExecutorAlreadyShutdown) { executor()->shutdown(); auto i = 0; - auto resultFut = AsyncTry([&] { ++i; }) - .until([](Status s) { return true; }) - .on(executor(), CancellationToken::uncancelable()); + auto resultFut = AsyncTry([&] { + ++i; + }).until([](Status s) { + return true; + }).on(executor(), CancellationToken::uncancelable()); ASSERT_THROWS_CODE(resultFut.get(), DBException, ErrorCodes::ShutdownInProgress); @@ -115,9 +119,9 @@ TEST_F(AsyncTryUntilTest, LoopDoesNotReturnBrokenPromiseIfExecutorShutdownWhileL auto resultFut = AsyncTry([&] { barrierBeforeShutdown.countDownAndWait(); barrierAfterShutdown.countDownAndWait(); - }) - .until([](Status) { return false; }) - .on(executor(), CancellationToken::uncancelable()); + }).until([](Status) { + return false; + }).on(executor(), CancellationToken::uncancelable()); barrierBeforeShutdown.countDownAndWait(); executor()->shutdown(); barrierAfterShutdown.countDownAndWait(); @@ -163,9 +167,9 @@ TEST_F(AsyncTryUntilTest, LoopExecutesUntilConditionIsTrue) { auto resultFut = AsyncTry([&] { ++i; return i; - }) - .until([&](StatusWith<int> swInt) { return swInt.getValue() == numLoops; }) - .on(executor(), CancellationToken::uncancelable()); + }).until([&](StatusWith<int> swInt) { + return swInt.getValue() == numLoops; + }).on(executor(), CancellationToken::uncancelable()); resultFut.wait(); ASSERT_EQ(i, numLoops); @@ -177,9 +181,9 @@ TEST_F(AsyncTryUntilTest, LoopExecutesUntilConditionIsTrueWithFutureReturnType) auto resultFut = AsyncTry([&] { ++i; return Future<int>::makeReady(i); - }) - .until([&](StatusWith<int> swInt) { return swInt.getValue() == numLoops; }) - .on(executor(), CancellationToken::uncancelable()); + }).until([&](StatusWith<int> swInt) { + return swInt.getValue() == numLoops; + }).on(executor(), CancellationToken::uncancelable()); resultFut.wait(); ASSERT_EQ(i, numLoops); @@ -191,9 +195,9 @@ TEST_F(AsyncTryUntilTest, LoopExecutesUntilConditionIsTrueWithSemiFutureReturnTy auto resultFut = AsyncTry([&] { ++i; return SemiFuture<int>::makeReady(i); - }) - .until([&](StatusWith<int> swInt) { return swInt.getValue() == numLoops; }) - .on(executor(), CancellationToken::uncancelable()); + }).until([&](StatusWith<int> swInt) { + return swInt.getValue() == numLoops; + }).on(executor(), CancellationToken::uncancelable()); resultFut.wait(); ASSERT_EQ(i, numLoops); @@ -205,9 +209,9 @@ TEST_F(AsyncTryUntilTest, LoopExecutesUntilConditionIsTrueWithExecutorFutureRetu auto resultFut = AsyncTry([&] { ++i; return ExecutorFuture<int>(executor(), i); - }) - .until([&](StatusWith<int> swInt) { return swInt.getValue() == numLoops; }) - .on(executor(), CancellationToken::uncancelable()); + }).until([&](StatusWith<int> swInt) { + return swInt.getValue() == numLoops; + }).on(executor(), CancellationToken::uncancelable()); resultFut.wait(); ASSERT_EQ(i, numLoops); @@ -324,9 +328,9 @@ TEST_F(AsyncTryUntilTest, LoopBodyPropagatesValueOfLastIterationToCaller) { auto resultFut = AsyncTry([&] { ++i; return i; - }) - .until([&](StatusWith<int> swInt) { return i == expectedResult; }) - .on(executor(), CancellationToken::uncancelable()); + }).until([&](StatusWith<int> swInt) { + return i == expectedResult; + }).on(executor(), CancellationToken::uncancelable()); ASSERT_EQ(resultFut.get(), expectedResult); } @@ -337,9 +341,9 @@ TEST_F(AsyncTryUntilTest, FutureReturningLoopBodyPropagatesValueOfLastIterationT auto resultFut = AsyncTry([&] { ++i; return Future<int>::makeReady(i); - }) - .until([&](StatusWith<int> swInt) { return i == expectedResult; }) - .on(executor(), CancellationToken::uncancelable()); + }).until([&](StatusWith<int> swInt) { + return i == expectedResult; + }).on(executor(), CancellationToken::uncancelable()); ASSERT_EQ(resultFut.get(), expectedResult); } @@ -350,9 +354,9 @@ TEST_F(AsyncTryUntilTest, SemiFutureReturningLoopBodyPropagatesValueOfLastIterat auto resultFut = AsyncTry([&] { ++i; return SemiFuture<int>::makeReady(i); - }) - .until([&](StatusWith<int> swInt) { return i == expectedResult; }) - .on(executor(), CancellationToken::uncancelable()); + }).until([&](StatusWith<int> swInt) { + return i == expectedResult; + }).on(executor(), CancellationToken::uncancelable()); ASSERT_EQ(resultFut.get(), expectedResult); } @@ -363,9 +367,9 @@ TEST_F(AsyncTryUntilTest, ExecutorFutureReturningLoopBodyPropagatesValueOfLastIt auto resultFut = AsyncTry([&] { ++i; return ExecutorFuture<int>(executor(), i); - }) - .until([&](StatusWith<int> swInt) { return i == expectedResult; }) - .on(executor(), CancellationToken::uncancelable()); + }).until([&](StatusWith<int> swInt) { + return i == expectedResult; + }).on(executor(), CancellationToken::uncancelable()); ASSERT_EQ(resultFut.get(), expectedResult); } @@ -541,9 +545,11 @@ TEST_F(AsyncTryUntilTest, CanceledTryUntilLoopDoesNotExecuteIfAlreadyCanceled) { CancellationSource cancelSource; auto canceledToken = cancelSource.token(); cancelSource.cancel(); - auto resultFut = AsyncTry([&] { ++counter; }) - .until([](Status) { return false; }) - .on(executor(), canceledToken); + auto resultFut = AsyncTry([&] { + ++counter; + }).until([](Status) { + return false; + }).on(executor(), canceledToken); ASSERT_EQ(resultFut.getNoThrow(), kCanceledStatus); ASSERT_EQ(counter, 0); } @@ -576,9 +582,10 @@ TEST_F(AsyncTryUntilTest, CanceledTryUntilLoopWithBackoffDoesNotExecuteIfAlready TEST_F(AsyncTryUntilTest, UntilBodyPropagatesErrorToCaller) { const auto error = Status(ErrorCodes::InternalError, "Some error"); - auto resultFut = AsyncTry([] {}) - .until([&](Status status) -> bool { iasserted(error); }) - .on(executor(), CancellationToken::uncancelable()); + auto resultFut = AsyncTry([] { + }).until([&](Status status) -> bool { + iasserted(error); + }).on(executor(), CancellationToken::uncancelable()); ASSERT_EQ(resultFut.getNoThrow(), error); } diff --git a/src/mongo/util/heap_profiler.cpp b/src/mongo/util/heap_profiler.cpp index 0f58c155c65..08f47243773 100644 --- a/src/mongo/util/heap_profiler.cpp +++ b/src/mongo/util/heap_profiler.cpp @@ -629,7 +629,9 @@ private: // Sort the stacks and find enough stacks to account for at least 99% of the active bytes // deem any stack that has ever met this criterion as "important". // Using heap structure to avoid comparing elements that won't make the cut anyway. - auto heapCompare = [](auto&& a, auto&& b) { return a.activeBytes > b.activeBytes; }; + auto heapCompare = [](auto&& a, auto&& b) { + return a.activeBytes > b.activeBytes; + }; std::make_heap(heap.begin(), heapEnd, heapCompare); size_t threshold = totalActiveBytes * 0.99; diff --git a/src/mongo/util/histogram_test.cpp b/src/mongo/util/histogram_test.cpp index 2e883335b6a..8b79b00c5c7 100644 --- a/src/mongo/util/histogram_test.cpp +++ b/src/mongo/util/histogram_test.cpp @@ -49,7 +49,9 @@ public: boost::optional<T> lower, upper; friend bool operator==(const BucketSpec& a, const BucketSpec& b) { - auto lens = [](auto&& x) { return std::tie(x.count, x.lower, x.upper); }; + auto lens = [](auto&& x) { + return std::tie(x.count, x.lower, x.upper); + }; return lens(a) == lens(b); } diff --git a/src/mongo/util/lockable_adapter.h b/src/mongo/util/lockable_adapter.h index 83999b34c3f..895388e10e4 100644 --- a/src/mongo/util/lockable_adapter.h +++ b/src/mongo/util/lockable_adapter.h @@ -65,7 +65,9 @@ private: template <typename T> static inline VTable forT = VTable{+[](void* t) { static_cast<T*>(t)->lock(); }, - +[](void* t) { static_cast<T*>(t)->unlock(); }}; + +[](void* t) { + static_cast<T*>(t)->unlock(); + }}; void* _underlyingLock; const VTable* _vtable; diff --git a/src/mongo/util/lru_cache.h b/src/mongo/util/lru_cache.h index 0e70642dec2..6726f555345 100644 --- a/src/mongo/util/lru_cache.h +++ b/src/mongo/util/lru_cache.h @@ -67,9 +67,9 @@ struct KeyConstraints { template <typename Hasher, typename Comparator, typename T, typename TT> inline constexpr bool IsComparableWith = - decltype(KeyConstraints<Hasher, Comparator>::IsHashable(std::declval<TT>()))::value&& decltype( - KeyConstraints<Hasher, Comparator>::IsComparable(std::declval<T>(), - std::declval<TT>()))::value; + decltype(KeyConstraints<Hasher, Comparator>::IsHashable(std::declval<TT>())):: + value&& decltype(KeyConstraints<Hasher, Comparator>::IsComparable( + std::declval<T>(), std::declval<TT>()))::value; template <typename K, diff --git a/src/mongo/util/net/hostname_canonicalization.cpp b/src/mongo/util/net/hostname_canonicalization.cpp index f02f5b0b330..7ec98fa49f2 100644 --- a/src/mongo/util/net/hostname_canonicalization.cpp +++ b/src/mongo/util/net/hostname_canonicalization.cpp @@ -57,16 +57,24 @@ StatusWith<std::vector<std::string>> getHostFQDNs(std::string hostName, using shim_addrinfo = struct addrinfo; shim_addrinfo* info = nullptr; const auto& shim_getaddrinfo = getaddrinfo; - const auto& shim_freeaddrinfo = [&info] { freeaddrinfo(info); }; + const auto& shim_freeaddrinfo = [&info] { + freeaddrinfo(info); + }; const auto& shim_getnameinfo = getnameinfo; - const auto& shim_toNativeString = [](const char* str) { return std::string(str); }; - const auto& shim_fromNativeString = [](const std::string& str) { return str; }; + const auto& shim_toNativeString = [](const char* str) { + return std::string(str); + }; + const auto& shim_fromNativeString = [](const std::string& str) { + return str; + }; #else using shim_char = wchar_t; using shim_addrinfo = struct addrinfoW; shim_addrinfo* info = nullptr; const auto& shim_getaddrinfo = GetAddrInfoW; - const auto& shim_freeaddrinfo = [&info] { FreeAddrInfoW(info); }; + const auto& shim_freeaddrinfo = [&info] { + FreeAddrInfoW(info); + }; const auto& shim_getnameinfo = GetNameInfoW; const auto& shim_toNativeString = toWideString; const auto& shim_fromNativeString = toUtf8String; diff --git a/src/mongo/util/net/sock.cpp b/src/mongo/util/net/sock.cpp index d5bb6635e1c..a110785decf 100644 --- a/src/mongo/util/net/sock.cpp +++ b/src/mongo/util/net/sock.cpp @@ -688,14 +688,14 @@ bool Socket::isStillConnected() { int nEvents = socketPoll(&pollInfo, 1, 0); auto ec = lastSocketError(); - LOGV2_DEBUG( - 23186, - 2, - "polling for status of connection to {remoteHost}, {errorOrEventDetected}", - "Polling for status of connection to remote host", - "remoteHost"_attr = remoteString(), - "errorOrEventDetected"_attr = - (nEvents == 0 ? "no events" : nEvents == -1 ? "error detected" : "event detected")); + LOGV2_DEBUG(23186, + 2, + "polling for status of connection to {remoteHost}, {errorOrEventDetected}", + "Polling for status of connection to remote host", + "remoteHost"_attr = remoteString(), + "errorOrEventDetected"_attr = (nEvents == 0 ? "no events" + : nEvents == -1 ? "error detected" + : "event detected")); if (nEvents == 0) { // No events incoming, return still connected AFAWK diff --git a/src/mongo/util/net/ssl_manager.cpp b/src/mongo/util/net/ssl_manager.cpp index 7d94fa88f05..98c7a7a447a 100644 --- a/src/mongo/util/net/ssl_manager.cpp +++ b/src/mongo/util/net/ssl_manager.cpp @@ -154,11 +154,15 @@ std::string RFC4514Parser::extractAttributeName() { // If the first character is a digit, then this is an OID and can only contain // numbers and '.' if (ctype::isDigit(ch)) { - characterCheck = [](char ch) { return ctype::isDigit(ch) || ch == '.'; }; + characterCheck = [](char ch) { + return ctype::isDigit(ch) || ch == '.'; + }; // If the first character is an alpha, then this is a short name and can only // contain alpha/digit/hyphen characters. } else if (ctype::isAlpha(ch)) { - characterCheck = [](char ch) { return ctype::isAlnum(ch) || ch == '-'; }; + characterCheck = [](char ch) { + return ctype::isAlnum(ch) || ch == '-'; + }; // Otherwise this is an invalid attribute name } else { uasserted(ErrorCodes::BadValue, diff --git a/src/mongo/util/net/ssl_manager_openssl.cpp b/src/mongo/util/net/ssl_manager_openssl.cpp index 6e2eefebf9b..361b8a78c89 100644 --- a/src/mongo/util/net/ssl_manager_openssl.cpp +++ b/src/mongo/util/net/ssl_manager_openssl.cpp @@ -1187,13 +1187,10 @@ private: const ServiceContext::Decoration<boost::optional<OCSPCache>> OCSPCache::getOCSPCache = ServiceContext::declareDecoration<boost::optional<OCSPCache>>(); -ServiceContext::ConstructorActionRegisterer OCSPCacheRegisterer("CreateOCSPCache", - [](ServiceContext* context) { - OCSPCache::create(context); - }, - [](ServiceContext* context) { - OCSPCache::destroy(context); - }); +ServiceContext::ConstructorActionRegisterer OCSPCacheRegisterer( + "CreateOCSPCache", + [](ServiceContext* context) { OCSPCache::create(context); }, + [](ServiceContext* context) { OCSPCache::destroy(context); }); using OCSPCacheVal = OCSPCache::ValueHandle; diff --git a/src/mongo/util/net/ssl_manager_test.cpp b/src/mongo/util/net/ssl_manager_test.cpp index 9f0751c9774..54b9dcef77b 100644 --- a/src/mongo/util/net/ssl_manager_test.cpp +++ b/src/mongo/util/net/ssl_manager_test.cpp @@ -522,9 +522,12 @@ TEST(SSLManager, InitContextFromFileShouldFail) { params.sslCAFile = "jstests/libs/ca.pem"; params.sslClusterFile = "jstests/libs/client.pem"; #if MONGO_CONFIG_SSL_PROVIDER == MONGO_CONFIG_SSL_PROVIDER_OPENSSL - ASSERT_THROWS_CODE([¶ms] { SSLManagerInterface::create(params, true /* isSSLServer */); }(), - DBException, - ErrorCodes::InvalidSSLConfiguration); + ASSERT_THROWS_CODE( + [¶ms] { + SSLManagerInterface::create(params, true /* isSSLServer */); + }(), + DBException, + ErrorCodes::InvalidSSLConfiguration); #endif } diff --git a/src/mongo/util/optional_util.h b/src/mongo/util/optional_util.h index dca4ab7b7c4..dbddce76a18 100644 --- a/src/mongo/util/optional_util.h +++ b/src/mongo/util/optional_util.h @@ -136,7 +136,7 @@ private: }; template <typename T, std::enable_if_t<canStreamWithExtension<T>, int> = 0> -Extension(const T& t)->Extension<T>; +Extension(const T& t) -> Extension<T>; } // namespace optional_io } // namespace mongo diff --git a/src/mongo/util/overloaded_visitor.h b/src/mongo/util/overloaded_visitor.h index 4ffad22d50a..a538aecc9bb 100644 --- a/src/mongo/util/overloaded_visitor.h +++ b/src/mongo/util/overloaded_visitor.h @@ -47,6 +47,6 @@ struct OverloadedVisitor : Ts... { using Ts::operator()...; }; template <typename... Ts> -OverloadedVisitor(Ts...)->OverloadedVisitor<Ts...>; +OverloadedVisitor(Ts...) -> OverloadedVisitor<Ts...>; } // namespace mongo diff --git a/src/mongo/util/overloaded_visitor_test.cpp b/src/mongo/util/overloaded_visitor_test.cpp index 0a900471162..32a2fb376bb 100644 --- a/src/mongo/util/overloaded_visitor_test.cpp +++ b/src/mongo/util/overloaded_visitor_test.cpp @@ -40,12 +40,11 @@ namespace { TEST(OverloadedVisitorTest, StdxVisit) { auto doVisit = [&](const stdx::variant<int, std::string>& var) { - return stdx::visit( - OverloadedVisitor{ - [](int v) { return 1; }, - [](const std::string& v) { return 2; }, - }, - var); + return stdx::visit(OverloadedVisitor{ + [](int v) { return 1; }, + [](const std::string& v) { return 2; }, + }, + var); }; ASSERT_EQ(doVisit(123), 1); ASSERT_EQ(doVisit(std::string("hi")), 2); @@ -53,12 +52,11 @@ TEST(OverloadedVisitorTest, StdxVisit) { TEST(OverloadedVisitorTest, Fallback) { auto doVisit = [&](const stdx::variant<int, std::string>& var) { - return stdx::visit( - OverloadedVisitor{ - [](int v) { return 1; }, - [](auto&& v) { return 2; }, - }, - var); + return stdx::visit(OverloadedVisitor{ + [](int v) { return 1; }, + [](auto&& v) { return 2; }, + }, + var); }; ASSERT_EQ(doVisit(123), 1); ASSERT_EQ(doVisit(std::string("hi")), 2); @@ -66,13 +64,12 @@ TEST(OverloadedVisitorTest, Fallback) { TEST(OverloadedVisitorTest, IntegerRank) { auto doVisit = [&](const stdx::variant<int, long, long long>& var) { - return stdx::visit( - OverloadedVisitor{ - [](long long v) { return 1; }, - [](long v) { return 2; }, - [](int v) { return 3; }, - }, - var); + return stdx::visit(OverloadedVisitor{ + [](long long v) { return 1; }, + [](long v) { return 2; }, + [](int v) { return 3; }, + }, + var); }; ASSERT_EQ(doVisit(123LL), 1); ASSERT_EQ(doVisit(123L), 2); @@ -84,17 +81,16 @@ TEST(OverloadedVisitorTest, MultiVisit) { stdx::variant<int, std::string> var2; auto doVisit = [&](const stdx::variant<int, std::string>& a, const stdx::variant<int, std::string, double>& b) { - return stdx::visit( - OverloadedVisitor{ - [](int a, int b) { return 0; }, - [](int a, const std::string& b) { return 1; }, - [](int a, double b) { return 2; }, - [](const std::string& a, int b) { return 3; }, - [](const std::string& a, const std::string& b) { return 4; }, - [](const std::string& a, double b) { return 5; }, - }, - a, - b); + return stdx::visit(OverloadedVisitor{ + [](int a, int b) { return 0; }, + [](int a, const std::string& b) { return 1; }, + [](int a, double b) { return 2; }, + [](const std::string& a, int b) { return 3; }, + [](const std::string& a, const std::string& b) { return 4; }, + [](const std::string& a, double b) { return 5; }, + }, + a, + b); }; ASSERT_EQ(doVisit(123, 123), 0); ASSERT_EQ(doVisit(123, "b"), 1); diff --git a/src/mongo/util/packaged_task.h b/src/mongo/util/packaged_task.h index 3f21808f11f..074b547a2a0 100644 --- a/src/mongo/util/packaged_task.h +++ b/src/mongo/util/packaged_task.h @@ -119,8 +119,8 @@ private: }; template <typename F, typename Sig = packaged_task_detail::SigFor<F>> -PackagedTask(F&& f)->PackagedTask<Sig>; +PackagedTask(F&& f) -> PackagedTask<Sig>; template <typename R, typename... Args> -PackagedTask(R (*)(Args...))->PackagedTask<R(Args...)>; +PackagedTask(R (*)(Args...)) -> PackagedTask<R(Args...)>; } // namespace mongo diff --git a/src/mongo/util/packaged_task_test.cpp b/src/mongo/util/packaged_task_test.cpp index b3af9376c25..bc6ac6ab9aa 100644 --- a/src/mongo/util/packaged_task_test.cpp +++ b/src/mongo/util/packaged_task_test.cpp @@ -67,7 +67,9 @@ TEST(PackagedTaskTest, LambdaTaskMultipleArgs) { } TEST(PackagedTaskTest, UniqueFunctionTaskNoArgs) { - unique_function<BSONObj()> fn = [] { return BSON("x" << 42); }; + unique_function<BSONObj()> fn = [] { + return BSON("x" << 42); + }; auto packagedGetBSON = PackagedTask(std::move(fn)); auto bsonFut = packagedGetBSON.getFuture(); ASSERT_FALSE(bsonFut.isReady()); diff --git a/src/mongo/util/pcre.cpp b/src/mongo/util/pcre.cpp index 961874713f5..7b0c383f8c9 100644 --- a/src/mongo/util/pcre.cpp +++ b/src/mongo/util/pcre.cpp @@ -479,7 +479,7 @@ MatchData& MatchData::operator=(MatchData&&) noexcept = default; IFWD(Regex, pattern, (const std::string&), (), ()) IFWD(Regex, options, (CompileOptions), (), ()) -IFWD(Regex, operator bool,(), (), ()) +IFWD(Regex, operator bool, (), (), ()) IFWD(Regex, error, (std::error_code), (), ()) IFWD(Regex, errorPosition, (size_t), (), ()) IFWD(Regex, captureCount, (size_t), (), ()) @@ -492,10 +492,10 @@ IFWD(Regex, (StringData r, std::string* s, MatchOptions o, size_t p), (r, s, o, p)) -IFWD(MatchData, operator bool,(), (), ()) +IFWD(MatchData, operator bool, (), (), ()) IFWD(MatchData, captureCount, (size_t), (), ()) -IFWD(MatchData, operator[],(StringData), (size_t i), (i)) -IFWD(MatchData, operator[],(StringData), (const std::string& name), (name)) +IFWD(MatchData, operator[], (StringData), (size_t i), (i)) +IFWD(MatchData, operator[], (StringData), (const std::string& name), (name)) IFWD(MatchData, getCaptures, (std::vector<StringData>), (), ()) IFWD(MatchData, getMatchList, (std::vector<StringData>), (), ()) IFWD(MatchData, error, (std::error_code), (), ()) diff --git a/src/mongo/util/pcre_test.cpp b/src/mongo/util/pcre_test.cpp index 9e50aebbb74..01dcfb9db4c 100644 --- a/src/mongo/util/pcre_test.cpp +++ b/src/mongo/util/pcre_test.cpp @@ -124,7 +124,9 @@ TEST(PcreTest, RegexMoveAssign) { } TEST(PcreTest, CodeSize) { - auto reSize = [](std::string p) { return Regex{std::move(p)}.codeSize(); }; + auto reSize = [](std::string p) { + return Regex{std::move(p)}.codeSize(); + }; ASSERT_LT(reSize(""), reSize("hi")); ASSERT_LT(reSize("hi"), reSize("^(hi)*|(\\d{45})$")); } diff --git a/src/mongo/util/pcre_util_test.cpp b/src/mongo/util/pcre_util_test.cpp index 66029835c54..7b784f503ba 100644 --- a/src/mongo/util/pcre_util_test.cpp +++ b/src/mongo/util/pcre_util_test.cpp @@ -44,8 +44,12 @@ using namespace fmt::literals; // Test compares `CompileOptions` as integers. TEST(PcreUtilTest, FlagsToOptions) { using namespace pcre::options; - auto parse = [](StringData flags) { return static_cast<uint32_t>(flagsToOptions(flags)); }; - auto expect = [](pcre::CompileOptions o) { return static_cast<uint32_t>(o); }; + auto parse = [](StringData flags) { + return static_cast<uint32_t>(flagsToOptions(flags)); + }; + auto expect = [](pcre::CompileOptions o) { + return static_cast<uint32_t>(o); + }; ASSERT_EQ(parse(""), expect(UTF)) << " UTF is on by default"; ASSERT_EQ(parse("i"), expect(UTF | CASELESS)); ASSERT_EQ(parse("m"), expect(UTF | MULTILINE)); @@ -55,7 +59,9 @@ TEST(PcreUtilTest, FlagsToOptions) { ASSERT_EQ(parse("imsux"), expect(CASELESS | MULTILINE | DOTALL | UTF | EXTENDED)); ASSERT_EQ(parse("xusmi"), expect(CASELESS | MULTILINE | DOTALL | UTF | EXTENDED)); - auto isBadFlagException = [](const DBException& ex) { return ex.code() == 51108; }; + auto isBadFlagException = [](const DBException& ex) { + return ex.code() == 51108; + }; ASSERT_THROWS_WITH_CHECK(parse("z"), DBException, isBadFlagException); ASSERT_THROWS_WITH_CHECK(parse("iz"), DBException, isBadFlagException); } @@ -66,7 +72,9 @@ TEST(PcreUtilTest, OptionsToFlags) { auto parse = [](pcre::CompileOptions flags) { return static_cast<std::string>(optionsToFlags(flags)); }; - auto expect = [](std::string o) { return (o); }; + auto expect = [](std::string o) { + return (o); + }; ASSERT_EQ(parse(UTF | CASELESS), expect("i")); ASSERT_EQ(parse(UTF | MULTILINE), expect("m")); ASSERT_EQ(parse(UTF | DOTALL), expect("s")); diff --git a/src/mongo/util/periodic_runner.h b/src/mongo/util/periodic_runner.h index 210bd3c4ecf..d7ecb1c7f1b 100644 --- a/src/mongo/util/periodic_runner.h +++ b/src/mongo/util/periodic_runner.h @@ -152,7 +152,7 @@ public: explicit PeriodicJobAnchor(std::shared_ptr<Job> handle); PeriodicJobAnchor() = default; - PeriodicJobAnchor(PeriodicJobAnchor &&) = default; + PeriodicJobAnchor(PeriodicJobAnchor&&) = default; PeriodicJobAnchor& operator=(PeriodicJobAnchor&&) = default; PeriodicJobAnchor(const PeriodicJobAnchor&) = delete; diff --git a/src/mongo/util/periodic_runner_impl.cpp b/src/mongo/util/periodic_runner_impl.cpp index 66b4f152d3c..6d66d5f643d 100644 --- a/src/mongo/util/periodic_runner_impl.cpp +++ b/src/mongo/util/periodic_runner_impl.cpp @@ -105,7 +105,9 @@ void PeriodicRunnerImpl::PeriodicJobImpl::_run() { _job.job(client.get()); lk.lock(); - auto getDeadlineFromInterval = [&] { return start + _job.interval; }; + auto getDeadlineFromInterval = [&] { + return start + _job.interval; + }; do { auto deadline = getDeadlineFromInterval(); diff --git a/src/mongo/util/periodic_runner_impl_test.cpp b/src/mongo/util/periodic_runner_impl_test.cpp index 9b2d3ca5e10..8985414f418 100644 --- a/src/mongo/util/periodic_runner_impl_test.cpp +++ b/src/mongo/util/periodic_runner_impl_test.cpp @@ -76,7 +76,8 @@ public: } auto makeStoppedJob() { - PeriodicRunner::PeriodicJob job("job", [](Client* client) {}, Seconds{1}); + PeriodicRunner::PeriodicJob job( + "job", [](Client* client) {}, Seconds{1}); auto jobAnchor = runner().makeJob(std::move(job)); jobAnchor.start(); jobAnchor.stop(); @@ -92,15 +93,16 @@ TEST_F(PeriodicRunnerImplTest, OneJobTest) { stdx::condition_variable cv; // Add a job, ensure that it runs once - PeriodicRunner::PeriodicJob job("job", - [&count, &mutex, &cv](Client*) { - { - stdx::unique_lock<Latch> lk(mutex); - count++; - } - cv.notify_all(); - }, - interval); + PeriodicRunner::PeriodicJob job( + "job", + [&count, &mutex, &cv](Client*) { + { + stdx::unique_lock<Latch> lk(mutex); + count++; + } + cv.notify_all(); + }, + interval); auto jobAnchor = runner().makeJob(std::move(job)); jobAnchor.start(); @@ -125,15 +127,16 @@ TEST_F(PeriodicRunnerImplTest, OnePausableJobDoesNotRunWithoutStart) { stdx::condition_variable cv; // Add a job, ensure that it runs once - PeriodicRunner::PeriodicJob job("job", - [&count, &mutex, &cv](Client*) { - { - stdx::unique_lock<Latch> lk(mutex); - count++; - } - cv.notify_all(); - }, - interval); + PeriodicRunner::PeriodicJob job( + "job", + [&count, &mutex, &cv](Client*) { + { + stdx::unique_lock<Latch> lk(mutex); + count++; + } + cv.notify_all(); + }, + interval); auto jobAnchor = runner().makeJob(std::move(job)); clockSource().advance(interval); @@ -150,15 +153,16 @@ TEST_F(PeriodicRunnerImplTest, OnePausableJobRunsCorrectlyWithStart) { stdx::condition_variable cv; // Add a job, ensure that it runs once - PeriodicRunner::PeriodicJob job("job", - [&count, &mutex, &cv](Client*) { - { - stdx::unique_lock<Latch> lk(mutex); - count++; - } - cv.notify_all(); - }, - interval); + PeriodicRunner::PeriodicJob job( + "job", + [&count, &mutex, &cv](Client*) { + { + stdx::unique_lock<Latch> lk(mutex); + count++; + } + cv.notify_all(); + }, + interval); auto jobAnchor = runner().makeJob(std::move(job)); jobAnchor.start(); @@ -183,17 +187,18 @@ TEST_F(PeriodicRunnerImplTest, OnePausableJobPausesCorrectly) { stdx::condition_variable cv; // Add a job, ensure that it runs once - PeriodicRunner::PeriodicJob job("job", - [&](Client*) { - { - stdx::unique_lock<Latch> lk(mutex); - // This will fail if pause does not work correctly. - ASSERT_FALSE(isPaused); - hasExecuted = true; - } - cv.notify_all(); - }, - interval); + PeriodicRunner::PeriodicJob job( + "job", + [&](Client*) { + { + stdx::unique_lock<Latch> lk(mutex); + // This will fail if pause does not work correctly. + ASSERT_FALSE(isPaused); + hasExecuted = true; + } + cv.notify_all(); + }, + interval); auto jobAnchor = runner().makeJob(std::move(job)); jobAnchor.start(); @@ -227,15 +232,16 @@ TEST_F(PeriodicRunnerImplTest, OnePausableJobResumesCorrectly) { auto mutex = MONGO_MAKE_LATCH(); stdx::condition_variable cv; - PeriodicRunner::PeriodicJob job("job", - [&count, &mutex, &cv](Client*) { - { - stdx::unique_lock<Latch> lk(mutex); - count++; - } - cv.notify_all(); - }, - interval); + PeriodicRunner::PeriodicJob job( + "job", + [&count, &mutex, &cv](Client*) { + { + stdx::unique_lock<Latch> lk(mutex); + count++; + } + cv.notify_all(); + }, + interval); auto jobAnchor = runner().makeJob(std::move(job)); jobAnchor.start(); @@ -294,25 +300,27 @@ TEST_F(PeriodicRunnerImplTest, TwoJobsTest) { stdx::condition_variable cv; // Add two jobs, ensure they both run the proper number of times - PeriodicRunner::PeriodicJob jobA("job", - [&countA, &mutex, &cv](Client*) { - { - stdx::unique_lock<Latch> lk(mutex); - countA++; - } - cv.notify_all(); - }, - intervalA); - - PeriodicRunner::PeriodicJob jobB("job", - [&countB, &mutex, &cv](Client*) { - { - stdx::unique_lock<Latch> lk(mutex); - countB++; - } - cv.notify_all(); - }, - intervalB); + PeriodicRunner::PeriodicJob jobA( + "job", + [&countA, &mutex, &cv](Client*) { + { + stdx::unique_lock<Latch> lk(mutex); + countA++; + } + cv.notify_all(); + }, + intervalA); + + PeriodicRunner::PeriodicJob jobB( + "job", + [&countB, &mutex, &cv](Client*) { + { + stdx::unique_lock<Latch> lk(mutex); + countB++; + } + cv.notify_all(); + }, + intervalB); auto jobAnchorA = runner().makeJob(std::move(jobA)); auto jobAnchorB = runner().makeJob(std::move(jobB)); @@ -339,27 +347,29 @@ TEST_F(PeriodicRunnerImplTest, TwoJobsDontDeadlock) { bool a = false; bool b = false; - PeriodicRunner::PeriodicJob jobA("job", - [&](Client*) { - stdx::unique_lock<Latch> lk(mutex); - a = true; + PeriodicRunner::PeriodicJob jobA( + "job", + [&](Client*) { + stdx::unique_lock<Latch> lk(mutex); + a = true; - cv.notify_one(); - cv.wait(lk, [&] { return b; }); - doneCv.notify_one(); - }, - Milliseconds(1)); + cv.notify_one(); + cv.wait(lk, [&] { return b; }); + doneCv.notify_one(); + }, + Milliseconds(1)); - PeriodicRunner::PeriodicJob jobB("job", - [&](Client*) { - stdx::unique_lock<Latch> lk(mutex); - b = true; + PeriodicRunner::PeriodicJob jobB( + "job", + [&](Client*) { + stdx::unique_lock<Latch> lk(mutex); + b = true; - cv.notify_one(); - cv.wait(lk, [&] { return a; }); - doneCv.notify_one(); - }, - Milliseconds(1)); + cv.notify_one(); + cv.wait(lk, [&] { return a; }); + doneCv.notify_one(); + }, + Milliseconds(1)); auto jobAnchorA = runner().makeJob(std::move(jobA)); auto jobAnchorB = runner().makeJob(std::move(jobB)); @@ -387,15 +397,16 @@ TEST_F(PeriodicRunnerImplTest, ChangingIntervalWorks) { stdx::condition_variable cv; // Add a job, ensure that it runs once - PeriodicRunner::PeriodicJob job("job", - [&](Client*) { - { - stdx::unique_lock<Latch> lk(mutex); - timesCalled++; - } - cv.notify_one(); - }, - Milliseconds(5)); + PeriodicRunner::PeriodicJob job( + "job", + [&](Client*) { + { + stdx::unique_lock<Latch> lk(mutex); + timesCalled++; + } + cv.notify_one(); + }, + Milliseconds(5)); auto jobAnchor = runner().makeJob(std::move(job)); jobAnchor.start(); diff --git a/src/mongo/util/processinfo_linux.cpp b/src/mongo/util/processinfo_linux.cpp index c05c1ac9e94..6bad8fd497d 100644 --- a/src/mongo/util/processinfo_linux.cpp +++ b/src/mongo/util/processinfo_linux.cpp @@ -407,20 +407,27 @@ public: CpuId parsedCpuId; auto cmp = [](auto&& a, auto&& b) { - auto tupLens = [](auto&& o) { return std::tie(o.core, o.physical); }; + auto tupLens = [](auto&& o) { + return std::tie(o.core, o.physical); + }; return tupLens(a) < tupLens(b); }; std::set<CpuId, decltype(cmp)> cpuIds(cmp); - CpuInfoParser cpuInfoParser{ - { - {"physical id", [&](const std::string& value) { parsedCpuId.physical = value; }}, - {"core id", [&](const std::string& value) { parsedCpuId.core = value; }}, - }, - [&]() { - cpuIds.insert(parsedCpuId); - parsedCpuId = CpuId{}; - }}; + CpuInfoParser cpuInfoParser{{ + {"physical id", + [&](const std::string& value) { + parsedCpuId.physical = value; + }}, + {"core id", + [&](const std::string& value) { + parsedCpuId.core = value; + }}, + }, + [&]() { + cpuIds.insert(parsedCpuId); + parsedCpuId = CpuId{}; + }}; cpuInfoParser.run(); physicalCores = cpuIds.size(); @@ -432,11 +439,14 @@ public: static int getNumCpuSockets() { std::set<std::string> socketIds; - CpuInfoParser cpuInfoParser{ - { - {"physical id", [&](const std::string& value) { socketIds.insert(value); }}, - }, - []() {}}; + CpuInfoParser cpuInfoParser{{ + {"physical id", + [&](const std::string& value) { + socketIds.insert(value); + }}, + }, + []() { + }}; cpuInfoParser.run(); // On ARM64, the "physical id" field is unpopulated, causing there to be 0 sockets found. In @@ -451,19 +461,37 @@ public: procCount = 0; - CpuInfoParser cpuInfoParser{ - { + CpuInfoParser cpuInfoParser{{ #ifdef __s390x__ - {R"re(processor\s+\d+)re", [&](const std::string& value) { procCount++; }}, - {"cpu MHz static", [&](const std::string& value) { freq = value; }}, - {"features", [&](const std::string& value) { features = value; }}, + {R"re(processor\s+\d+)re", + [&](const std::string& value) { + procCount++; + }}, + {"cpu MHz static", + [&](const std::string& value) { + freq = value; + }}, + {"features", + [&](const std::string& value) { + features = value; + }}, #else - {"processor", [&](const std::string& value) { procCount++; }}, - {"cpu MHz", [&](const std::string& value) { freq = value; }}, - {"flags", [&](const std::string& value) { features = value; }}, + {"processor", + [&](const std::string& value) { + procCount++; + }}, + {"cpu MHz", + [&](const std::string& value) { + freq = value; + }}, + {"flags", + [&](const std::string& value) { + features = value; + }}, #endif - }, - []() {}}; + }, + []() { + }}; cpuInfoParser.run(); } diff --git a/src/mongo/util/producer_consumer_queue_test.cpp b/src/mongo/util/producer_consumer_queue_test.cpp index 2d6a4119384..3d07ad587fb 100644 --- a/src/mongo/util/producer_consumer_queue_test.cpp +++ b/src/mongo/util/producer_consumer_queue_test.cpp @@ -862,9 +862,15 @@ PRODUCER_CONSUMER_QUEUE_TEST(pipeCompiles, runPermutations<false, false>) { // // At some point this was working with a single move, and this pattern helped me catch some // lifetime screw ups - auto producer = [](auto p) { return std::move(p); }(std::move(pipe.producer)); - auto controller = [](auto c) { return std::move(c); }(std::move(pipe.controller)); - auto consumer = [](auto c) { return std::move(c); }(std::move(pipe.consumer)); + auto producer = [](auto p) { + return std::move(p); + }(std::move(pipe.producer)); + auto controller = [](auto c) { + return std::move(c); + }(std::move(pipe.controller)); + auto consumer = [](auto c) { + return std::move(c); + }(std::move(pipe.consumer)); producer.push(MoveOnly(1)); std::array<MoveOnly, 1> container({MoveOnly(1)}); diff --git a/src/mongo/util/read_through_cache.h b/src/mongo/util/read_through_cache.h index 1d6a4269cfb..0bb10dc3fef 100644 --- a/src/mongo/util/read_through_cache.h +++ b/src/mongo/util/read_through_cache.h @@ -657,21 +657,22 @@ public: stdx::lock_guard lg(_cache._mutex); _valid = true; - _cancelToken.emplace(_cache._asyncWork([ this, promise = std::move(promise) ]( - OperationContext * opCtx, const Status& status) mutable noexcept { - promise.setWith([&] { - uassertStatusOK(status); - if constexpr (std::is_same_v<Time, CacheNotCausallyConsistent>) { - return _cache._lookupFn(opCtx, _key, _cachedValue); - } else { - auto minTimeInStore = [&] { - stdx::lock_guard lg(_cache._mutex); - return _minTimeInStore; - }(); - return _cache._lookupFn(opCtx, _key, _cachedValue, minTimeInStore); - } - }); - })); + _cancelToken.emplace( + _cache._asyncWork([this, promise = std::move(promise)]( + OperationContext* opCtx, const Status& status) mutable noexcept { + promise.setWith([&] { + uassertStatusOK(status); + if constexpr (std::is_same_v<Time, CacheNotCausallyConsistent>) { + return _cache._lookupFn(opCtx, _key, _cachedValue); + } else { + auto minTimeInStore = [&] { + stdx::lock_guard lg(_cache._mutex); + return _minTimeInStore; + }(); + return _cache._lookupFn(opCtx, _key, _cachedValue, minTimeInStore); + } + }); + })); return std::move(future); } diff --git a/src/mongo/util/read_through_cache_test.cpp b/src/mongo/util/read_through_cache_test.cpp index f44ceed13b4..1f02bd9ff8d 100644 --- a/src/mongo/util/read_through_cache_test.cpp +++ b/src/mongo/util/read_through_cache_test.cpp @@ -56,16 +56,16 @@ struct CachedValue { class Cache : public ReadThroughCache<std::string, CachedValue> { public: Cache(ServiceContext* service, ThreadPoolInterface& threadPool, size_t size, LookupFn lookupFn) - : ReadThroughCache(_mutex, - service, - threadPool, - [this, lookupFn = std::move(lookupFn)](OperationContext* opCtx, - const std::string& key, - const ValueHandle& cachedValue) { - ++countLookups; - return lookupFn(opCtx, key, cachedValue); - }, - size) {} + : ReadThroughCache( + _mutex, + service, + threadPool, + [this, lookupFn = std::move(lookupFn)]( + OperationContext* opCtx, const std::string& key, const ValueHandle& cachedValue) { + ++countLookups; + return lookupFn(opCtx, key, cachedValue); + }, + size) {} int countLookups{0}; @@ -79,17 +79,18 @@ public: ThreadPoolInterface& threadPool, size_t size, LookupFn lookupFn) - : ReadThroughCache(_mutex, - service, - threadPool, - [this, lookupFn = std::move(lookupFn)](OperationContext* opCtx, - const std::string& key, - const ValueHandle& cachedValue, - Timestamp timeInStore) { - ++countLookups; - return lookupFn(opCtx, key, cachedValue, timeInStore); - }, - size) {} + : ReadThroughCache( + _mutex, + service, + threadPool, + [this, lookupFn = std::move(lookupFn)](OperationContext* opCtx, + const std::string& key, + const ValueHandle& cachedValue, + Timestamp timeInStore) { + ++countLookups; + return lookupFn(opCtx, key, cachedValue, timeInStore); + }, + size) {} int countLookups{0}; @@ -318,7 +319,9 @@ TEST_F(ReadThroughCacheTest, InvalidateCacheSizeZeroReissuesLookup) { } TEST_F(ReadThroughCacheTest, KeyDoesNotExist) { - auto fnTest = [&](auto cache) { ASSERT(!cache.acquire(_opCtx, "TestKey")); }; + auto fnTest = [&](auto cache) { + ASSERT(!cache.acquire(_opCtx, "TestKey")); + }; fnTest(CacheWithThreadPool<Cache>( getServiceContext(), diff --git a/src/mongo/util/scopeguard.h b/src/mongo/util/scopeguard.h index 63195c7335f..aeaa9fd7603 100644 --- a/src/mongo/util/scopeguard.h +++ b/src/mongo/util/scopeguard.h @@ -50,11 +50,11 @@ template <typename F> class [[nodiscard]] ScopeGuard { public: template <typename FuncArg> - ScopeGuard(FuncArg && f) : _func(std::forward<FuncArg>(f)) {} + ScopeGuard(FuncArg&& f) : _func(std::forward<FuncArg>(f)) {} // Remove all move and copy, MCE (mandatory copy elision) covers us here. ScopeGuard(const ScopeGuard&) = delete; - ScopeGuard(ScopeGuard &&) = delete; + ScopeGuard(ScopeGuard&&) = delete; ScopeGuard& operator=(const ScopeGuard&) = delete; ScopeGuard& operator=(ScopeGuard&&) = delete; @@ -74,7 +74,7 @@ private: }; template <typename F> -ScopeGuard(F &&)->ScopeGuard<std::decay_t<F>>; +ScopeGuard(F&&) -> ScopeGuard<std::decay_t<F>>; } // namespace mongo diff --git a/src/mongo/util/stacktrace_bm.cpp b/src/mongo/util/stacktrace_bm.cpp index b2df446d07b..3a4c939b800 100644 --- a/src/mongo/util/stacktrace_bm.cpp +++ b/src/mongo/util/stacktrace_bm.cpp @@ -76,7 +76,9 @@ void BM_Baseline(benchmark::State& state) { RecursionParam param; size_t i = 0; param.n = state.range(0); - param.f = [&] { ++i; }; + param.f = [&] { + ++i; + }; for (auto _ : state) { benchmark::DoNotOptimize(recursionTest(param)); ++items; diff --git a/src/mongo/util/static_immortal_test.cpp b/src/mongo/util/static_immortal_test.cpp index 90ed283de23..cab57dccbde 100644 --- a/src/mongo/util/static_immortal_test.cpp +++ b/src/mongo/util/static_immortal_test.cpp @@ -86,7 +86,9 @@ TEST(StaticImmortalTest, DeducedValueTypeCopyInit) { } TEST(StaticImmortalTest, DeducedValueTypeExpression) { - static const StaticImmortal m = [] { return Map{{"hello", 123}, {"bye", 456}}; }(); + static const StaticImmortal m = [] { + return Map{{"hello", 123}, {"bye", 456}}; + }(); ASSERT_EQ(m->find("bye")->second, 456); } diff --git a/src/mongo/util/str_escape.cpp b/src/mongo/util/str_escape.cpp index e96922a017e..db037a32362 100644 --- a/src/mongo/util/str_escape.cpp +++ b/src/mongo/util/str_escape.cpp @@ -123,7 +123,9 @@ void escape(Buffer& buffer, }; // Helper function to write a valid one byte UTF-8 sequence from the input stream - auto writeValid1Byte = [&]() { singleHandler(flushAndWrite, *it); }; + auto writeValid1Byte = [&]() { + singleHandler(flushAndWrite, *it); + }; // Helper function to write a valid two byte UTF-8 sequence from the input stream auto writeValid2Byte = [&]() { @@ -138,7 +140,9 @@ void escape(Buffer& buffer, // Helper function to write an invalid UTF-8 sequence from the input stream // Will try and write up to num bytes but bail if we reach the end of the input. // Updates the position of 'it'. - auto writeInvalid = [&](uint8_t c) { invalidByteHandler(flushAndWrite, c); }; + auto writeInvalid = [&](uint8_t c) { + invalidByteHandler(flushAndWrite, c); + }; while (it != inLast) { @@ -506,8 +510,10 @@ std::string escapeForJSON(StringData str, size_t maxLength, size_t* wouldWrite) bool validUTF8(StringData str) { // No-op buffer and handlers, defined to re-use escape method logic. NoopBuffer buffer; - auto singleByteHandler = [](const auto& writer, uint8_t unescaped) {}; - auto twoByteEscaper = [](const auto& writer, uint8_t first, uint8_t second) {}; + auto singleByteHandler = [](const auto& writer, uint8_t unescaped) { + }; + auto twoByteEscaper = [](const auto& writer, uint8_t first, uint8_t second) { + }; // Throws an exception when an invalid UTF8 character is detected. auto invalidByteHandler = [](const auto& writer, uint8_t) { diff --git a/src/mongo/util/synchronized_value.h b/src/mongo/util/synchronized_value.h index 75bc29c4101..9e5651366ee 100644 --- a/src/mongo/util/synchronized_value.h +++ b/src/mongo/util/synchronized_value.h @@ -132,7 +132,7 @@ public: } /** Lock and return a holder to the value and lock. Const or non-const. */ - auto operator-> () const { + auto operator->() const { return synchronize(); } auto operator*() const { @@ -144,7 +144,7 @@ public: } /** Mutators */ - auto operator-> () { + auto operator->() { return synchronize(); } auto operator*() { diff --git a/src/mongo/util/thread_safety_context_test.cpp b/src/mongo/util/thread_safety_context_test.cpp index c91cfaa95da..1752069b8f3 100644 --- a/src/mongo/util/thread_safety_context_test.cpp +++ b/src/mongo/util/thread_safety_context_test.cpp @@ -106,9 +106,9 @@ TEST_F(ThreadSafetyContextTest, CreateThreadsAfterSafetyContext) { TEST_F(ThreadSafetyContextTest, SingleThreadedContext) { ASSERT(ThreadSafetyContext::getThreadSafetyContext()->isSingleThreaded()); - stdx::thread( - []() { ASSERT(!ThreadSafetyContext::getThreadSafetyContext()->isSingleThreaded()); }) - .join(); + stdx::thread([]() { + ASSERT(!ThreadSafetyContext::getThreadSafetyContext()->isSingleThreaded()); + }).join(); ASSERT(!ThreadSafetyContext::getThreadSafetyContext()->isSingleThreaded()); } diff --git a/src/mongo/util/uuid.cpp b/src/mongo/util/uuid.cpp index 3d0b7991c72..5ae8c6d2456 100644 --- a/src/mongo/util/uuid.cpp +++ b/src/mongo/util/uuid.cpp @@ -92,11 +92,9 @@ UUID UUID::parse(const BSONObj& obj) { bool UUID::isUUIDString(StringData s) { static constexpr auto pat = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"_sd; return s.size() == pat.size() && - std::mismatch(s.begin(), - s.end(), - pat.begin(), - [](char a, char b) { return b == 'x' ? ctype::isXdigit(a) : a == b; }) - .first == s.end(); + std::mismatch(s.begin(), s.end(), pat.begin(), [](char a, char b) { + return b == 'x' ? ctype::isXdigit(a) : a == b; + }).first == s.end(); } bool UUID::isRFC4122v4() const { |