diff options
author | Billy Donahue <billy.donahue@mongodb.com> | 2022-06-30 20:13:00 +0000 |
---|---|---|
committer | Evergreen Agent <no-reply@evergreen.mongodb.com> | 2022-07-06 15:17:27 +0000 |
commit | 501b2dc980abcc8090cff1998141af30b42d8dd1 (patch) | |
tree | 804539df912dd3857cea6116851df468190877b3 /src | |
parent | 3cc20216a850af1d4bf63956740d73e8fc3779df (diff) | |
download | mongo-501b2dc980abcc8090cff1998141af30b42d8dd1.tar.gz |
SERVER-67709 rename visit_helper
Diffstat (limited to 'src')
57 files changed, 698 insertions, 599 deletions
diff --git a/src/mongo/db/catalog/coll_mod.cpp b/src/mongo/db/catalog/coll_mod.cpp index d7c5ff1ee92..f3aae154159 100644 --- a/src/mongo/db/catalog/coll_mod.cpp +++ b/src/mongo/db/catalog/coll_mod.cpp @@ -62,8 +62,8 @@ #include "mongo/idl/command_generic_argument.h" #include "mongo/logv2/log.h" #include "mongo/util/fail_point.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/util/version/releases.h" -#include "mongo/util/visit_helper.h" #define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kCommand @@ -522,7 +522,7 @@ StatusWith<std::pair<ParsedCollModRequest, BSONObj>> parseCollModRequest(Operati } auto status = stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&oplogEntryBuilder](const std::string& value) -> Status { if (value != "off") { return {ErrorCodes::InvalidOptions, @@ -579,7 +579,7 @@ void _setClusteredExpireAfterSeconds( boost::optional<int64_t> oldExpireAfterSeconds = oldCollOptions.expireAfterSeconds; stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const std::string& newExpireAfterSeconds) { invariant(newExpireAfterSeconds == "off"); if (!oldExpireAfterSeconds) { diff --git a/src/mongo/db/catalog/collection_options.cpp b/src/mongo/db/catalog/collection_options.cpp index 4f1635393f3..49dbe398ec7 100644 --- a/src/mongo/db/catalog/collection_options.cpp +++ b/src/mongo/db/catalog/collection_options.cpp @@ -42,8 +42,8 @@ #include "mongo/db/query/collation/collator_interface.h" #include "mongo/db/query/query_feature_flags_gen.h" #include "mongo/idl/command_generic_argument.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/util/str.h" -#include "mongo/util/visit_helper.h" namespace mongo { namespace { @@ -375,7 +375,7 @@ CollectionOptions CollectionOptions::fromCreateCommand(const NamespaceString& ns } if (auto clusteredIndex = cmd.getClusteredIndex()) { stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](bool isClustered) { if (isClustered) { options.clusteredIndex = diff --git a/src/mongo/db/catalog/drop_indexes.cpp b/src/mongo/db/catalog/drop_indexes.cpp index 493c8326146..0e383f9add5 100644 --- a/src/mongo/db/catalog/drop_indexes.cpp +++ b/src/mongo/db/catalog/drop_indexes.cpp @@ -51,7 +51,7 @@ #include "mongo/db/s/shard_key_index_util.h" #include "mongo/db/service_context.h" #include "mongo/logv2/log.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" #define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kCommand @@ -155,29 +155,29 @@ bool containsClusteredIndex(const CollectionPtr& collection, const IndexArgument auto clusteredIndexSpec = collection->getClusteredInfo()->getIndexSpec(); return stdx::visit( - visit_helper::Overloaded{[&](const std::string& indexName) -> bool { - // While the clusteredIndex's name is optional during user - // creation, it should always be filled in by default on the - // collection object. - auto clusteredIndexName = clusteredIndexSpec.getName(); - invariant(clusteredIndexName.is_initialized()); - - return clusteredIndexName.get() == indexName; - }, - [&](const std::vector<std::string>& indexNames) -> bool { - // While the clusteredIndex's name is optional during user - // creation, it should always be filled in by default on the - // collection object. - auto clusteredIndexName = clusteredIndexSpec.getName(); - invariant(clusteredIndexName.is_initialized()); - - return std::find(indexNames.begin(), - indexNames.end(), - clusteredIndexName.get()) != indexNames.end(); - }, - [&](const BSONObj& indexKey) -> bool { - return clusteredIndexSpec.getKey().woCompare(indexKey) == 0; - }}, + OverloadedVisitor{[&](const std::string& indexName) -> bool { + // While the clusteredIndex's name is optional during user + // creation, it should always be filled in by default on the + // collection object. + auto clusteredIndexName = clusteredIndexSpec.getName(); + invariant(clusteredIndexName.is_initialized()); + + return clusteredIndexName.get() == indexName; + }, + [&](const std::vector<std::string>& indexNames) -> bool { + // While the clusteredIndex's name is optional during user + // creation, it should always be filled in by default on the + // collection object. + auto clusteredIndexName = clusteredIndexSpec.getName(); + invariant(clusteredIndexName.is_initialized()); + + return std::find(indexNames.begin(), + indexNames.end(), + clusteredIndexName.get()) != indexNames.end(); + }, + [&](const BSONObj& indexKey) -> bool { + return clusteredIndexSpec.getKey().woCompare(indexKey) == 0; + }}, index); } @@ -191,7 +191,7 @@ StatusWith<std::vector<std::string>> getIndexNames(OperationContext* opCtx, invariant(opCtx->lockState()->isCollectionLockedForMode(collection->ns(), MODE_IX)); return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const std::string& arg) -> StatusWith<std::vector<std::string>> { return {{arg}}; }, [](const std::vector<std::string>& arg) -> StatusWith<std::vector<std::string>> { return arg; @@ -414,13 +414,13 @@ DropIndexesReply dropIndexes(OperationContext* opCtx, "CMD: dropIndexes", "namespace"_attr = nss, "uuid"_attr = collectionUUID, - "indexes"_attr = stdx::visit( - visit_helper::Overloaded{[](const std::string& arg) { return arg; }, - [](const std::vector<std::string>& arg) { - return boost::algorithm::join(arg, ","); - }, - [](const BSONObj& arg) { return arg.toString(); }}, - index)); + "indexes"_attr = + stdx::visit(OverloadedVisitor{[](const std::string& arg) { return arg; }, + [](const std::vector<std::string>& arg) { + return boost::algorithm::join(arg, ","); + }, + [](const BSONObj& arg) { return arg.toString(); }}, + index)); } if ((*collection)->isClustered() && diff --git a/src/mongo/db/change_stream_options_manager.cpp b/src/mongo/db/change_stream_options_manager.cpp index 98da89d5094..d99b3352c95 100644 --- a/src/mongo/db/change_stream_options_manager.cpp +++ b/src/mongo/db/change_stream_options_manager.cpp @@ -119,7 +119,7 @@ Status ChangeStreamOptionsParameter::validate(const BSONElement& newValueElement ChangeStreamOptions newOptions = ChangeStreamOptions::parse(ctxt, changeStreamOptionsObj); auto preAndPostImages = newOptions.getPreAndPostImages(); stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const std::string& expireAfterSeconds) { if (expireAfterSeconds != "off"_sd) { validateStatus = { diff --git a/src/mongo/db/commands/get_cluster_parameter_invocation.cpp b/src/mongo/db/commands/get_cluster_parameter_invocation.cpp index 7eb4218040e..f5f2b1442c6 100644 --- a/src/mongo/db/commands/get_cluster_parameter_invocation.cpp +++ b/src/mongo/db/commands/get_cluster_parameter_invocation.cpp @@ -61,43 +61,45 @@ GetClusterParameterInvocation::retrieveRequestedParameters(OperationContext* opC }; stdx::visit( - visit_helper::Overloaded{ - [&](const std::string& strParameterName) { - if (strParameterName == "*"_sd) { - // Retrieve all cluster parameter values. - Map clusterParameterMap = clusterParameters->getMap(); - parameterValues.reserve(clusterParameterMap.size()); - parameterNames.reserve(clusterParameterMap.size()); - for (const auto& param : clusterParameterMap) { - makeBSON(param.second); - } - } else { - // Any other string must correspond to a single parameter name. Return - // an error if a disabled cluster parameter is explicitly requested. - ServerParameter* sp = clusterParameters->get(strParameterName); - uassert(ErrorCodes::BadValue, - str::stream() << "Server parameter: '" << strParameterName - << "' is currently disabled", - sp->isEnabled()); - makeBSON(sp); - } - }, - [&](const std::vector<std::string>& listParameterNames) { - uassert(ErrorCodes::BadValue, - "Must supply at least one cluster server parameter name to " - "getClusterParameter", - listParameterNames.size() > 0); - parameterValues.reserve(listParameterNames.size()); - parameterNames.reserve(listParameterNames.size()); - for (const auto& requestedParameterName : listParameterNames) { - ServerParameter* sp = clusterParameters->get(requestedParameterName); - uassert(ErrorCodes::BadValue, - str::stream() << "Server parameter: '" << requestedParameterName - << "' is currently disabled'", - sp->isEnabled()); - makeBSON(sp); - } - }}, + OverloadedVisitor{[&](const std::string& strParameterName) { + if (strParameterName == "*"_sd) { + // Retrieve all cluster parameter values. + Map clusterParameterMap = clusterParameters->getMap(); + parameterValues.reserve(clusterParameterMap.size()); + parameterNames.reserve(clusterParameterMap.size()); + for (const auto& param : clusterParameterMap) { + makeBSON(param.second); + } + } else { + // Any other string must correspond to a single parameter name. + // Return an error if a disabled cluster parameter is explicitly + // requested. + ServerParameter* sp = clusterParameters->get(strParameterName); + uassert(ErrorCodes::BadValue, + str::stream() << "Server parameter: '" << strParameterName + << "' is currently disabled", + sp->isEnabled()); + makeBSON(sp); + } + }, + [&](const std::vector<std::string>& listParameterNames) { + uassert(ErrorCodes::BadValue, + "Must supply at least one cluster server parameter name to " + "getClusterParameter", + listParameterNames.size() > 0); + parameterValues.reserve(listParameterNames.size()); + parameterNames.reserve(listParameterNames.size()); + for (const auto& requestedParameterName : listParameterNames) { + ServerParameter* sp = + clusterParameters->get(requestedParameterName); + uassert(ErrorCodes::BadValue, + str::stream() + << "Server parameter: '" << requestedParameterName + << "' is currently disabled'", + sp->isEnabled()); + makeBSON(sp); + } + }}, cmdBody); return {std::move(parameterNames), std::move(parameterValues)}; diff --git a/src/mongo/db/commands/rename_collection_cmd.cpp b/src/mongo/db/commands/rename_collection_cmd.cpp index f35d8cebd6e..1e839ca0271 100644 --- a/src/mongo/db/commands/rename_collection_cmd.cpp +++ b/src/mongo/db/commands/rename_collection_cmd.cpp @@ -107,7 +107,7 @@ public: options.stayTemp = renameRequest.getStayTemp(); options.expectedSourceUUID = renameRequest.getCollectionUUID(); stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&options](bool dropTarget) { options.dropTarget = dropTarget; }, [&options](const UUID& uuid) { options.dropTarget = true; diff --git a/src/mongo/db/cst/bson_location.h b/src/mongo/db/cst/bson_location.h index 2c7b6ad7cab..99ef7660e29 100644 --- a/src/mongo/db/cst/bson_location.h +++ b/src/mongo/db/cst/bson_location.h @@ -36,7 +36,7 @@ #include "mongo/base/string_data.h" #include "mongo/bson/bsonobj.h" #include "mongo/stdx/variant.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo { @@ -67,7 +67,7 @@ public: std::string toString() const { std::ostringstream stream; stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const BSONElement& elem) { stream << "'" << elem.toString(false) << "'"; }, [&](const StringData& elem) { stream << "'" << elem << "'"; }}, _location); @@ -75,21 +75,20 @@ public: // point to the parser (e.g. the 'pipeline' argument for an aggregation command). invariant(_prefix.size() > 0); for (auto it = _prefix.rbegin(); it != _prefix.rend() - 1; ++it) { - stdx::visit(visit_helper::Overloaded{[&](const unsigned int& index) { - stream << " within array at index " << index; - }, - [&](const StringData& pref) { - stream << " within '" << pref << "'"; - }}, + stdx::visit(OverloadedVisitor{[&](const unsigned int& index) { + stream << " within array at index " << index; + }, + [&](const StringData& pref) { + stream << " within '" << pref << "'"; + }}, *it); } // The final prefix (or first element in the vector) is the input description. - stdx::visit(visit_helper::Overloaded{[&](const unsigned int& index) { MONGO_UNREACHABLE; }, - [&](const StringData& pref) { - stream << " of input " << pref; - }}, - _prefix[0]); + stdx::visit( + OverloadedVisitor{[&](const unsigned int& index) { MONGO_UNREACHABLE; }, + [&](const StringData& pref) { stream << " of input " << pref; }}, + _prefix[0]); return stream.str(); } diff --git a/src/mongo/db/cst/c_node.cpp b/src/mongo/db/cst/c_node.cpp index 2d7c610085e..e172cf6f52e 100644 --- a/src/mongo/db/cst/c_node.cpp +++ b/src/mongo/db/cst/c_node.cpp @@ -31,7 +31,7 @@ #include "mongo/bson/bsontypes.h" #include "mongo/db/query/datetime/date_time_support.h" #include "mongo/util/hex.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" #include <iterator> #include <limits> @@ -50,12 +50,12 @@ auto tabs(int num) { auto printFieldname(const CNode::Fieldname& fieldname) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const KeyFieldname& key) { return "<KeyFieldname "s + toStringData(key) + ">"; }, [](const UserFieldname& user) { return "<UserFieldname "s + user + ">"; }, [](const FieldnamePath& path) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const ProjectionPath& projPath) { return "<ProjectionPath "s + path::vectorToString(projPath) + ">"; }, @@ -73,7 +73,7 @@ auto printFieldname(const CNode::Fieldname& fieldname) { auto printNonZeroKey(const NonZeroKey& nonZeroKey) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const int& keyInt) { return "int "s + std::to_string(keyInt); }, [](const long long& keyLong) { return "long "s + std::to_string(keyLong); }, [](const double& keyDouble) { return "double "s + std::to_string(keyDouble); }, @@ -84,7 +84,7 @@ auto printNonZeroKey(const NonZeroKey& nonZeroKey) { template <typename T> auto printValue(const T& payload) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const CNode::ArrayChildren&) { return "<Array>"s; }, [](const CNode::ObjectChildren&) { return "<Object>"s; }, [](const CompoundInclusionKey&) { return "<CompoundInclusionKey>"s; }, @@ -96,14 +96,14 @@ auto printValue(const T& payload) { }, [](const ValuePath& valuePath) { return stdx::visit( - visit_helper::Overloaded{[&](const AggregationPath& aggPath) { - return "<AggregationPath "s + - path::vectorToString(aggPath) + ">"; - }, - [&](const AggregationVariablePath& aggVarPath) { - return "<AggregationVariablePath "s + - path::vectorToString(aggVarPath) + ">"; - }}, + OverloadedVisitor{[&](const AggregationPath& aggPath) { + return "<AggregationPath "s + + path::vectorToString(aggPath) + ">"; + }, + [&](const AggregationVariablePath& aggVarPath) { + return "<AggregationVariablePath "s + + path::vectorToString(aggVarPath) + ">"; + }}, valuePath); }, [](const UserDouble& userDouble) { @@ -166,7 +166,7 @@ auto printValue(const T& payload) { std::string CNode::toStringHelper(int numTabs) const { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [numTabs](const ArrayChildren& children) { return std::accumulate(children.cbegin(), children.cend(), @@ -224,7 +224,7 @@ std::pair<BSONObj, bool> CNode::toBsonWithArrayIndicator() const { }; return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ // Build an array which will lose its identity and appear as a BSONObj [&](const ArrayChildren& children) { return std::pair{ @@ -275,7 +275,7 @@ std::pair<BSONObj, bool> CNode::toBsonWithArrayIndicator() const { bool CNode::isNumber() const { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const UserLong&) { return true; }, [](const UserDouble&) { return true; }, [](const UserDecimal&) { return true; }, @@ -304,18 +304,17 @@ int CNode::numberInt() const { long long CNode::numberLong() const { return stdx::visit( - visit_helper::Overloaded{ - [](const UserDouble& userDouble) { - return (BSON("" << userDouble).firstElement()).safeNumberLong(); - }, - [](const UserInt& userInt) { - return (BSON("" << userInt).firstElement()).safeNumberLong(); - }, - [](const UserLong& userLong) { return userLong; }, - [](const UserDecimal& userDecimal) { - return (BSON("" << userDecimal).firstElement()).safeNumberLong(); - }, - [](auto &&) -> UserLong { MONGO_UNREACHABLE }}, + OverloadedVisitor{[](const UserDouble& userDouble) { + return (BSON("" << userDouble).firstElement()).safeNumberLong(); + }, + [](const UserInt& userInt) { + return (BSON("" << userInt).firstElement()).safeNumberLong(); + }, + [](const UserLong& userLong) { return userLong; }, + [](const UserDecimal& userDecimal) { + return (BSON("" << userDecimal).firstElement()).safeNumberLong(); + }, + [](auto &&) -> UserLong { MONGO_UNREACHABLE }}, payload); } diff --git a/src/mongo/db/cst/c_node_disambiguation.cpp b/src/mongo/db/cst/c_node_disambiguation.cpp index 4e3f2de776b..15098cadd59 100644 --- a/src/mongo/db/cst/c_node_disambiguation.cpp +++ b/src/mongo/db/cst/c_node_disambiguation.cpp @@ -33,14 +33,14 @@ #include "mongo/db/cst/c_node_disambiguation.h" #include "mongo/stdx/variant.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo::c_node_disambiguation { namespace { ProjectionType disambiguateCNode(const CNode& cst) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const CNode::ObjectChildren& children) { return *std::accumulate( children.begin(), diff --git a/src/mongo/db/cst/c_node_validation.cpp b/src/mongo/db/cst/c_node_validation.cpp index 634db01a562..8acc2dfa434 100644 --- a/src/mongo/db/cst/c_node_validation.cpp +++ b/src/mongo/db/cst/c_node_validation.cpp @@ -42,7 +42,7 @@ #include "mongo/db/pipeline/variable_validation.h" #include "mongo/db/query/util/make_data_structure.h" #include "mongo/stdx/variant.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo::c_node_validation { using namespace std::string_literals; @@ -220,7 +220,7 @@ Status addPathsFromTreeToSet(const CNode::ObjectChildren& children, stdx::get<KeyFieldname>(child.first) == KeyFieldname::id)); if (auto status = stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const CompoundInclusionKey& compoundKey) { // In this context we have a compound inclusion key to descend into. return addPathsFromTreeToSet( @@ -275,7 +275,7 @@ Status validateNumericType(T num) { Status validateSingleType(const CNode& element) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const UserDouble& dbl) { return validateNumericType(dbl); }, [&](const UserInt& num) { return validateNumericType(num); }, [&](const UserLong& lng) { return validateNumericType(lng); }, diff --git a/src/mongo/db/cst/cst_match_translation.cpp b/src/mongo/db/cst/cst_match_translation.cpp index f8ee19e5623..ba7184e585f 100644 --- a/src/mongo/db/cst/cst_match_translation.cpp +++ b/src/mongo/db/cst/cst_match_translation.cpp @@ -42,7 +42,7 @@ #include "mongo/db/matcher/expression_expr.h" #include "mongo/db/matcher/expression_tree.h" #include "mongo/db/matcher/matcher_type_set.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo::cst_match_translation { namespace { @@ -90,17 +90,17 @@ std::unique_ptr<MatchExpression> translateNot(const UserFieldname& fieldName, std::unique_ptr<MatchExpression> translateExists(const CNode::Fieldname& fieldName, const CNode& argument) { auto root = std::make_unique<ExistsMatchExpression>(stdx::get<UserFieldname>(fieldName)); - if (stdx::visit( - visit_helper::Overloaded{ - [&](const UserLong& userLong) { return userLong != 0; }, - [&](const UserDouble& userDbl) { return userDbl != 0; }, - [&](const UserDecimal& userDc) { return userDc.isNotEqual(Decimal128(0)); }, - [&](const UserInt& userInt) { return userInt != 0; }, - [&](const UserBoolean& b) { return b; }, - [&](const UserNull&) { return false; }, - [&](const UserUndefined&) { return false; }, - [&](auto&&) { return true; }}, - argument.payload)) { + if (stdx::visit(OverloadedVisitor{[&](const UserLong& userLong) { return userLong != 0; }, + [&](const UserDouble& userDbl) { return userDbl != 0; }, + [&](const UserDecimal& userDc) { + return userDc.isNotEqual(Decimal128(0)); + }, + [&](const UserInt& userInt) { return userInt != 0; }, + [&](const UserBoolean& b) { return b; }, + [&](const UserNull&) { return false; }, + [&](const UserUndefined&) { return false; }, + [&](auto&&) { return true; }}, + argument.payload)) { return root; } return std::make_unique<NotMatchExpression>(root.release()); @@ -110,7 +110,7 @@ MatcherTypeSet getMatcherTypeSet(const CNode& argument) { MatcherTypeSet ts; auto add_individual_to_type_set = [&](const CNode& a) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const UserLong& userLong) { auto valueAsInt = BSON("" << userLong).firstElement().parseIntegerElementToInt(); @@ -275,7 +275,7 @@ std::unique_ptr<MatchExpression> translateMatchPredicate( } else { // Expression is over a user fieldname. return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const CNode::ObjectChildren& userObject) -> std::unique_ptr<MatchExpression> { return translatePathExpression(stdx::get<UserFieldname>(fieldName), userObject); }, diff --git a/src/mongo/db/cst/cst_pipeline_translation.cpp b/src/mongo/db/cst/cst_pipeline_translation.cpp index ca85a8884a0..efc100357fe 100644 --- a/src/mongo/db/cst/cst_pipeline_translation.cpp +++ b/src/mongo/db/cst/cst_pipeline_translation.cpp @@ -62,7 +62,7 @@ #include "mongo/db/pipeline/variables.h" #include "mongo/db/query/util/make_data_structure.h" #include "mongo/util/intrusive_counter.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo::cst_pipeline_translation { namespace { @@ -102,14 +102,14 @@ auto translateLiteralObjectToValue(const CNode::ObjectChildren& object) { * uncollapsed otherwise. */ Value translateLiteralToValue(const CNode& cst) { - return stdx::visit( - visit_helper::Overloaded{ - [](const CNode::ArrayChildren& array) { return translateLiteralArrayToValue(array); }, - [](const CNode::ObjectChildren& object) { - return translateLiteralObjectToValue(object); - }, - [&](auto&& payload) { return translateLiteralLeaf(cst); }}, - cst.payload); + return stdx::visit(OverloadedVisitor{[](const CNode::ArrayChildren& array) { + return translateLiteralArrayToValue(array); + }, + [](const CNode::ObjectChildren& object) { + return translateLiteralObjectToValue(object); + }, + [&](auto&& payload) { return translateLiteralLeaf(cst); }}, + cst.payload); } /** @@ -155,7 +155,7 @@ auto transformInputExpression(const CNode::ObjectChildren& object, const VariablesParseState& vps) { auto expressions = std::vector<boost::intrusive_ptr<Expression>>{}; stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const CNode::ArrayChildren& array) { static_cast<void>(std::transform( array.begin(), array.end(), std::back_inserter(expressions), [&](auto&& elem) { @@ -860,7 +860,7 @@ boost::intrusive_ptr<Expression> translateExpression(const CNode& cst, ExpressionContext* expCtx, const VariablesParseState& vps) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ // When we're not inside an agg operator/function, this is a non-leaf literal. [&](const CNode::ArrayChildren& array) -> boost::intrusive_ptr<Expression> { return translateLiteralArray(array, expCtx, vps); @@ -885,15 +885,14 @@ boost::intrusive_ptr<Expression> translateExpression(const CNode& cst, [](const NonZeroKey&) -> boost::intrusive_ptr<Expression> { MONGO_UNREACHABLE; }, [&](const ValuePath& vp) -> boost::intrusive_ptr<Expression> { return stdx::visit( - visit_helper::Overloaded{ - [&](const AggregationPath& ap) { - return ExpressionFieldPath::createPathFromString( - expCtx, path::vectorToString(ap.components), vps); - }, - [&](const AggregationVariablePath& avp) { - return ExpressionFieldPath::createVarFromString( - expCtx, path::vectorToString(avp.components), vps); - }}, + OverloadedVisitor{[&](const AggregationPath& ap) { + return ExpressionFieldPath::createPathFromString( + expCtx, path::vectorToString(ap.components), vps); + }, + [&](const AggregationVariablePath& avp) { + return ExpressionFieldPath::createVarFromString( + expCtx, path::vectorToString(avp.components), vps); + }}, vp); }, // Everything else is a literal leaf. @@ -921,24 +920,23 @@ std::unique_ptr<Pipeline, PipelineDeleter> translatePipeline( */ Value translateLiteralLeaf(const CNode& cst) { return stdx::visit( - visit_helper::Overloaded{ - // These are illegal since they're non-leaf. - [](const CNode::ArrayChildren&) -> Value { MONGO_UNREACHABLE; }, - [](const CNode::ObjectChildren&) -> Value { MONGO_UNREACHABLE; }, - [](const CompoundInclusionKey&) -> Value { MONGO_UNREACHABLE; }, - [](const CompoundExclusionKey&) -> Value { MONGO_UNREACHABLE; }, - [](const CompoundInconsistentKey&) -> Value { MONGO_UNREACHABLE; }, - // These are illegal since they're non-literal. - [](const KeyValue&) -> Value { MONGO_UNREACHABLE; }, - [](const NonZeroKey&) -> Value { MONGO_UNREACHABLE; }, - [](const ValuePath&) -> Value { MONGO_UNREACHABLE; }, - // These payloads require a special translation to DocumentValue parlance. - [](const UserUndefined&) { return Value{BSONUndefined}; }, - [](const UserNull&) { return Value{BSONNULL}; }, - [](const UserMinKey&) { return Value{MINKEY}; }, - [](const UserMaxKey&) { return Value{MAXKEY}; }, - // The rest convert directly. - [](auto&& payload) { return Value{payload}; }}, + OverloadedVisitor{// These are illegal since they're non-leaf. + [](const CNode::ArrayChildren&) -> Value { MONGO_UNREACHABLE; }, + [](const CNode::ObjectChildren&) -> Value { MONGO_UNREACHABLE; }, + [](const CompoundInclusionKey&) -> Value { MONGO_UNREACHABLE; }, + [](const CompoundExclusionKey&) -> Value { MONGO_UNREACHABLE; }, + [](const CompoundInconsistentKey&) -> Value { MONGO_UNREACHABLE; }, + // These are illegal since they're non-literal. + [](const KeyValue&) -> Value { MONGO_UNREACHABLE; }, + [](const NonZeroKey&) -> Value { MONGO_UNREACHABLE; }, + [](const ValuePath&) -> Value { MONGO_UNREACHABLE; }, + // These payloads require a special translation to DocumentValue parlance. + [](const UserUndefined&) { return Value{BSONUndefined}; }, + [](const UserNull&) { return Value{BSONNULL}; }, + [](const UserMinKey&) { return Value{MINKEY}; }, + [](const UserMaxKey&) { return Value{MAXKEY}; }, + // The rest convert directly. + [](auto&& payload) { return Value{payload}; }}, cst.payload); } diff --git a/src/mongo/db/cst/cst_sort_translation.cpp b/src/mongo/db/cst/cst_sort_translation.cpp index b2f85d71646..e395c70dde5 100644 --- a/src/mongo/db/cst/cst_sort_translation.cpp +++ b/src/mongo/db/cst/cst_sort_translation.cpp @@ -37,7 +37,7 @@ #include "mongo/db/exec/document_value/document_metadata_fields.h" #include "mongo/db/pipeline/expression.h" #include "mongo/db/pipeline/field_path.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo::cst_sort_translation { @@ -50,7 +50,7 @@ SortPattern translateSortSpec(const CNode& cst, auto&& path = path::vectorToString( std::move(stdx::get<SortPath>(stdx::get<FieldnamePath>(keyValPair.first)).components)); stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const CNode::ObjectChildren& object) { // $meta is always the only key in the object, and always has a KeyValue as its // value. diff --git a/src/mongo/db/exec/mock_stage.cpp b/src/mongo/db/exec/mock_stage.cpp index a84c7995408..ab2dd12edfa 100644 --- a/src/mongo/db/exec/mock_stage.cpp +++ b/src/mongo/db/exec/mock_stage.cpp @@ -31,7 +31,7 @@ #include "mongo/db/exec/mock_stage.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo { @@ -55,7 +55,7 @@ PlanStage::StageState MockStage::doWork(WorkingSetID* out) { _results.pop(); auto returnState = stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](WorkingSetID wsid) -> PlanStage::StageState { return PlanStage::ADVANCED; }, [](PlanStage::StageState state) -> PlanStage::StageState { return state; }, [](Status status) -> PlanStage::StageState { diff --git a/src/mongo/db/exec/sbe/stages/check_bounds.cpp b/src/mongo/db/exec/sbe/stages/check_bounds.cpp index bc62b089005..3b3c3ca7537 100644 --- a/src/mongo/db/exec/sbe/stages/check_bounds.cpp +++ b/src/mongo/db/exec/sbe/stages/check_bounds.cpp @@ -66,13 +66,14 @@ void CheckBoundsStage::prepare(CompileCtx& ctx) { _inRecordIdAccessor = _children[0]->getAccessor(ctx, _inRecordIdSlot); // Set up the IndexBounds accessor for the slot where IndexBounds will be stored. - _indexBoundsAccessor = stdx::visit( - visit_helper::Overloaded{ - [](const IndexBounds&) -> RuntimeEnvironment::Accessor* { return nullptr; }, - [&ctx](CheckBoundsParams::RuntimeEnvironmentSlotId slot) { - return ctx.getRuntimeEnvAccessor(slot); - }}, - _params.indexBounds); + _indexBoundsAccessor = + stdx::visit(OverloadedVisitor{[](const IndexBounds&) -> RuntimeEnvironment::Accessor* { + return nullptr; + }, + [&ctx](CheckBoundsParams::RuntimeEnvironmentSlotId slot) { + return ctx.getRuntimeEnvAccessor(slot); + }}, + _params.indexBounds); } value::SlotAccessor* CheckBoundsStage::getAccessor(CompileCtx& ctx, value::SlotId slot) { @@ -93,7 +94,7 @@ void CheckBoundsStage::open(bool reOpen) { // Set up the IndexBoundsChecker by extracting the IndexBounds from the RuntimeEnvironment if // value is provided there. auto indexBoundsPtr = stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const IndexBounds& indexBounds) { return &indexBounds; }, [&](CheckBoundsParams::RuntimeEnvironmentSlotId) -> const IndexBounds* { tassert(6579900, "'_indexBoundsAccessor' must be populated", _indexBoundsAccessor); @@ -212,7 +213,7 @@ size_t CheckBoundsStage::estimateCompileTimeSize() const { size += size_estimator::estimate(_specificStats); size += size_estimator::estimate(_params.keyPattern); size += stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const IndexBounds& indexBounds) { return size_estimator::estimate(indexBounds); }, [](CheckBoundsParams::RuntimeEnvironmentSlotId) -> size_t { return 0; }}, _params.indexBounds); diff --git a/src/mongo/db/index/sort_key_generator.cpp b/src/mongo/db/index/sort_key_generator.cpp index 0019027a85a..34bfbb7f61a 100644 --- a/src/mongo/db/index/sort_key_generator.cpp +++ b/src/mongo/db/index/sort_key_generator.cpp @@ -33,7 +33,7 @@ #include "mongo/bson/bsonobj_comparator.h" #include "mongo/db/query/collation/collation_index_key.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo { @@ -223,7 +223,7 @@ boost::optional<Value> SortKeyGenerator::extractKeyPart( auto keyVariant = doc.getNestedFieldNonCaching(*patternPart.fieldPath); auto key = stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ // In this case, the document has an array along the path given. This means the // document is ineligible for taking the fast path for index key generation. [](Document::TraversesArrayTag) -> boost::optional<Value> { return boost::none; }, diff --git a/src/mongo/db/matcher/doc_validation_error.cpp b/src/mongo/db/matcher/doc_validation_error.cpp index 85b4943f538..721f7b81c8e 100644 --- a/src/mongo/db/matcher/doc_validation_error.cpp +++ b/src/mongo/db/matcher/doc_validation_error.cpp @@ -318,11 +318,11 @@ struct ValidationErrorContext { void appendLatestCompleteError(BSONObjBuilder* builder) { const static std::string kDetailsString = "details"; stdx::visit( - visit_helper::Overloaded{[&](const auto& details) -> void { - verifySizeAndAppend(details, kDetailsString, builder); - }, - [&](const std::monostate& state) -> void { MONGO_UNREACHABLE }, - [&](const std::string& str) -> void { MONGO_UNREACHABLE }}, + OverloadedVisitor{[&](const auto& details) -> void { + verifySizeAndAppend(details, kDetailsString, builder); + }, + [&](const std::monostate& state) -> void { MONGO_UNREACHABLE }, + [&](const std::string& str) -> void { MONGO_UNREACHABLE }}, latestCompleteError); } /** @@ -331,7 +331,7 @@ struct ValidationErrorContext { */ void appendLatestCompleteError(BSONArrayBuilder* builder) { stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const BSONObj& obj) -> void { verifySizeAndAppend(obj, builder); }, [&](const std::string& str) -> void { builder->append(str); }, [&](const BSONArray& arr) -> void { diff --git a/src/mongo/db/ops/write_ops.cpp b/src/mongo/db/ops/write_ops.cpp index 41c7fa4f5d2..4389f1b0032 100644 --- a/src/mongo/db/ops/write_ops.cpp +++ b/src/mongo/db/ops/write_ops.cpp @@ -35,8 +35,8 @@ #include "mongo/db/update/update_oplog_entry_version.h" #include "mongo/rpc/get_status_from_command_result.h" #include "mongo/util/assert_util.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/util/str.h" -#include "mongo/util/visit_helper.h" namespace mongo { @@ -229,7 +229,7 @@ UpdateModification UpdateModification::parseFromBSON(BSONElement elem) { int UpdateModification::objsize() const { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const ReplacementUpdate& replacement) -> int { return replacement.bson.objsize(); }, [](const ModifierUpdate& modifier) -> int { return modifier.bson.objsize(); }, [](const PipelineUpdate& pipeline) -> int { @@ -247,12 +247,11 @@ int UpdateModification::objsize() const { UpdateModification::Type UpdateModification::type() const { return stdx::visit( - visit_helper::Overloaded{ - [](const ReplacementUpdate& replacement) { return Type::kReplacement; }, - [](const ModifierUpdate& modifier) { return Type::kModifier; }, - [](const PipelineUpdate& pipelineUpdate) { return Type::kPipeline; }, - [](const DeltaUpdate& delta) { return Type::kDelta; }, - [](const TransformUpdate& transform) { return Type::kTransform; }}, + OverloadedVisitor{[](const ReplacementUpdate& replacement) { return Type::kReplacement; }, + [](const ModifierUpdate& modifier) { return Type::kModifier; }, + [](const PipelineUpdate& pipelineUpdate) { return Type::kPipeline; }, + [](const DeltaUpdate& delta) { return Type::kDelta; }, + [](const TransformUpdate& transform) { return Type::kTransform; }}, _update); } @@ -262,24 +261,24 @@ UpdateModification::Type UpdateModification::type() const { */ void UpdateModification::serializeToBSON(StringData fieldName, BSONObjBuilder* bob) const { - stdx::visit( - visit_helper::Overloaded{ - [fieldName, bob](const ReplacementUpdate& replacement) { - *bob << fieldName << replacement.bson; - }, - [fieldName, bob](const ModifierUpdate& modifier) { - *bob << fieldName << modifier.bson; - }, - [fieldName, bob](const PipelineUpdate& pipeline) { - BSONArrayBuilder arrayBuilder(bob->subarrayStart(fieldName)); - for (auto&& stage : pipeline) { - arrayBuilder << stage; - } - arrayBuilder.doneFast(); - }, - [fieldName, bob](const DeltaUpdate& delta) { *bob << fieldName << delta.diff; }, - [](const TransformUpdate& transform) {}}, - _update); + stdx::visit(OverloadedVisitor{[fieldName, bob](const ReplacementUpdate& replacement) { + *bob << fieldName << replacement.bson; + }, + [fieldName, bob](const ModifierUpdate& modifier) { + *bob << fieldName << modifier.bson; + }, + [fieldName, bob](const PipelineUpdate& pipeline) { + BSONArrayBuilder arrayBuilder(bob->subarrayStart(fieldName)); + for (auto&& stage : pipeline) { + arrayBuilder << stage; + } + arrayBuilder.doneFast(); + }, + [fieldName, bob](const DeltaUpdate& delta) { + *bob << fieldName << delta.diff; + }, + [](const TransformUpdate& transform) {}}, + _update); } WriteError::WriteError(int32_t index, Status status) : _index(index), _status(std::move(status)) {} diff --git a/src/mongo/db/ops/write_ops_parsers.h b/src/mongo/db/ops/write_ops_parsers.h index ea898a153b0..c05c882bb3e 100644 --- a/src/mongo/db/ops/write_ops_parsers.h +++ b/src/mongo/db/ops/write_ops_parsers.h @@ -36,7 +36,7 @@ #include "mongo/db/repl/optime.h" #include "mongo/db/update/document_diff_serialization.h" #include "mongo/stdx/variant.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo { namespace write_ops { @@ -175,7 +175,7 @@ public: StringBuilder sb; stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&sb](const ReplacementUpdate& replacement) { sb << "{type: Replacement, update: " << replacement.bson << "}"; }, diff --git a/src/mongo/db/pipeline/change_stream_document_diff_parser.cpp b/src/mongo/db/pipeline/change_stream_document_diff_parser.cpp index c847f32872e..6818a80393d 100644 --- a/src/mongo/db/pipeline/change_stream_document_diff_parser.cpp +++ b/src/mongo/db/pipeline/change_stream_document_diff_parser.cpp @@ -189,7 +189,7 @@ void buildUpdateDescriptionWithDeltaOplog( } stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](DocumentDiffReader* reader) { boost::optional<BSONElement> nextMod; while ((nextMod = reader->nextUpdate()) || (nextMod = reader->nextInsert())) { @@ -202,10 +202,9 @@ void buildUpdateDescriptionWithDeltaOplog( while (auto nextSubDiff = reader->nextSubDiff()) { stdx::variant<DocumentDiffReader*, ArrayDiffReader*> nextReader; - stdx::visit(visit_helper::Overloaded{[&nextReader](auto& reader) { - nextReader = &reader; - }}, - nextSubDiff->second); + stdx::visit( + OverloadedVisitor{[&nextReader](auto& reader) { nextReader = &reader; }}, + nextSubDiff->second); buildUpdateDescriptionWithDeltaOplog( nextReader, builder, {{nextSubDiff->first}}); } @@ -222,7 +221,7 @@ void buildUpdateDescriptionWithDeltaOplog( for (auto nextMod = reader->next(); nextMod; nextMod = reader->next()) { stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](BSONElement elem) { builder->addToUpdatedFields(nextMod->first, Value(elem)); }, diff --git a/src/mongo/db/pipeline/document_source_densify.cpp b/src/mongo/db/pipeline/document_source_densify.cpp index 740ef193431..daae674995b 100644 --- a/src/mongo/db/pipeline/document_source_densify.cpp +++ b/src/mongo/db/pipeline/document_source_densify.cpp @@ -34,7 +34,7 @@ #include "mongo/db/query/sort_pattern.h" #include "mongo/stdx/variant.h" #include "mongo/util/assert_util.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" using boost::intrusive_ptr; using boost::optional; @@ -493,7 +493,7 @@ DocumentSource::GetNextResult DocumentSourceInternalDensify::finishDensifyingPar return DocumentSource::GetNextResult::makeEOF(); } return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](Full) { // Densify between partitions's last seen value and global max. tassert(5733707, "_current must be set if partitionTable is non-empty", _current); @@ -518,7 +518,7 @@ DocumentSource::GetNextResult DocumentSourceInternalDensify::finishDensifyingPar DocumentSource::GetNextResult DocumentSourceInternalDensify::handleSourceExhausted() { _eof = true; return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](RangeStatement::Full) { if (_partitionExpr) { return finishDensifyingPartitionedInput(); @@ -705,7 +705,7 @@ DocumentSource::GetNextResult DocumentSourceInternalDensify::doGetNext() { } return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](Full) { _current = val; _globalMin = val; @@ -742,59 +742,64 @@ DocumentSource::GetNextResult DocumentSourceInternalDensify::doGetNext() { auto val = getDensifyValue(currentDoc); return stdx::visit( - visit_helper::Overloaded{ - [&](Full) { - if (_partitionExpr) { - // Keep track of '_globalMax' for later. The latest document from the - // source is always the max. - _globalMax = val; - // If we haven't seen this partition before, densify between - // '_globalMin' and this value. - auto partitionVal = getDensifyPartition(currentDoc); - auto foundPartitionVal = _partitionTable.find(partitionVal); - if (foundPartitionVal == _partitionTable.end()) { - // _current represents the last value seen. We want to generate - // _globalMin, so pretend we've seen the value before that. - _current = _globalMin->decrement(_range); - // Insert the new partition into the table. - setPartitionValue(currentDoc); - return handleNeedGen(currentDoc); - } - // Otherwise densify between the last seen value and this one. - _current = foundPartitionVal->second; - } - return handleNeedGen(currentDoc); - }, - [&](Partition) { - // If we haven't seen this partition before, add it to the table then - // return. - auto partitionVal = getDensifyPartition(currentDoc); - auto foundPartitionVal = _partitionTable.find(partitionVal); - if (foundPartitionVal == _partitionTable.end()) { - setPartitionValue(currentDoc); - return nextDoc; - } - // Reset current to be the last value in this partition. - _current = foundPartitionVal->second; - return handleNeedGen(currentDoc); - }, - [&](ExplicitBounds bounds) { - if (_partitionExpr) { - // If we haven't seen this partition before, add it to the table - // then check where it is in the range. - auto partitionVal = getDensifyPartition(currentDoc); - auto foundPartitionVal = _partitionTable.find(partitionVal); - if (foundPartitionVal == _partitionTable.end()) { - setPartitionValue(currentDoc); - // This partition has seen no values. - _current = boost::none; - return processFirstDocForExplicitRange(currentDoc); - } - // Otherwise reset current to be the last value in this partition. - _current = foundPartitionVal->second; - } - return handleNeedGenExplicit(nextDoc.getDocument()); - }}, + OverloadedVisitor{[&](Full) { + if (_partitionExpr) { + // Keep track of '_globalMax' for later. The latest + // document from the source is always the max. + _globalMax = val; + // If we haven't seen this partition before, densify + // between + // '_globalMin' and this value. + auto partitionVal = getDensifyPartition(currentDoc); + auto foundPartitionVal = + _partitionTable.find(partitionVal); + if (foundPartitionVal == _partitionTable.end()) { + // _current represents the last value seen. We want to + // generate _globalMin, so pretend we've seen the + // value before that. + _current = _globalMin->decrement(_range); + // Insert the new partition into the table. + setPartitionValue(currentDoc); + return handleNeedGen(currentDoc); + } + // Otherwise densify between the last seen value and this + // one. + _current = foundPartitionVal->second; + } + return handleNeedGen(currentDoc); + }, + [&](Partition) { + // If we haven't seen this partition before, add it to the + // table then return. + auto partitionVal = getDensifyPartition(currentDoc); + auto foundPartitionVal = _partitionTable.find(partitionVal); + if (foundPartitionVal == _partitionTable.end()) { + setPartitionValue(currentDoc); + return nextDoc; + } + // Reset current to be the last value in this partition. + _current = foundPartitionVal->second; + return handleNeedGen(currentDoc); + }, + [&](ExplicitBounds bounds) { + if (_partitionExpr) { + // If we haven't seen this partition before, add it to the + // table then check where it is in the range. + auto partitionVal = getDensifyPartition(currentDoc); + auto foundPartitionVal = + _partitionTable.find(partitionVal); + if (foundPartitionVal == _partitionTable.end()) { + setPartitionValue(currentDoc); + // This partition has seen no values. + _current = boost::none; + return processFirstDocForExplicitRange(currentDoc); + } + // Otherwise reset current to be the last value in this + // partition. + _current = foundPartitionVal->second; + } + return handleNeedGenExplicit(nextDoc.getDocument()); + }}, _range.getBounds()); } case DensifyState::kHaveGenerator: { @@ -805,50 +810,49 @@ DocumentSource::GetNextResult DocumentSourceInternalDensify::doGetNext() { auto generatedDoc = _docGenerator->getNextDocument(); return stdx::visit( - visit_helper::Overloaded{[&](Full) { - if (_docGenerator->done()) { - _docGenerator = boost::none; - if (_eof && _partitionExpr) { - _densifyState = - DensifyState::kFinishingDensify; - } else { - _densifyState = DensifyState::kNeedGen; - } - } - // The generator's final document may not be on the - // step. - auto genDensifyVal = getDensifyValue(generatedDoc); - if (genDensifyVal == _current->increment(_range)) { - _current = genDensifyVal; - setPartitionValue(generatedDoc); - } - return generatedDoc; - }, - [&](Partition) { - if (_docGenerator->done()) { - _docGenerator = boost::none; - _densifyState = DensifyState::kNeedGen; - } - // The generator's final document may not be on the - // step. - auto genDensifyVal = getDensifyValue(generatedDoc); - if (genDensifyVal == _current->increment(_range)) { - _current = genDensifyVal; - setPartitionValue(generatedDoc); - } - return generatedDoc; - }, - [&](ExplicitBounds bounds) { - auto val = getDensifyValue(generatedDoc); - // Only want to update the rangeMin if the value - - // current is divisible by the step. - if (val.isOnStepRelativeTo(*_current, _range)) { - _current = val; - setPartitionValue(generatedDoc); - } - resetDocGen(bounds); - return generatedDoc; - }}, + OverloadedVisitor{[&](Full) { + if (_docGenerator->done()) { + _docGenerator = boost::none; + if (_eof && _partitionExpr) { + _densifyState = DensifyState::kFinishingDensify; + } else { + _densifyState = DensifyState::kNeedGen; + } + } + // The generator's final document may not be on the + // step. + auto genDensifyVal = getDensifyValue(generatedDoc); + if (genDensifyVal == _current->increment(_range)) { + _current = genDensifyVal; + setPartitionValue(generatedDoc); + } + return generatedDoc; + }, + [&](Partition) { + if (_docGenerator->done()) { + _docGenerator = boost::none; + _densifyState = DensifyState::kNeedGen; + } + // The generator's final document may not be on the + // step. + auto genDensifyVal = getDensifyValue(generatedDoc); + if (genDensifyVal == _current->increment(_range)) { + _current = genDensifyVal; + setPartitionValue(generatedDoc); + } + return generatedDoc; + }, + [&](ExplicitBounds bounds) { + auto val = getDensifyValue(generatedDoc); + // Only want to update the rangeMin if the value - + // current is divisible by the step. + if (val.isOnStepRelativeTo(*_current, _range)) { + _current = val; + setPartitionValue(generatedDoc); + } + resetDocGen(bounds); + return generatedDoc; + }}, _range.getBounds()); } case DensifyState::kFinishingDensify: { @@ -875,7 +879,7 @@ DocumentSource::GetNextResult DocumentSourceInternalDensify::doGetNext() { DensifyValue DensifyValue::increment(const RangeStatement& range) const { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](Value val) { return DensifyValue(uassertStatusOK(ExpressionAdd::apply(val, range.getStep()))); }, @@ -888,7 +892,7 @@ DensifyValue DensifyValue::increment(const RangeStatement& range) const { DensifyValue DensifyValue::decrement(const RangeStatement& range) const { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](Value val) { return DensifyValue( uassertStatusOK(ExpressionSubtract::apply(val, range.getStep()))); @@ -902,7 +906,7 @@ DensifyValue DensifyValue::decrement(const RangeStatement& range) const { bool DensifyValue::isOnStepRelativeTo(DensifyValue base, RangeStatement range) const { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](Value val) { Value diff = uassertStatusOK(ExpressionSubtract::apply(val, base.getNumber())); Value remainder = uassertStatusOK(ExpressionMod::apply(diff, range.getStep())); diff --git a/src/mongo/db/pipeline/document_source_densify.h b/src/mongo/db/pipeline/document_source_densify.h index 6415c5425d8..fc629977ce6 100644 --- a/src/mongo/db/pipeline/document_source_densify.h +++ b/src/mongo/db/pipeline/document_source_densify.h @@ -38,8 +38,8 @@ #include "mongo/db/pipeline/field_path.h" #include "mongo/db/pipeline/memory_usage_tracker.h" #include "mongo/db/query/datetime/date_time_support.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/util/time_support.h" -#include "mongo/util/visit_helper.h" namespace mongo { @@ -61,12 +61,11 @@ public: * Convert a DensifyValue into a Value for use in documents/serialization. */ Value toValue() const { - return stdx::visit( - visit_helper::Overloaded{[&](Value unwrappedVal) { return unwrappedVal; }, - [&](Date_t dateVal) { return Value(dateVal); } + return stdx::visit(OverloadedVisitor{[&](Value unwrappedVal) { return unwrappedVal; }, + [&](Date_t dateVal) { return Value(dateVal); } - }, - _value); + }, + _value); } /** @@ -74,17 +73,16 @@ public: * of (lhs - rhs). Returns -1 if lhs < rhs, 0 if lhs == rhs, and 1 if lhs > rhs. */ static int compare(const DensifyValue& lhs, const DensifyValue& rhs) { - return stdx::visit( - visit_helper::Overloaded{[&](Value lhsVal) { - Value rhsVal = stdx::get<Value>(rhs._value); - return Value::compare(lhsVal, rhsVal, nullptr); - }, - [&](Date_t lhsVal) { - Date_t rhsVal = stdx::get<Date_t>(rhs._value); - return Value::compare( - Value(lhsVal), Value(rhsVal), nullptr); - }}, - lhs._value); + return stdx::visit(OverloadedVisitor{[&](Value lhsVal) { + Value rhsVal = stdx::get<Value>(rhs._value); + return Value::compare(lhsVal, rhsVal, nullptr); + }, + [&](Date_t lhsVal) { + Date_t rhsVal = stdx::get<Date_t>(rhs._value); + return Value::compare( + Value(lhsVal), Value(rhsVal), nullptr); + }}, + lhs._value); } /** @@ -104,8 +102,8 @@ public: } std::string toString() const { - return stdx::visit(visit_helper::Overloaded{[&](Value v) { return v.toString(); }, - [&](Date_t d) { return d.toString(); }}, + return stdx::visit(OverloadedVisitor{[&](Value v) { return v.toString(); }, + [&](Date_t d) { return d.toString(); }}, _value); } @@ -124,8 +122,8 @@ public: */ size_t getApproximateSize() const { return stdx::visit( - visit_helper::Overloaded{[&](Value v) { return v.getApproximateSize(); }, - [&](Date_t d) { return Value(d).getApproximateSize(); }}, + OverloadedVisitor{[&](Value v) { return v.getApproximateSize(); }, + [&](Date_t d) { return Value(d).getApproximateSize(); }}, _value); } @@ -245,12 +243,12 @@ public: MutableDocument spec; spec[kArgStep] = _step; spec[kArgBounds] = stdx::visit( - visit_helper::Overloaded{[&](Full) { return Value(kValFull); }, - [&](Partition) { return Value(kValPartition); }, - [&](ExplicitBounds bounds) { - return Value(std::vector<Value>( - {bounds.first.toValue(), bounds.second.toValue()})); - }}, + OverloadedVisitor{[&](Full) { return Value(kValFull); }, + [&](Partition) { return Value(kValPartition); }, + [&](ExplicitBounds bounds) { + return Value(std::vector<Value>( + {bounds.first.toValue(), bounds.second.toValue()})); + }}, _bounds); if (_unit) spec[kArgUnit] = Value(serializeTimeUnit(*_unit)); diff --git a/src/mongo/db/pipeline/document_source_fill.cpp b/src/mongo/db/pipeline/document_source_fill.cpp index f7938a89a63..755b1f397df 100644 --- a/src/mongo/db/pipeline/document_source_fill.cpp +++ b/src/mongo/db/pipeline/document_source_fill.cpp @@ -37,7 +37,7 @@ #include "mongo/db/pipeline/field_path.h" #include "mongo/stdx/variant.h" #include "mongo/util/assert_util.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" #include <string> namespace mongo { diff --git a/src/mongo/db/pipeline/document_source_set_window_fields.cpp b/src/mongo/db/pipeline/document_source_set_window_fields.cpp index 0920fdda988..aaee42b59d0 100644 --- a/src/mongo/db/pipeline/document_source_set_window_fields.cpp +++ b/src/mongo/db/pipeline/document_source_set_window_fields.cpp @@ -41,7 +41,7 @@ #include "mongo/db/pipeline/lite_parsed_document_source.h" #include "mongo/db/query/query_knobs_gen.h" #include "mongo/db/query/sort_pattern.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" using boost::intrusive_ptr; using boost::optional; diff --git a/src/mongo/db/pipeline/sharded_agg_helpers.cpp b/src/mongo/db/pipeline/sharded_agg_helpers.cpp index 522ff971056..8b8f6e476dd 100644 --- a/src/mongo/db/pipeline/sharded_agg_helpers.cpp +++ b/src/mongo/db/pipeline/sharded_agg_helpers.cpp @@ -64,7 +64,7 @@ #include "mongo/s/stale_exception.h" #include "mongo/s/transaction_router.h" #include "mongo/util/fail_point.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" #define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kQuery @@ -734,7 +734,7 @@ std::unique_ptr<Pipeline, PipelineDeleter> targetShardsAndAddMergeCursors( boost::optional<BSONObj> readConcern) { auto&& [aggRequest, pipeline] = [&] { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](std::unique_ptr<Pipeline, PipelineDeleter>&& pipeline) { return std::make_pair( AggregateCommandRequest(expCtx->ns, pipeline->serializeToBson()), diff --git a/src/mongo/db/pipeline/window_function/partition_iterator.cpp b/src/mongo/db/pipeline/window_function/partition_iterator.cpp index d8992aec28c..ea59f5c6e09 100644 --- a/src/mongo/db/pipeline/window_function/partition_iterator.cpp +++ b/src/mongo/db/pipeline/window_function/partition_iterator.cpp @@ -30,7 +30,7 @@ #include "mongo/platform/basic.h" #include "mongo/db/pipeline/window_function/partition_iterator.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" using boost::optional; @@ -196,7 +196,7 @@ PartitionIterator::AdvanceResult PartitionIterator::advanceInternal() { namespace { optional<int> numericBound(WindowBounds::Bound<int> bound) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](WindowBounds::Unbounded) -> optional<int> { return boost::none; }, [](WindowBounds::Current) -> optional<int> { return 0; }, [](int i) -> optional<int> { return i; }, @@ -259,7 +259,7 @@ optional<std::pair<int, int>> PartitionIterator::getEndpointsRangeBased( // 'lower' is the smallest offset in the partition that's within the lower bound of the window. optional<int> lower = stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](WindowBounds::Current) -> optional<int> { // 'range: ["current", _]' means the current document, which is always offset 0. return 0; @@ -318,7 +318,7 @@ optional<std::pair<int, int>> PartitionIterator::getEndpointsRangeBased( // 'upper' is the largest offset in the partition that's within the upper bound of the window. optional<int> upper = stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](WindowBounds::Current) -> optional<int> { // 'range: [_, "current"]' means the current document, which is offset 0. return 0; @@ -445,7 +445,7 @@ optional<std::pair<int, int>> PartitionIterator::getEndpoints( tassert(5423301, "getEndpoints assumes there is a current document", (*this)[0] != boost::none); return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const WindowBounds::DocumentBased docBounds) { return getEndpointsDocumentBased(docBounds, hint); }, diff --git a/src/mongo/db/pipeline/window_function/window_bounds.cpp b/src/mongo/db/pipeline/window_function/window_bounds.cpp index dd082135e02..6025e255be9 100644 --- a/src/mongo/db/pipeline/window_function/window_bounds.cpp +++ b/src/mongo/db/pipeline/window_function/window_bounds.cpp @@ -65,7 +65,7 @@ WindowBounds::Bound<T> parseBound(ExpressionContext* expCtx, template <class T> Value serializeBound(const WindowBounds::Bound<T>& bound) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const WindowBounds::Unbounded&) { return Value(WindowBounds::kValUnbounded); }, [](const WindowBounds::Current&) { return Value(WindowBounds::kValCurrent); }, [](const T& n) { return Value(n); }, @@ -220,7 +220,7 @@ WindowBounds WindowBounds::parse(BSONObj args, } void WindowBounds::serialize(MutableDocument& args) const { stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const DocumentBased& docBounds) { args[kArgDocuments] = Value{std::vector<Value>{ serializeBound(docBounds.lower), diff --git a/src/mongo/db/pipeline/window_function/window_function_exec.cpp b/src/mongo/db/pipeline/window_function/window_function_exec.cpp index 6de2a88f3f6..5afcdfb3197 100644 --- a/src/mongo/db/pipeline/window_function/window_function_exec.cpp +++ b/src/mongo/db/pipeline/window_function/window_function_exec.cpp @@ -77,7 +77,7 @@ std::unique_ptr<WindowFunctionExec> translateDocumentWindow( auto inputExpr = translateInputExpression(expr, sortBy); return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const WindowBounds::Unbounded&) -> std::unique_ptr<WindowFunctionExec> { // A left unbounded window will always be non-removable regardless of the upper // bound. @@ -145,7 +145,7 @@ std::unique_ptr<WindowFunctionExec> WindowFunctionExec::create( WindowBounds bounds = functionStmt.expr->bounds(); return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const WindowBounds::DocumentBased& docBounds) { return translateDocumentWindow( iter, functionStmt.expr, sortBy, docBounds, &functionMemTracker); diff --git a/src/mongo/db/pipeline/window_function/window_function_exec_non_removable.h b/src/mongo/db/pipeline/window_function/window_function_exec_non_removable.h index 6d858d7646f..c96f2a4695f 100644 --- a/src/mongo/db/pipeline/window_function/window_function_exec_non_removable.h +++ b/src/mongo/db/pipeline/window_function/window_function_exec_non_removable.h @@ -109,7 +109,7 @@ private: void initialize() { auto needMore = [&](int index) { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const WindowBounds::Unbounded&) { return true; }, [&](const WindowBounds::Current&) { return index == 0; }, [&](const int& n) { return index <= n; }, diff --git a/src/mongo/db/pipeline/window_function/window_function_exec_removable_document.cpp b/src/mongo/db/pipeline/window_function/window_function_exec_removable_document.cpp index ef053afdc30..625b15aac09 100644 --- a/src/mongo/db/pipeline/window_function/window_function_exec_removable_document.cpp +++ b/src/mongo/db/pipeline/window_function/window_function_exec_removable_document.cpp @@ -46,7 +46,7 @@ WindowFunctionExecRemovableDocument::WindowFunctionExecRemovableDocument( memTracker) { stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const WindowBounds::Unbounded&) { // If the window is left unbounded we should use the non-removable executor. MONGO_UNREACHABLE_TASSERT(5339802); @@ -57,7 +57,7 @@ WindowFunctionExecRemovableDocument::WindowFunctionExecRemovableDocument( bounds.lower); stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const WindowBounds::Unbounded&) { // Pass. _upperBound defaults to boost::none which represents no upper // bound. diff --git a/src/mongo/db/query/explain.cpp b/src/mongo/db/query/explain.cpp index 4aa6e7bad7f..8c7796209cb 100644 --- a/src/mongo/db/query/explain.cpp +++ b/src/mongo/db/query/explain.cpp @@ -61,9 +61,9 @@ #include "mongo/db/server_options.h" #include "mongo/util/hex.h" #include "mongo/util/net/socket_utils.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/util/str.h" #include "mongo/util/version.h" -#include "mongo/util/visit_helper.h" namespace mongo { namespace { @@ -433,15 +433,14 @@ void Explain::planCacheEntryToBSON(const PlanCacheEntry& entry, BSONObjBuilder* } } - auto explainer = - stdx::visit(visit_helper::Overloaded{[](const plan_ranker::StatsDetails&) { - return plan_explainer_factory::make(nullptr); - }, - [](const plan_ranker::SBEStatsDetails&) { - return plan_explainer_factory::make( - nullptr, nullptr, nullptr); - }}, - debugInfo.decision->stats); + auto explainer = stdx::visit( + OverloadedVisitor{[](const plan_ranker::StatsDetails&) { + return plan_explainer_factory::make(nullptr); + }, + [](const plan_ranker::SBEStatsDetails&) { + return plan_explainer_factory::make(nullptr, nullptr, nullptr); + }}, + debugInfo.decision->stats); auto plannerStats = explainer->getCachedPlanStats(debugInfo, ExplainOptions::Verbosity::kQueryPlanner); auto execStats = diff --git a/src/mongo/db/query/plan_cache.h b/src/mongo/db/query/plan_cache.h index 1201c0f197c..06a6644e16b 100644 --- a/src/mongo/db/query/plan_cache.h +++ b/src/mongo/db/query/plan_cache.h @@ -366,15 +366,15 @@ public: "number of scores in decision must match viable candidates"); } - auto newWorks = stdx::visit( - visit_helper::Overloaded{[](const plan_ranker::StatsDetails& details) { - return details.candidatePlanStats[0]->common.works; - }, - [](const plan_ranker::SBEStatsDetails& details) { - return calculateNumberOfReads( - details.candidatePlanStats[0].get()); - }}, - why.stats); + auto newWorks = + stdx::visit(OverloadedVisitor{[](const plan_ranker::StatsDetails& details) { + return details.candidatePlanStats[0]->common.works; + }, + [](const plan_ranker::SBEStatsDetails& details) { + return calculateNumberOfReads( + details.candidatePlanStats[0].get()); + }}, + why.stats); auto partition = _partitionedCache->lockOnePartition(key); auto [queryHash, planCacheKey, isNewEntryActive, shouldBeCreated, increasedWorks] = [&]() { diff --git a/src/mongo/db/query/plan_ranking_decision.h b/src/mongo/db/query/plan_ranking_decision.h index 8e8543b98e3..53db8f6a464 100644 --- a/src/mongo/db/query/plan_ranking_decision.h +++ b/src/mongo/db/query/plan_ranking_decision.h @@ -32,7 +32,7 @@ #include "mongo/db/exec/plan_stats.h" #include "mongo/db/exec/sbe/stages/plan_stats.h" #include "mongo/util/container_size_helper.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo::plan_ranker { struct StatsDetails { @@ -72,26 +72,25 @@ struct PlanRankingDecision { std::unique_ptr<PlanRankingDecision> clone() const { auto decision = std::make_unique<PlanRankingDecision>(); stdx::visit( - visit_helper::Overloaded{ - [&decision](const StatsDetails& details) { - std::vector<std::unique_ptr<PlanStageStats>> copy; - copy.reserve(details.candidatePlanStats.size()); - for (auto&& stats : details.candidatePlanStats) { - invariant(stats); - copy.emplace_back(stats->clone()); - } - decision->stats = StatsDetails{std::move(copy)}; - }, - [&decision](const SBEStatsDetails& details) { - std::vector<std::unique_ptr<mongo::sbe::PlanStageStats>> copy; - copy.reserve(details.candidatePlanStats.size()); - for (auto&& stats : details.candidatePlanStats) { - invariant(stats); - copy.emplace_back(stats->clone()); - } - decision->stats = - SBEStatsDetails{std::move(copy), details.serializedWinningPlan}; - }}, + OverloadedVisitor{[&decision](const StatsDetails& details) { + std::vector<std::unique_ptr<PlanStageStats>> copy; + copy.reserve(details.candidatePlanStats.size()); + for (auto&& stats : details.candidatePlanStats) { + invariant(stats); + copy.emplace_back(stats->clone()); + } + decision->stats = StatsDetails{std::move(copy)}; + }, + [&decision](const SBEStatsDetails& details) { + std::vector<std::unique_ptr<mongo::sbe::PlanStageStats>> copy; + copy.reserve(details.candidatePlanStats.size()); + for (auto&& stats : details.candidatePlanStats) { + invariant(stats); + copy.emplace_back(stats->clone()); + } + decision->stats = SBEStatsDetails{std::move(copy), + details.serializedWinningPlan}; + }}, stats); decision->scores = scores; decision->candidateOrder = candidateOrder; @@ -102,7 +101,7 @@ struct PlanRankingDecision { uint64_t estimateObjectSizeInBytes() const { return // Add size of 'stats' instance. stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](const StatsDetails& details) { return container_size_helper::estimateObjectSizeInBytes( details.candidatePlanStats, diff --git a/src/mongo/db/query/sbe_stage_builder_index_scan.cpp b/src/mongo/db/query/sbe_stage_builder_index_scan.cpp index b4f9025181f..30f80565655 100644 --- a/src/mongo/db/query/sbe_stage_builder_index_scan.cpp +++ b/src/mongo/db/query/sbe_stage_builder_index_scan.cpp @@ -54,7 +54,7 @@ #include "mongo/db/query/sbe_stage_builder_filter.h" #include "mongo/db/query/util/make_data_structure.h" #include "mongo/logv2/log.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" #include <boost/optional.hpp> #define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kQuery diff --git a/src/mongo/db/query/sbe_stage_builder_projection.cpp b/src/mongo/db/query/sbe_stage_builder_projection.cpp index bff2daf2f78..e45fa11ddd3 100644 --- a/src/mongo/db/query/sbe_stage_builder_projection.cpp +++ b/src/mongo/db/query/sbe_stage_builder_projection.cpp @@ -47,8 +47,8 @@ #include "mongo/db/query/sbe_stage_builder_filter.h" #include "mongo/db/query/tree_walker.h" #include "mongo/db/query/util/make_data_structure.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/util/str.h" -#include "mongo/util/visit_helper.h" namespace mongo::stage_builder { namespace { diff --git a/src/mongo/db/repl/oplog_entry.h b/src/mongo/db/repl/oplog_entry.h index 03ce6b7000d..506fe21e025 100644 --- a/src/mongo/db/repl/oplog_entry.h +++ b/src/mongo/db/repl/oplog_entry.h @@ -36,7 +36,7 @@ #include "mongo/db/repl/apply_ops_gen.h" #include "mongo/db/repl/oplog_entry_gen.h" #include "mongo/db/repl/optime.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo { namespace repl { @@ -47,8 +47,8 @@ std::vector<T> toVector(boost::optional<stdx::variant<T, std::vector<T>>> optVal if (!optVals) { return {}; } - return stdx::visit(visit_helper::Overloaded{[](T val) { return std::vector<T>{val}; }, - [](const std::vector<T>& vals) { return vals; }}, + return stdx::visit(OverloadedVisitor{[](T val) { return std::vector<T>{val}; }, + [](const std::vector<T>& vals) { return vals; }}, *optVals); } } // namespace variant_util diff --git a/src/mongo/db/s/balancer/balancer.cpp b/src/mongo/db/s/balancer/balancer.cpp index ebd2079f504..b6081dd3982 100644 --- a/src/mongo/db/s/balancer/balancer.cpp +++ b/src/mongo/db/s/balancer/balancer.cpp @@ -556,7 +556,7 @@ void Balancer::_consumeActionStreamLoop() { _outstandingStreamingOps.fetchAndAdd(1); stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&, selectedStream](MergeInfo&& mergeAction) { applyThrottling(); auto result = diff --git a/src/mongo/db/s/balancer/balancer_defragmentation_policy_impl.cpp b/src/mongo/db/s/balancer/balancer_defragmentation_policy_impl.cpp index 8171e6e7460..89f45fd7644 100644 --- a/src/mongo/db/s/balancer/balancer_defragmentation_policy_impl.cpp +++ b/src/mongo/db/s/balancer/balancer_defragmentation_policy_impl.cpp @@ -260,63 +260,64 @@ public: return; } stdx::visit( - visit_helper::Overloaded{ - [&](const MergeInfo& mergeAction) { - auto& mergeResponse = stdx::get<Status>(response); - auto& shardingPendingActions = _pendingActionsByShards[mergeAction.shardId]; - handleActionResult( - opCtx, - _nss, - _uuid, - getType(), - mergeResponse, - [&]() { - shardingPendingActions.rangesWithoutDataSize.emplace_back( - mergeAction.chunkRange); - }, - [&]() { - shardingPendingActions.rangesToMerge.emplace_back( - mergeAction.chunkRange); - }, - [&]() { _abort(getType()); }); - }, - [&](const DataSizeInfo& dataSizeAction) { - auto& dataSizeResponse = stdx::get<StatusWith<DataSizeResponse>>(response); - handleActionResult( - opCtx, - _nss, - _uuid, - getType(), - dataSizeResponse.getStatus(), - [&]() { - ChunkType chunk(dataSizeAction.uuid, - dataSizeAction.chunkRange, - dataSizeAction.version, - dataSizeAction.shardId); - auto catalogManager = ShardingCatalogManager::get(opCtx); - catalogManager->setChunkEstimatedSize( - opCtx, - chunk, - dataSizeResponse.getValue().sizeBytes, - ShardingCatalogClient::kMajorityWriteConcern); - }, - [&]() { - auto& shardingPendingActions = - _pendingActionsByShards[dataSizeAction.shardId]; - shardingPendingActions.rangesWithoutDataSize.emplace_back( - dataSizeAction.chunkRange); - }, - [&]() { _abort(getType()); }); - }, - [&](const AutoSplitVectorInfo& _) { - uasserted(ErrorCodes::BadValue, "Unexpected action type"); - }, - [&](const SplitInfoWithKeyPattern& _) { - uasserted(ErrorCodes::BadValue, "Unexpected action type"); - }, - [&](const MigrateInfo& _) { - uasserted(ErrorCodes::BadValue, "Unexpected action type"); - }}, + OverloadedVisitor{[&](const MergeInfo& mergeAction) { + auto& mergeResponse = stdx::get<Status>(response); + auto& shardingPendingActions = + _pendingActionsByShards[mergeAction.shardId]; + handleActionResult( + opCtx, + _nss, + _uuid, + getType(), + mergeResponse, + [&]() { + shardingPendingActions.rangesWithoutDataSize.emplace_back( + mergeAction.chunkRange); + }, + [&]() { + shardingPendingActions.rangesToMerge.emplace_back( + mergeAction.chunkRange); + }, + [&]() { _abort(getType()); }); + }, + [&](const DataSizeInfo& dataSizeAction) { + auto& dataSizeResponse = + stdx::get<StatusWith<DataSizeResponse>>(response); + handleActionResult( + opCtx, + _nss, + _uuid, + getType(), + dataSizeResponse.getStatus(), + [&]() { + ChunkType chunk(dataSizeAction.uuid, + dataSizeAction.chunkRange, + dataSizeAction.version, + dataSizeAction.shardId); + auto catalogManager = ShardingCatalogManager::get(opCtx); + catalogManager->setChunkEstimatedSize( + opCtx, + chunk, + dataSizeResponse.getValue().sizeBytes, + ShardingCatalogClient::kMajorityWriteConcern); + }, + [&]() { + auto& shardingPendingActions = + _pendingActionsByShards[dataSizeAction.shardId]; + shardingPendingActions.rangesWithoutDataSize.emplace_back( + dataSizeAction.chunkRange); + }, + [&]() { _abort(getType()); }); + }, + [&](const AutoSplitVectorInfo& _) { + uasserted(ErrorCodes::BadValue, "Unexpected action type"); + }, + [&](const SplitInfoWithKeyPattern& _) { + uasserted(ErrorCodes::BadValue, "Unexpected action type"); + }, + [&](const MigrateInfo& _) { + uasserted(ErrorCodes::BadValue, "Unexpected action type"); + }}, action); } @@ -472,7 +473,7 @@ public: const DefragmentationAction& action, const DefragmentationActionResponse& response) override { stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const MigrateInfo& migrationAction) { auto& migrationResponse = stdx::get<Status>(response); auto match = @@ -1095,36 +1096,35 @@ public: return; } stdx::visit( - visit_helper::Overloaded{ - [&](const MergeInfo& mergeAction) { - auto& mergeResponse = stdx::get<Status>(response); - auto onSuccess = [] {}; - auto onRetriableError = [&] { - _unmergedRangesByShard[mergeAction.shardId].emplace_back( - mergeAction.chunkRange); - }; - auto onNonretriableError = [this] { _abort(getType()); }; - handleActionResult(opCtx, - _nss, - _uuid, - getType(), - mergeResponse, - onSuccess, - onRetriableError, - onNonretriableError); - }, - [&](const DataSizeInfo& _) { - uasserted(ErrorCodes::BadValue, "Unexpected action type"); - }, - [&](const AutoSplitVectorInfo& _) { - uasserted(ErrorCodes::BadValue, "Unexpected action type"); - }, - [&](const SplitInfoWithKeyPattern& _) { - uasserted(ErrorCodes::BadValue, "Unexpected action type"); - }, - [&](const MigrateInfo& _) { - uasserted(ErrorCodes::BadValue, "Unexpected action type"); - }}, + OverloadedVisitor{[&](const MergeInfo& mergeAction) { + auto& mergeResponse = stdx::get<Status>(response); + auto onSuccess = [] {}; + auto onRetriableError = [&] { + _unmergedRangesByShard[mergeAction.shardId].emplace_back( + mergeAction.chunkRange); + }; + auto onNonretriableError = [this] { _abort(getType()); }; + handleActionResult(opCtx, + _nss, + _uuid, + getType(), + mergeResponse, + onSuccess, + onRetriableError, + onNonretriableError); + }, + [&](const DataSizeInfo& _) { + uasserted(ErrorCodes::BadValue, "Unexpected action type"); + }, + [&](const AutoSplitVectorInfo& _) { + uasserted(ErrorCodes::BadValue, "Unexpected action type"); + }, + [&](const SplitInfoWithKeyPattern& _) { + uasserted(ErrorCodes::BadValue, "Unexpected action type"); + }, + [&](const MigrateInfo& _) { + uasserted(ErrorCodes::BadValue, "Unexpected action type"); + }}, action); } @@ -1280,7 +1280,7 @@ public: return; } stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const MergeInfo& _) { uasserted(ErrorCodes::BadValue, "Unexpected action type"); }, diff --git a/src/mongo/db/s/balancer/balancer_defragmentation_policy_test.cpp b/src/mongo/db/s/balancer/balancer_defragmentation_policy_test.cpp index d1f431b4082..a34c79ffc33 100644 --- a/src/mongo/db/s/balancer/balancer_defragmentation_policy_test.cpp +++ b/src/mongo/db/s/balancer/balancer_defragmentation_policy_test.cpp @@ -565,7 +565,7 @@ TEST_F(BalancerDefragmentationPolicyTest, PhaseOneNotConsecutive) { uint8_t timesMiddleRangeDataSizeFound = 0; auto inspectAction = [&](const DefragmentationAction& action) { stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const MergeInfo& mergeAction) { if (mergeAction.chunkRange.getMin().woCompare(kKeyAtMin) == 0 && mergeAction.chunkRange.getMax().woCompare(BSON("x" << 5)) == 0) { diff --git a/src/mongo/db/s/balancer/cluster_chunks_resize_policy_impl.cpp b/src/mongo/db/s/balancer/cluster_chunks_resize_policy_impl.cpp index 2c7f98e4b97..4ea6fa8b63f 100644 --- a/src/mongo/db/s/balancer/cluster_chunks_resize_policy_impl.cpp +++ b/src/mongo/db/s/balancer/cluster_chunks_resize_policy_impl.cpp @@ -383,7 +383,7 @@ void ClusterChunksResizePolicyImpl::applyActionResult(OperationContext* opCtx, } auto updatedEntryIt = stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const AutoSplitVectorInfo& act) mutable { auto& swSplitVectorResult = stdx::get<StatusWith<AutoSplitVectorResponse>>(result); auto match = _collectionsBeingProcessed.find(act.uuid); diff --git a/src/mongo/db/s/resharding/resharding_metrics.cpp b/src/mongo/db/s/resharding/resharding_metrics.cpp index 2f843b4f589..3a86497bfd1 100644 --- a/src/mongo/db/s/resharding/resharding_metrics.cpp +++ b/src/mongo/db/s/resharding/resharding_metrics.cpp @@ -144,7 +144,7 @@ std::unique_ptr<ReshardingMetrics> ReshardingMetrics::makeInstance(UUID instance StringData ReshardingMetrics::getStateString() const noexcept { return stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](CoordinatorStateEnum state) { return CoordinatorState_serializer(state); }, [](RecipientStateEnum state) { return RecipientState_serializer(state); }, [](DonorStateEnum state) { return DonorState_serializer(state); }}, diff --git a/src/mongo/db/storage/duplicate_key_error_info.cpp b/src/mongo/db/storage/duplicate_key_error_info.cpp index 4a724f2ef09..ea5dfd678a2 100644 --- a/src/mongo/db/storage/duplicate_key_error_info.cpp +++ b/src/mongo/db/storage/duplicate_key_error_info.cpp @@ -35,8 +35,8 @@ #include "mongo/bson/bsonobjbuilder.h" #include "mongo/util/assert_util.h" #include "mongo/util/hex.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/util/text.h" -#include "mongo/util/visit_helper.h" namespace mongo { namespace { @@ -95,7 +95,7 @@ void DuplicateKeyErrorInfo::serialize(BSONObjBuilder* bob) const { } stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](stdx::monostate) {}, [bob](const RecordId& rid) { rid.serializeToken("foundValue", bob); }, [bob](const BSONObj& obj) { diff --git a/src/mongo/db/storage/index_entry_comparison.cpp b/src/mongo/db/storage/index_entry_comparison.cpp index 50ef5509367..d93c1eac7b2 100644 --- a/src/mongo/db/storage/index_entry_comparison.cpp +++ b/src/mongo/db/storage/index_entry_comparison.cpp @@ -231,7 +231,7 @@ Status buildDupKeyErrorStatus(const BSONObj& key, sb << builderForErrmsg.obj(); stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](stdx::monostate) {}, [&sb](const RecordId& rid) { sb << " found value: " << rid; }, [&sb](const BSONObj& obj) { diff --git a/src/mongo/db/storage/index_entry_comparison_test.cpp b/src/mongo/db/storage/index_entry_comparison_test.cpp index eef2b5c2651..76661cdb381 100644 --- a/src/mongo/db/storage/index_entry_comparison_test.cpp +++ b/src/mongo/db/storage/index_entry_comparison_test.cpp @@ -51,7 +51,7 @@ void buildDupKeyErrorStatusProducesExpectedErrorObject( expectedObjBuilder.append("keyPattern", keyPattern); expectedObjBuilder.append("keyValue", keyValueWithFieldName); stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [](stdx::monostate) {}, [&](const RecordId& rid) { rid.serializeToken("foundValue", &expectedObjBuilder); }, [&](const BSONObj& obj) { expectedObjBuilder.append("foundValue", obj); }, diff --git a/src/mongo/db/ttl.cpp b/src/mongo/db/ttl.cpp index 73f3727776a..d44ef72a6c6 100644 --- a/src/mongo/db/ttl.cpp +++ b/src/mongo/db/ttl.cpp @@ -407,16 +407,17 @@ bool TTLMonitor::_doTTLIndexDelete(OperationContext* opCtx, ResourceConsumption::ScopedMetricsCollector scopedMetrics(opCtx, nss->db().toString()); const auto& collection = coll.getCollection(); - return stdx::visit( - visit_helper::Overloaded{[&](const TTLCollectionCache::ClusteredId&) { - return _deleteExpiredWithCollscan( - opCtx, ttlCollectionCache, collection); - }, - [&](const TTLCollectionCache::IndexName& indexName) { - return _deleteExpiredWithIndex( - opCtx, ttlCollectionCache, collection, indexName); - }}, - info); + return stdx::visit(OverloadedVisitor{[&](const TTLCollectionCache::ClusteredId&) { + return _deleteExpiredWithCollscan( + opCtx, ttlCollectionCache, collection); + }, + [&](const TTLCollectionCache::IndexName& indexName) { + return _deleteExpiredWithIndex(opCtx, + ttlCollectionCache, + collection, + indexName); + }}, + info); } catch (const ExceptionForCat<ErrorCategory::Interruption>&) { // The exception is relevant to the entire TTL monitoring process, not just the specific TTL // index. Let the exception escape so it can be addressed at the higher monitoring layer. diff --git a/src/mongo/db/update/document_diff_applier.cpp b/src/mongo/db/update/document_diff_applier.cpp index ec592ef3363..e9130b670f9 100644 --- a/src/mongo/db/update/document_diff_applier.cpp +++ b/src/mongo/db/update/document_diff_applier.cpp @@ -34,8 +34,8 @@ #include "mongo/db/update_index_data.h" #include "mongo/stdx/variant.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/util/string_map.h" -#include "mongo/util/visit_helper.h" namespace mongo::doc_diff { namespace { @@ -250,7 +250,7 @@ int32_t computeDamageOnObject(const BSONObj& preImageRoot, } stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](Delete) { appendDamage(damages, 0, 0, targetOffset, elt.size()); diffSize -= elt.size(); @@ -332,7 +332,7 @@ int32_t computeDamageForArrayIndex(const BSONObj& preImageRoot, bool mustCheckExistenceForInsertOperations) { int32_t diffSize = 0; stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&](const BSONElement& update) { invariant(!update.eoo()); auto preValuePos = arrayPreImage.end()->rawdata(); @@ -520,7 +520,7 @@ public: FieldRef::FieldRefTempAppend tempAppend(*path, elt.fieldNameStringData()); stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [this, &path](Delete) { // Do not append anything. updateIndexesAffected(path); @@ -615,7 +615,7 @@ private: const ArrayDiffReader::ArrayModification& modification, BSONArrayBuilder* builder) { stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [this, &path, builder](const BSONElement& update) { invariant(!update.eoo()); builder->append(update); diff --git a/src/mongo/db/update/document_diff_serialization.cpp b/src/mongo/db/update/document_diff_serialization.cpp index 0f5533e1d06..ccda45d8443 100644 --- a/src/mongo/db/update/document_diff_serialization.cpp +++ b/src/mongo/db/update/document_diff_serialization.cpp @@ -121,20 +121,19 @@ void appendElementToBuilder(stdx::variant<mutablebson::Element, BSONElement> ele StringData fieldName, BSONObjBuilder* builder) { stdx::visit( - visit_helper::Overloaded{ - [&](const mutablebson::Element& element) { - if (element.hasValue()) { - builder->appendAs(element.getValue(), fieldName); - } else if (element.getType() == BSONType::Object) { - BSONObjBuilder subBuilder(builder->subobjStart(fieldName)); - element.writeChildrenTo(&subBuilder); - } else { - invariant(element.getType() == BSONType::Array); - BSONArrayBuilder subBuilder(builder->subarrayStart(fieldName)); - element.writeArrayTo(&subBuilder); - } - }, - [&](BSONElement element) { builder->appendAs(element, fieldName); }}, + OverloadedVisitor{[&](const mutablebson::Element& element) { + if (element.hasValue()) { + builder->appendAs(element.getValue(), fieldName); + } else if (element.getType() == BSONType::Object) { + BSONObjBuilder subBuilder(builder->subobjStart(fieldName)); + element.writeChildrenTo(&subBuilder); + } else { + invariant(element.getType() == BSONType::Array); + BSONArrayBuilder subBuilder(builder->subarrayStart(fieldName)); + element.writeArrayTo(&subBuilder); + } + }, + [&](BSONElement element) { builder->appendAs(element, fieldName); }}, elem); } @@ -486,11 +485,9 @@ boost::optional<std::pair<size_t, ArrayDiffReader::ArrayModification>> ArrayDiff str::stream() << "expected sub diff at index " << idx << " but got " << next, next.type() == BSONType::Object); - auto modification = - stdx::visit(visit_helper::Overloaded{[](const auto& reader) -> ArrayModification { - return {reader}; - }}, - getReader(next.embeddedObject())); + auto modification = stdx::visit( + OverloadedVisitor{[](const auto& reader) -> ArrayModification { return {reader}; }}, + getReader(next.embeddedObject())); return {{idx, modification}}; } else { uasserted(4770502, diff --git a/src/mongo/db/update/document_diff_serialization.h b/src/mongo/db/update/document_diff_serialization.h index 9817088495f..907638f413d 100644 --- a/src/mongo/db/update/document_diff_serialization.h +++ b/src/mongo/db/update/document_diff_serialization.h @@ -35,8 +35,8 @@ #include "mongo/bson/mutable/document.h" #include "mongo/stdx/variant.h" #include "mongo/util/itoa.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/util/string_map.h" -#include "mongo/util/visit_helper.h" // This file contains classes for serializing document diffs to a format that can be stored in the // oplog. Any code/machinery which manipulates document diffs should do so through these classes. diff --git a/src/mongo/db/update/update_driver.cpp b/src/mongo/db/update/update_driver.cpp index dcb164f0ace..9014ea37ce7 100644 --- a/src/mongo/db/update/update_driver.cpp +++ b/src/mongo/db/update/update_driver.cpp @@ -49,8 +49,8 @@ #include "mongo/db/update/update_oplog_entry_version.h" #include "mongo/stdx/variant.h" #include "mongo/util/embedded_builder.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/util/str.h" -#include "mongo/util/visit_helper.h" namespace mongo { diff --git a/src/mongo/db/write_concern_options.cpp b/src/mongo/db/write_concern_options.cpp index c87e21691fc..9a0faf2b361 100644 --- a/src/mongo/db/write_concern_options.cpp +++ b/src/mongo/db/write_concern_options.cpp @@ -222,14 +222,13 @@ WriteConcernW deserializeWriteConcernW(BSONElement wEl) { } void serializeWriteConcernW(const WriteConcernW& w, StringData fieldName, BSONObjBuilder* builder) { - stdx::visit( - visit_helper::Overloaded{[&](int64_t wNumNodes) { - builder->appendNumber(fieldName, - static_cast<long long>(wNumNodes)); - }, - [&](std::string wMode) { builder->append(fieldName, wMode); }, - [&](WTags wTags) { builder->append(fieldName, wTags); }}, - w); + stdx::visit(OverloadedVisitor{[&](int64_t wNumNodes) { + builder->appendNumber(fieldName, + static_cast<long long>(wNumNodes)); + }, + [&](std::string wMode) { builder->append(fieldName, wMode); }, + [&](WTags wTags) { builder->append(fieldName, wTags); }}, + w); } std::int64_t parseWTimeoutFromBSON(BSONElement element) { diff --git a/src/mongo/idl/basic_types.h b/src/mongo/idl/basic_types.h index 4b77f57461d..5d835e64707 100644 --- a/src/mongo/idl/basic_types.h +++ b/src/mongo/idl/basic_types.h @@ -30,7 +30,7 @@ #pragma once #include "mongo/util/assert_util.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" #include <boost/optional.hpp> #include "mongo/base/string_data.h" diff --git a/src/mongo/s/commands/cluster_rename_collection_cmd.cpp b/src/mongo/s/commands/cluster_rename_collection_cmd.cpp index 98584802646..7fdb7767d47 100644 --- a/src/mongo/s/commands/cluster_rename_collection_cmd.cpp +++ b/src/mongo/s/commands/cluster_rename_collection_cmd.cpp @@ -81,7 +81,7 @@ public: renameCollReq.setStayTemp(request().getStayTemp()); renameCollReq.setExpectedSourceUUID(request().getCollectionUUID()); stdx::visit( - visit_helper::Overloaded{ + OverloadedVisitor{ [&renameCollReq](bool dropTarget) { renameCollReq.setDropTarget(dropTarget); }, [&renameCollReq](const UUID& uuid) { renameCollReq.setDropTarget(true); diff --git a/src/mongo/s/write_ops/batched_command_request.cpp b/src/mongo/s/write_ops/batched_command_request.cpp index c33280790d2..5b1bca59b5d 100644 --- a/src/mongo/s/write_ops/batched_command_request.cpp +++ b/src/mongo/s/write_ops/batched_command_request.cpp @@ -31,7 +31,7 @@ #include "mongo/db/pipeline/variables.h" #include "mongo/s/write_ops/batched_command_request.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" #include "mongo/bson/bsonobj.h" @@ -116,27 +116,27 @@ std::size_t BatchedCommandRequest::sizeWriteOps() const { } bool BatchedCommandRequest::hasLegacyRuntimeConstants() const { - return _visit(visit_helper::Overloaded{[](write_ops::InsertCommandRequest&) { return false; }, - [&](write_ops::UpdateCommandRequest& op) { - return op.getLegacyRuntimeConstants().has_value(); - }, - [&](write_ops::DeleteCommandRequest& op) { - return op.getLegacyRuntimeConstants().has_value(); - }}); -} - -void BatchedCommandRequest::setLegacyRuntimeConstants(LegacyRuntimeConstants runtimeConstants) { - _visit(visit_helper::Overloaded{[](write_ops::InsertCommandRequest&) {}, + return _visit(OverloadedVisitor{[](write_ops::InsertCommandRequest&) { return false; }, [&](write_ops::UpdateCommandRequest& op) { - op.setLegacyRuntimeConstants(std::move(runtimeConstants)); + return op.getLegacyRuntimeConstants().has_value(); }, [&](write_ops::DeleteCommandRequest& op) { - op.setLegacyRuntimeConstants(std::move(runtimeConstants)); + return op.getLegacyRuntimeConstants().has_value(); }}); } +void BatchedCommandRequest::setLegacyRuntimeConstants(LegacyRuntimeConstants runtimeConstants) { + _visit(OverloadedVisitor{[](write_ops::InsertCommandRequest&) {}, + [&](write_ops::UpdateCommandRequest& op) { + op.setLegacyRuntimeConstants(std::move(runtimeConstants)); + }, + [&](write_ops::DeleteCommandRequest& op) { + op.setLegacyRuntimeConstants(std::move(runtimeConstants)); + }}); +} + void BatchedCommandRequest::unsetLegacyRuntimeConstants() { - _visit(visit_helper::Overloaded{ + _visit(OverloadedVisitor{ [](write_ops::InsertCommandRequest&) {}, [&](write_ops::UpdateCommandRequest& op) { op.setLegacyRuntimeConstants(boost::none); }, [&](write_ops::DeleteCommandRequest& op) { op.setLegacyRuntimeConstants(boost::none); }}); diff --git a/src/mongo/s/write_ops/batched_command_request.h b/src/mongo/s/write_ops/batched_command_request.h index eea7f7bbe11..ea2512da86d 100644 --- a/src/mongo/s/write_ops/batched_command_request.h +++ b/src/mongo/s/write_ops/batched_command_request.h @@ -36,7 +36,7 @@ #include "mongo/rpc/op_msg.h" #include "mongo/s/chunk_version.h" #include "mongo/s/database_version.h" -#include "mongo/util/visit_helper.h" +#include "mongo/util/overloaded_visitor.h" namespace mongo { diff --git a/src/mongo/util/SConscript b/src/mongo/util/SConscript index ef164a32031..92eb09c5e07 100644 --- a/src/mongo/util/SConscript +++ b/src/mongo/util/SConscript @@ -713,7 +713,6 @@ icuEnv.CppUnitTest( 'histogram_test.cpp', 'hierarchical_acquisition_test.cpp', 'icu_test.cpp', - 'static_immortal_test.cpp', 'invalidating_lru_cache_test.cpp', 'itoa_test.cpp', 'latch_analyzer_test.cpp' if get_option('use-diagnostic-latches') == 'on' else [], @@ -723,6 +722,7 @@ icuEnv.CppUnitTest( 'md5_test.cpp', 'md5main.cpp', 'out_of_line_executor_test.cpp', + 'overloaded_visitor_test.cpp', 'packaged_task_test.cpp', 'pcre_test.cpp', 'pcre_util_test.cpp', @@ -738,6 +738,7 @@ icuEnv.CppUnitTest( 'scoped_unlock_test.cpp', 'secure_zero_memory_test.cpp', 'signal_handlers_synchronous_test.cpp' if not env.TargetOSIs('windows') else [], + 'static_immortal_test.cpp', 'str_test.cpp', 'string_map_test.cpp', 'strong_weak_finish_line_test.cpp', diff --git a/src/mongo/util/visit_helper.h b/src/mongo/util/overloaded_visitor.h index 435e05ee36f..4ffad22d50a 100644 --- a/src/mongo/util/visit_helper.h +++ b/src/mongo/util/overloaded_visitor.h @@ -30,27 +30,23 @@ #pragma once namespace mongo { -namespace visit_helper { /** - * This is the "overload pattern" designed to be used with std::visit. Example usage: + * This is the "overload pattern" for use with variant visit calls. + * See https://www.modernescpp.com/index.php/visiting-a-std-variant-with-the-overload-pattern + * Example usage: * - * auto result = std::visit( - * visit_helper::Overloaded{ - * [](int a) { - * ... - * }, - * [](StringData b) { - * ... - * }, - * }, - * someVariant); + * auto r = stdx::visit(OverloadedVisitor{ + * [](int v) { return intStuff(v); }, + * [](StringData v) { return stringStuff(v); }, + * }, + * someStdxVariant); */ -template <class... Ts> -struct Overloaded : Ts... { +template <typename... Ts> +struct OverloadedVisitor : Ts... { using Ts::operator()...; }; -template <class... Ts> -Overloaded(Ts...)->Overloaded<Ts...>; -} // namespace visit_helper +template <typename... 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 new file mode 100644 index 00000000000..0a900471162 --- /dev/null +++ b/src/mongo/util/overloaded_visitor_test.cpp @@ -0,0 +1,108 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#include "mongo/util/overloaded_visitor.h" + +#include <string> +#include <utility> + +#include "mongo/stdx/variant.h" +#include "mongo/unittest/unittest.h" + +namespace mongo { +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); + }; + ASSERT_EQ(doVisit(123), 1); + ASSERT_EQ(doVisit(std::string("hi")), 2); +} + +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); + }; + ASSERT_EQ(doVisit(123), 1); + ASSERT_EQ(doVisit(std::string("hi")), 2); +} + +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); + }; + ASSERT_EQ(doVisit(123LL), 1); + ASSERT_EQ(doVisit(123L), 2); + ASSERT_EQ(doVisit(123), 3); +} + +TEST(OverloadedVisitorTest, MultiVisit) { + stdx::variant<int, std::string> var1; + 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); + }; + ASSERT_EQ(doVisit(123, 123), 0); + ASSERT_EQ(doVisit(123, "b"), 1); + ASSERT_EQ(doVisit(123, 0.5), 2); + ASSERT_EQ(doVisit("a", 123), 3); + ASSERT_EQ(doVisit("a", "b"), 4); + ASSERT_EQ(doVisit("a", 0.5), 5); +} + +} // namespace +} // namespace mongo |