1
0
Fork 0

C++17 clean up (#10287)

This commit is contained in:
Jan Christoph Uhde 2019-11-11 08:49:54 +01:00 committed by Jan
parent 90a4db9440
commit 484e2971d6
159 changed files with 896 additions and 883 deletions

View File

@ -36,6 +36,11 @@
#include <functional>
#include <type_traits>
#if __cplusplus >= 201703L
#include <string_view>
#define VELOCYPACK_HAS_STRING_VIEW 1
#endif
#include "velocypack/velocypack-common.h"
#include "velocypack/Exception.h"
#include "velocypack/Options.h"
@ -710,6 +715,12 @@ class Slice {
throw Exception(Exception::InvalidValueType, "Expecting type String");
}
#ifdef VELOCYPACK_HAS_STRING_VIEW
std::string_view stringView() const {
StringRef ref = this->stringRef();
return std::string_view(ref.data(), ref.size());
}
#endif
// return the value for a Binary object
uint8_t const* getBinary(ValueLength& length) const {

View File

@ -75,7 +75,7 @@ std::shared_ptr<TRI_action_t> TRI_DefineActionVocBase(std::string const& name,
WRITE_LOCKER(writeLocker, ActionsLock);
// create a new action and store the callback function
auto it = which->emplace(url, action);
auto it = which->try_emplace(url, action);
if (!it.second) {
return (*(it.first)).second;

View File

@ -72,7 +72,7 @@ bool FailedServer::start(bool& aborts) {
LOG_TOPIC("a04da", INFO, Logger::SUPERVISION) << reason.str();
finish(_server, "", false, reason.str());
return false;
} else if(!status.second) {
} else if (!status.second) {
std::stringstream reason;
reason << "Server " << _server << " no longer in health. Already removed. Abort.";
LOG_TOPIC("1479a", INFO, Logger::SUPERVISION) << reason.str();

View File

@ -189,9 +189,9 @@ bool RemoveFollower::start(bool&) {
for (VPackSlice srv : VPackArrayIterator(planned)) {
std::string serverName = srv.copyString();
if (checkServerHealth(_snapshot, serverName) == "GOOD") {
overview.emplace(serverName, 0);
overview.try_emplace(serverName, 0);
} else {
overview.emplace(serverName, -1);
overview.try_emplace(serverName, -1);
if (serverName == planned[0].copyString()) {
leaderBad = true;
}

View File

@ -84,7 +84,7 @@ Function const* AqlFunctionFeature::getFunctionByName(std::string const& name) {
void AqlFunctionFeature::add(Function const& func) {
TRI_ASSERT(_functionNames.find(func.name) == _functionNames.end());
// add function to the map
_functionNames.emplace(func.name, func);
_functionNames.try_emplace(func.name, func);
}
void AqlFunctionFeature::addAlias(std::string const& alias, std::string const& original) {

View File

@ -650,7 +650,7 @@ void AqlItemBlock::toVelocyPack(transaction::Methods* trx, VPackBuilder& result)
if (it == table.end()) {
currentState = Next;
a.toVelocyPack(trx, raw, false);
table.emplace(a, pos++);
table.try_emplace(a, pos++);
} else {
currentState = Positional;
tablePos = it->second;

View File

@ -127,7 +127,7 @@ class AqlItemBlock {
} catch (...) {
// invoke dtor
value->~AqlValue();
// TODO - instead of disabling it completly we could you use
// TODO - instead of disabling it completely we could you use
// a constexpr if() with c++17
_data[address].destroy();
throw;

View File

@ -1624,6 +1624,7 @@ AqlValueMaterializer::AqlValueMaterializer(AqlValueMaterializer const& other)
AqlValueMaterializer& AqlValueMaterializer::operator=(AqlValueMaterializer const& other) {
if (this != &other) {
TRI_ASSERT(trx == other.trx); // must be from same transaction
trx = other.trx; // to shut up cppcheck
if (hasCopied) {
// destroy our own slice
materialized.destroy();
@ -1647,6 +1648,7 @@ AqlValueMaterializer::AqlValueMaterializer(AqlValueMaterializer&& other) noexcep
AqlValueMaterializer& AqlValueMaterializer::operator=(AqlValueMaterializer&& other) noexcept {
if (this != &other) {
TRI_ASSERT(trx == other.trx); // must be from same transaction
trx = other.trx; // to shut up cppcheck
if (hasCopied) {
// destroy our own slice
materialized.destroy();

View File

@ -40,6 +40,7 @@
#include "Basics/Exceptions.h"
#include "Basics/StringUtils.h"
#include "Basics/tri-strings.h"
#include "Basics/tryEmplaceHelper.h"
#include "Cluster/ClusterFeature.h"
#include "Cluster/ClusterInfo.h"
#include "Containers/SmallVector.h"
@ -1132,7 +1133,7 @@ AstNode* Ast::createNodeIntersectedArray(AstNode const* lhs, AstNode const* rhs)
auto member = lhs->getMemberUnchecked(i);
VPackSlice slice = member->computeValue();
cache.emplace(slice, member);
cache.try_emplace(slice, member);
}
auto node = createNodeArray(cache.size() + nr);
@ -1176,7 +1177,7 @@ AstNode* Ast::createNodeUnionizedArray(AstNode const* lhs, AstNode const* rhs) {
}
VPackSlice slice = member->computeValue();
if (cache.emplace(slice, member).second) {
if (cache.try_emplace(slice, member).second) {
// only insert unique values
node->addMember(member);
}
@ -1876,7 +1877,7 @@ void Ast::validateAndOptimize() {
return false;
} else if (node->type == NODE_TYPE_COLLECTION) {
// note the level on which we first saw a collection
ctx->collectionsFirstSeen.emplace(node->getString(), ctx->nestingLevel);
ctx->collectionsFirstSeen.try_emplace(node->getString(), ctx->nestingLevel);
} else if (node->type == NODE_TYPE_AGGREGATIONS) {
++ctx->stopOptimizationRequests;
} else if (node->type == NODE_TYPE_SUBQUERY) {
@ -2069,7 +2070,7 @@ void Ast::validateAndOptimize() {
definition = (*it).second;
}
ctx->variableDefinitions.emplace(variable, definition);
ctx->variableDefinitions.try_emplace(variable, definition);
return this->optimizeLet(node);
}
@ -2217,13 +2218,13 @@ TopLevelAttributes Ast::getReferencedAttributes(AstNode const* node, bool& isSaf
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
auto it = result.find(variable);
if (it == result.end()) {
// insert variable and attributeName
result.emplace(variable, std::unordered_set<std::string>(
{std::string(attributeName, nameLength)}));
} else {
auto[it, emp] = result.try_emplace(
variable,
arangodb::lazyConstruct([&]{
return std::unordered_set<std::string>( {std::string(attributeName, nameLength)});
})
);
if (emp) {
// insert attributeName only
(*it).second.emplace(attributeName, nameLength);
}
@ -2582,7 +2583,7 @@ AstNode const* Ast::deduplicateArray(AstNode const* node) {
VPackSlice slice = member->computeValue();
if (cache.find(slice) == cache.end()) {
cache.emplace(slice, member);
cache.try_emplace(slice, member);
}
}

View File

@ -61,7 +61,7 @@ void BindParameters::process() {
}
for (auto it : VPackObjectIterator(slice, false)) {
std::string const key(it.key.copyString());
auto const key(it.key.copyString());
VPackSlice const value(it.value);
if (value.isNone()) {
@ -73,7 +73,7 @@ void BindParameters::process() {
THROW_ARANGO_EXCEPTION_PARAMS(TRI_ERROR_QUERY_BIND_PARAMETER_TYPE, key.c_str());
}
_parameters.emplace(std::move(key), std::make_pair(value, false));
_parameters.try_emplace(std::move(key), value, false);
}
_processed = true;

View File

@ -68,7 +68,7 @@ BlocksWithClients::BlocksWithClients(ExecutionEngine* engine, ExecutionNode cons
_wasShutdown(false) {
_shardIdMap.reserve(_nrClients);
for (size_t i = 0; i < _nrClients; i++) {
_shardIdMap.emplace(std::make_pair(shardIds[i], i));
_shardIdMap.try_emplace(shardIds[i], i);
}
auto scatter = ExecutionNode::castTo<ScatterNode const*>(ep);
TRI_ASSERT(scatter != nullptr);

View File

@ -124,7 +124,7 @@ struct Collection {
void addShardToServer(ShardID const& sid, ServerID const& server) const {
// Cannot add the same shard twice!
TRI_ASSERT(_shardToServerMapping.find(sid) == _shardToServerMapping.end());
_shardToServerMapping.emplace(sid, server);
_shardToServerMapping.try_emplace(sid, server);
}
/// @brief lookup the server responsible for the given shard.

View File

@ -58,7 +58,7 @@ Collection* Collections::add(std::string const& name, AccessMode::Type accessTyp
}
auto collection = std::make_unique<Collection>(name, _vocbase, accessType);
_collections.emplace(name, collection.get());
_collections.try_emplace(name, collection.get());
return collection.release();
}

View File

@ -29,6 +29,8 @@
#include "Aql/IndexNode.h"
#include "Aql/SortCondition.h"
#include "Aql/SortNode.h"
#include "Basics/tryEmplaceHelper.h"
using namespace arangodb::aql;
using EN = arangodb::aql::ExecutionNode;
@ -93,7 +95,7 @@ bool ConditionFinder::before(ExecutionNode* en) {
}
case EN::CALCULATION: {
_variableDefinitions.emplace(
_variableDefinitions.try_emplace(
ExecutionNode::castTo<CalculationNode const*>(en)->outVariable()->id,
ExecutionNode::castTo<CalculationNode const*>(en)->expression()->node());
TRI_IF_FAILURE("ConditionFinder::variableDefinition") {
@ -146,16 +148,19 @@ bool ConditionFinder::before(ExecutionNode* en) {
// will clear out usedIndexes
IndexIteratorOptions opts;
opts.ascending = !descending;
std::unique_ptr<ExecutionNode> newNode(
new IndexNode(_plan, _plan->nextId(), node->collection(),
node->outVariable(), usedIndexes, std::move(condition), opts));
TRI_IF_FAILURE("ConditionFinder::insertIndexNode") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}
// We keep this node's change
_changes->emplace(node->id(), newNode.get());
newNode.release();
_changes->try_emplace(
node->id(),
arangodb::lazyConstruct([&]{
return new IndexNode(_plan, _plan->nextId(), node->collection(),
node->outVariable(), usedIndexes, std::move(condition), opts);
})
);
}
break;

View File

@ -101,7 +101,7 @@ EngineInfoContainerDBServerServerBased::TraverserEngineShardLists::TraverserEngi
}
}
#endif
_vertexCollections.emplace(col->name(), std::move(shards));
_vertexCollections.try_emplace(col->name(), std::move(shards));
}
}

View File

@ -171,7 +171,7 @@ std::pair<ExecutionState, SharedAqlItemBlockPtr> ExecutionBlock::traceGetSomeEnd
if (it != _engine->_stats.nodes.end()) {
it->second += stats;
} else {
_engine->_stats.nodes.emplace(en->id(), stats);
_engine->_stats.nodes.try_emplace(en->id(), stats);
}
if (_profile >= PROFILE_LEVEL_TRACE_1) {
@ -238,7 +238,7 @@ std::pair<ExecutionState, size_t> ExecutionBlock::traceSkipSomeEnd(
if (it != _engine->_stats.nodes.end()) {
it->second += stats;
} else {
_engine->_stats.nodes.emplace(en->id(), stats);
_engine->_stats.nodes.try_emplace(en->id(), stats);
}
if (_profile >= PROFILE_LEVEL_TRACE_1) {

View File

@ -117,7 +117,7 @@ ExecutionBlockImpl<Executor>::ExecutionBlockImpl(ExecutionEngine* engine,
_state(InternalState::FETCH_DATA) {
// already insert ourselves into the statistics results
if (_profile >= PROFILE_LEVEL_BLOCKS) {
_engine->_stats.nodes.emplace(node->id(), ExecutionStats::Node());
_engine->_stats.nodes.try_emplace(node->id(), ExecutionStats::Node());
}
}

View File

@ -180,7 +180,7 @@ Result ExecutionEngine::createBlocks(std::vector<ExecutionNode*> const& nodes,
root(eb);
// put it into our cache:
cache.emplace(en, eb);
cache.try_emplace(en, eb);
}
return {TRI_ERROR_NO_ERROR};
}
@ -273,7 +273,7 @@ struct SingleServerQueryInstanciator final : public WalkerWorker<ExecutionNode>
block->addDependency(it2->second);
}
cache.emplace(en, block);
cache.try_emplace(en, block);
}
}

View File

@ -383,7 +383,7 @@ ExecutionNode::ExecutionNode(ExecutionPlan* plan, VPackSlice const& slice)
RegisterId registerId = it.get("RegisterId").getNumericValue<RegisterId>();
unsigned int depth = it.get("depth").getNumericValue<unsigned int>();
_registerPlan->varInfo.emplace(variableId, VarInfo(depth, registerId));
_registerPlan->varInfo.try_emplace(variableId, VarInfo(depth, registerId));
}
VPackSlice nrRegsList = slice.get("nrRegs");

View File

@ -818,8 +818,8 @@ ExecutionNode* ExecutionPlan::registerNode(std::unique_ptr<ExecutionNode> node)
TRI_ASSERT(node->plan() == this);
TRI_ASSERT(node->id() > 0);
TRI_ASSERT(_ids.find(node->id()) == _ids.end());
_ids.emplace(node->id(), node.get()); // take ownership
auto[it, emplaced] = _ids.try_emplace(node->id(), node.get()); // take ownership
TRI_ASSERT(emplaced);
return node.release();
}
@ -831,7 +831,10 @@ ExecutionNode* ExecutionPlan::registerNode(ExecutionNode* node) {
TRI_ASSERT(_ids.find(node->id()) == _ids.end());
try {
_ids.emplace(node->id(), node);
auto [it, emplaced] = _ids.try_emplace(node->id(), node);
if (!emplaced) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "unable to register node in plan");
}
} catch (...) {
delete node;
throw;

View File

@ -148,7 +148,7 @@ ExecutionStats::ExecutionStats(VPackSlice const& slice) : ExecutionStats() {
if (alias != _nodeAliases.end()) {
nid = alias->second;
}
nodes.emplace(nid, node);
nodes.try_emplace(nid, node);
}
}
}

View File

@ -51,7 +51,7 @@ AqlValue FixedVarExpressionContext::getVariableValue(Variable const* variable, b
void FixedVarExpressionContext::clearVariableValues() { _vars.clear(); }
void FixedVarExpressionContext::setVariableValue(Variable const* var, AqlValue const& value) {
_vars.emplace(var, value);
_vars.try_emplace(var, value);
}
void FixedVarExpressionContext::serializeAllVariables(transaction::Methods* trx,

View File

@ -4522,9 +4522,9 @@ AqlValue Functions::Sorted(ExpressionContext* expressionContext, transaction::Me
std::map<VPackSlice, size_t, arangodb::basics::VelocyPackHelper::VPackLess<true>> values(less);
for (VPackSlice it : VPackArrayIterator(slice)) {
if (!it.isNone()) {
auto f = values.emplace(it, 1);
if (!f.second) {
++(*f.first).second;
auto [itr, emplaced] = values.try_emplace(it, 1);
if (!emplaced) {
++itr->second;
}
}
}
@ -4672,7 +4672,7 @@ AqlValue Functions::Intersection(ExpressionContext* expressionContext,
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}
values.emplace(it, 1);
values.try_emplace(it, 1);
} else {
// check if we have seen the same element before
auto found = values.find(it);
@ -5609,7 +5609,7 @@ AqlValue Functions::Minus(ExpressionContext* expressionContext, transaction::Met
VPackArrayIterator it(arraySlice);
while (it.valid()) {
contains.emplace(it.value(), it.index());
contains.try_emplace(it.value(), it.index());
it.next();
}

View File

@ -151,7 +151,7 @@ GraphNode::GraphNode(ExecutionPlan* plan, size_t id, TRI_vocbase_t* vocbase,
// do not re-add the same collection!
continue;
}
seenCollections.emplace(eColName, dir);
seenCollections.try_emplace(eColName, dir);
auto collection = resolver->getCollection(eColName);
@ -282,7 +282,7 @@ GraphNode::GraphNode(ExecutionPlan* plan, arangodb::velocypack::Slice const& bas
_directions.emplace_back(d);
}
if(!ServerState::instance()->isDBServer()) {
if (!ServerState::instance()->isDBServer()) {
// Graph Information. Do we need to reload the graph here?
std::string graphName;
if (base.hasKey("graph") && (base.get("graph").isString())) {
@ -522,7 +522,7 @@ CostEstimate GraphNode::estimateCost() const {
void GraphNode::addEngine(TraverserEngineID const& engine, ServerID const& server) {
TRI_ASSERT(arangodb::ServerState::instance()->isCoordinator());
_engines.emplace(server, engine);
_engines.try_emplace(server, engine);
}
/// @brief Returns a reference to the engines. (CLUSTER ONLY)

View File

@ -305,16 +305,15 @@ decltype(HashedCollectExecutor::_allGroups)::iterator HashedCollectExecutor::fin
}
// note: aggregateValues may be a nullptr!
auto emplaceResult =
_allGroups.emplace(std::move(_nextGroupValues), std::move(aggregateValues));
auto [result, emplaced] = _allGroups.try_emplace(std::move(_nextGroupValues), std::move(aggregateValues));
// emplace must not fail
TRI_ASSERT(emplaceResult.second);
TRI_ASSERT(emplaced);
// Moving _nextGroupValues left us with an empty vector of minimum capacity.
// So in order to have correct capacity reserve again.
_nextGroupValues.reserve(_infos.getGroupRegisters().size());
return emplaceResult.first;
return result;
};
std::pair<ExecutionState, size_t> HashedCollectExecutor::expectedNumberOfRows(size_t atMost) const {

View File

@ -873,21 +873,21 @@ void IResearchViewNode::planNodeRegisters(
for (auto const& scorer : _scorers) {
++nrRegsHere[depth];
++nrRegs[depth];
varInfo.emplace(scorer.var->id, aql::VarInfo(depth, totalNrRegs++));
varInfo.try_emplace(scorer.var->id, aql::VarInfo(depth, totalNrRegs++));
}
// Plan register for document-id only block
if (isLateMaterialized()) {
++nrRegsHere[depth];
++nrRegs[depth];
varInfo.emplace(_outNonMaterializedColPtr->id, aql::VarInfo(depth, totalNrRegs++));
varInfo.try_emplace(_outNonMaterializedColPtr->id, aql::VarInfo(depth, totalNrRegs++));
++nrRegsHere[depth];
++nrRegs[depth];
varInfo.emplace(_outNonMaterializedDocId->id, aql::VarInfo(depth, totalNrRegs++));
varInfo.try_emplace(_outNonMaterializedDocId->id, aql::VarInfo(depth, totalNrRegs++));
} else {
++nrRegsHere[depth];
++nrRegs[depth];
varInfo.emplace(_outVariable->id, aql::VarInfo(depth, totalNrRegs++));
varInfo.try_emplace(_outVariable->id, aql::VarInfo(depth, totalNrRegs++));
}
}

View File

@ -173,7 +173,7 @@ bool optimizeSort(IResearchViewNode& viewNode, ExecutionPlan* plan) {
if (current->getType() == EN::CALCULATION) {
// pick up the meanings of variables as we walk the plan
variableDefinitions.emplace(
variableDefinitions.try_emplace(
ExecutionNode::castTo<CalculationNode const*>(current)->outVariable()->id,
ExecutionNode::castTo<CalculationNode const*>(current)->expression()->node());
}
@ -449,7 +449,7 @@ void scatterViewInClusterRule(arangodb::aql::Optimizer* opt,
plan->findNodesOfType(nodes, ExecutionNode::SUBQUERY, true);
for (auto& it : nodes) {
subqueries.emplace(EN::castTo<SubqueryNode const*>(it)->getSubquery(), it);
subqueries.try_emplace(EN::castTo<SubqueryNode const*>(it)->getSubquery(), it);
}
// we are a coordinator. now look in the plan for nodes of type

View File

@ -53,7 +53,7 @@ ExecutionBlockImpl<IdExecutor<BlockPassthrough::Enable, void>>::ExecutionBlockIm
_doCount(doCount) {
// already insert ourselves into the statistics results
if (_profile >= PROFILE_LEVEL_BLOCKS) {
_engine->_stats.nodes.emplace(node->id(), ExecutionStats::Node());
_engine->_stats.nodes.try_emplace(node->id(), ExecutionStats::Node());
}
}

View File

@ -203,7 +203,7 @@ void InputAqlItemRow::toVelocyPack(transaction::Methods* trx, VPackBuilder& resu
if (it == table.end()) {
currentState = Next;
a.toVelocyPack(trx, raw, false);
table.emplace(a, pos++);
table.try_emplace(a, pos++);
} else {
currentState = Positional;
tablePos = it->second;

View File

@ -1488,7 +1488,7 @@ class PropagateConstantAttributesHelper {
auto it = _constants.find(variable);
if (it == _constants.end()) {
_constants.emplace(variable,
_constants.try_emplace(variable,
std::unordered_map<std::string, AstNode const*>{{name, value}});
return;
}
@ -1497,7 +1497,7 @@ class PropagateConstantAttributesHelper {
if (it2 == (*it).second.end()) {
// first value for the attribute
(*it).second.emplace(name, value);
(*it).second.try_emplace(name, value);
} else {
auto previous = (*it2).second;
@ -2131,7 +2131,7 @@ class arangodb::aql::RedundantCalculationsReplacer final
Variable::replace(node->_expressionVariable, _replacements);
}
for (auto const& it : _replacements) {
node->_variableMap.emplace(it.second->id, it.second->name);
node->_variableMap.try_emplace(it.second->id, it.second->name);
}
// node->_keepVariables does not need to be updated at the moment as the
// "remove-redundant-calculations" rule will stop when it finds a
@ -2766,7 +2766,7 @@ void arangodb::aql::removeUnnecessaryCalculationsRule(Optimizer* opt,
if (!hasCollectWithOutVariable) {
// no COLLECT found, now replace
std::unordered_map<VariableId, Variable const*> replacements;
replacements.emplace(outVariable->id,
replacements.try_emplace(outVariable->id,
static_cast<Variable const*>(rootNode->getData()));
RedundantCalculationsReplacer finder(plan->getAst(), replacements);
@ -3274,7 +3274,7 @@ struct SortToIndexNode final : public WalkerWorker<ExecutionNode> {
}
case EN::CALCULATION: {
_variableDefinitions.emplace(
_variableDefinitions.try_emplace(
ExecutionNode::castTo<CalculationNode const*>(en)->outVariable()->id,
ExecutionNode::castTo<CalculationNode const*>(en)->expression()->node());
return false;
@ -4197,7 +4197,7 @@ void arangodb::aql::collectInClusterRule(Optimizer* opt, std::unique_ptr<Executi
auto copy = collectNode->groupVariables();
TRI_ASSERT(!copy.empty());
std::unordered_map<Variable const*, Variable const*> replacements;
replacements.emplace(copy[0].second, out);
replacements.try_emplace(copy[0].second, out);
copy[0].second = out;
collectNode->groupVariables(copy);
@ -4241,7 +4241,7 @@ void arangodb::aql::collectInClusterRule(Optimizer* opt, std::unique_ptr<Executi
for (auto const& it : groupVars) {
// create new out variables
auto out = plan->getAst()->variables()->createTemporaryVariable();
replacements.emplace(it.second, out);
replacements.try_emplace(it.second, out);
outVars.emplace_back(out, it.second);
}
@ -5624,7 +5624,7 @@ void arangodb::aql::removeDataModificationOutVariablesRule(Optimizer* opt,
if (setter != nullptr && (setter->getType() == EN::ENUMERATE_COLLECTION ||
setter->getType() == EN::INDEX)) {
std::unordered_map<VariableId, Variable const*> replacements;
replacements.emplace(old->id, inVariable);
replacements.try_emplace(old->id, inVariable);
RedundantCalculationsReplacer finder(plan->getAst(), replacements);
plan->root()->walk(finder);
modified = true;
@ -5640,7 +5640,7 @@ void arangodb::aql::removeDataModificationOutVariablesRule(Optimizer* opt,
if (setter != nullptr && (setter->getType() == EN::ENUMERATE_COLLECTION ||
setter->getType() == EN::INDEX)) {
std::unordered_map<VariableId, Variable const*> replacements;
replacements.emplace(old->id, inVariable);
replacements.try_emplace(old->id, inVariable);
RedundantCalculationsReplacer finder(plan->getAst(), replacements);
plan->root()->walk(finder);
modified = true;
@ -6152,7 +6152,7 @@ void arangodb::aql::inlineSubqueriesRule(Optimizer* opt, std::unique_ptr<Executi
// finally replace the variables
std::unordered_map<VariableId, Variable const*> replacements;
replacements.emplace(listNode->outVariable()->id, returnNode->inVariable());
replacements.try_emplace(listNode->outVariable()->id, returnNode->inVariable());
RedundantCalculationsReplacer finder(plan->getAst(), replacements);
plan->root()->walk(finder);
@ -6634,7 +6634,7 @@ static void optimizeFilterNode(ExecutionPlan* plan, FilterNode* fn, GeoIndexInfo
return;
}
if (checkGeoFilterExpression(plan, node, info)) {
info.exesToModify.emplace(fn, expr);
info.exesToModify.try_emplace(fn, expr);
}
});
}
@ -7052,7 +7052,7 @@ void arangodb::aql::optimizeSubqueriesRule(Optimizer* opt,
if (found.first != nullptr) {
auto it = subqueryAttributes.find(found.first);
if (it == subqueryAttributes.end()) {
subqueryAttributes.emplace(found.first,
subqueryAttributes.try_emplace(found.first,
std::make_tuple(found.second,
std::unordered_set<ExecutionNode const*>{n},
usedForCount));

View File

@ -182,15 +182,15 @@ void replaceNode(ExecutionPlan* plan, ExecutionNode* oldNode, ExecutionNode* new
bool substituteClusterSingleDocumentOperationsIndex(Optimizer* opt, ExecutionPlan* plan,
OptimizerRule const& rule) {
bool modified = false;
::arangodb::containers::SmallVector<ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<ExecutionNode*> nodes{a};
plan->findNodesOfType(nodes, EN::INDEX, false);
if (nodes.size() != 1) {
return modified;
return false;
}
bool modified = false;
for (auto* node : nodes) {
if (!::depIsSingletonOrConstCalc(node)) {
continue;
@ -278,15 +278,15 @@ bool substituteClusterSingleDocumentOperationsIndex(Optimizer* opt, ExecutionPla
bool substituteClusterSingleDocumentOperationsNoIndex(Optimizer* opt, ExecutionPlan* plan,
OptimizerRule const& rule) {
bool modified = false;
::arangodb::containers::SmallVector<ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<ExecutionNode*> nodes{a};
plan->findNodesOfType(nodes, {EN::INSERT, EN::REMOVE, EN::UPDATE, EN::REPLACE}, false);
if (nodes.size() != 1) {
return modified;
return false;
}
bool modified = false;
for (auto* node : nodes) {
auto mod = ExecutionNode::castTo<ModificationNode*>(node);

View File

@ -117,7 +117,7 @@ void OptimizerRulesFeature::registerRule(char const* name, RuleFunction func,
return;
}
_ruleLookup.emplace(ruleName, level);
_ruleLookup.try_emplace(ruleName, level);
_rules.push_back(std::move(rule));
}

View File

@ -227,7 +227,7 @@ Query::~Query() {
void Query::addDataSource( // track DataSource
std::shared_ptr<arangodb::LogicalDataSource> const& ds // DataSource to track
) {
_queryDataSources.emplace(ds->guid(), ds->name());
_queryDataSources.try_emplace(ds->guid(), ds->name());
}
/// @brief clone a query
@ -708,7 +708,7 @@ ExecutionState Query::execute(QueryRegistry* registry, QueryResult& queryResult)
_trx->state()->allCollections( // collect transaction DataSources
[&dataSources](TransactionCollection& trxCollection) -> bool {
auto const& c = trxCollection.collection();
dataSources.emplace(c->guid(), c->name());
dataSources.try_emplace(c->guid(), c->name());
return true; // continue traversal
});
@ -934,7 +934,7 @@ QueryResultV8 Query::executeV8(v8::Isolate* isolate, QueryRegistry* registry) {
_trx->state()->allCollections( // collect transaction DataSources
[&dataSources](TransactionCollection& trxCollection) -> bool {
auto const& c = trxCollection.collection();
dataSources.emplace(c->guid(), c->name());
dataSources.try_emplace(c->guid(), c->name());
return true; // continue traversal
});

View File

@ -25,6 +25,7 @@
#include "Basics/Exceptions.h"
#include "Basics/MutexLocker.h"
#include "Basics/ReadLocker.h"
#include "Basics/tryEmplaceHelper.h"
#include "Basics/VelocyPackHelper.h"
#include "Basics/WriteLocker.h"
#include "Basics/conversions.h"
@ -67,7 +68,7 @@ static bool showBindVars = true; // will be set once on startup. cannot be chan
QueryCacheResultEntry::QueryCacheResultEntry(uint64_t hash, QueryString const& queryString,
std::shared_ptr<VPackBuilder> const& queryResult,
std::shared_ptr<VPackBuilder> const& bindVars,
std::unordered_map<std::string, std::string>&& dataSources
std::unordered_map<std::string, std::string>&& dataSources
)
: _hash(hash),
_queryString(queryString.data(), queryString.size()),
@ -590,9 +591,10 @@ std::shared_ptr<QueryCacheResultEntry> QueryCache::lookup(
auto const part = getPart(vocbase);
READ_LOCKER(readLocker, _entriesLock[part]);
auto it = _entries[part].find(vocbase);
auto& entry = _entries[part];
auto it = entry.find(vocbase);
if (it == _entries[part].end()) {
if (it == entry.end()) {
// no entry found for the requested database
return nullptr;
}
@ -640,15 +642,12 @@ void QueryCache::store(TRI_vocbase_t* vocbase, std::shared_ptr<QueryCacheResultE
// get the right part of the cache to store the result in
auto const part = getPart(vocbase);
WRITE_LOCKER(writeLocker, _entriesLock[part]);
auto it = _entries[part].find(vocbase);
if (it == _entries[part].end()) {
// create entry for the current database
auto db = std::make_unique<QueryCacheDatabaseEntry>();
it = _entries[part].emplace(vocbase, std::move(db)).first;
}
auto [it, emplaced] = _entries[part].try_emplace(
vocbase,
arangodb::lazyConstruct([&]{
return std::make_unique<QueryCacheDatabaseEntry>();
})
);
// store cache entry
(*it).second->store(std::move(entry), allowedMaxResultsCount, allowedMaxResultsSize);
}
@ -658,9 +657,10 @@ void QueryCache::invalidate(TRI_vocbase_t* vocbase, std::vector<std::string> con
auto const part = getPart(vocbase);
WRITE_LOCKER(writeLocker, _entriesLock[part]);
auto it = _entries[part].find(vocbase);
auto& entry = _entries[part];
auto it = entry.find(vocbase);
if (it == _entries[part].end()) {
if (it == entry.end()) {
return;
}
@ -673,9 +673,10 @@ void QueryCache::invalidate(TRI_vocbase_t* vocbase, std::string const& dataSourc
auto const part = getPart(vocbase);
WRITE_LOCKER(writeLocker, _entriesLock[part]);
auto it = _entries[part].find(vocbase);
auto& entry = _entries[part];
auto it = entry.find(vocbase);
if (it == _entries[part].end()) {
if (it == entry.end()) {
return;
}
@ -691,14 +692,15 @@ void QueryCache::invalidate(TRI_vocbase_t* vocbase) {
auto const part = getPart(vocbase);
WRITE_LOCKER(writeLocker, _entriesLock[part]);
auto it = _entries[part].find(vocbase);
auto& entry = _entries[part];
auto it = entry.find(vocbase);
if (it == _entries[part].end()) {
if (it == entry.end()) {
return;
}
databaseQueryCache = std::move((*it).second);
_entries[part].erase(it);
entry.erase(it);
}
// delete without holding the lock
@ -728,9 +730,10 @@ void QueryCache::queriesToVelocyPack(TRI_vocbase_t* vocbase, VPackBuilder& build
auto const part = getPart(vocbase);
READ_LOCKER(readLocker, _entriesLock[part]);
auto it = _entries[part].find(vocbase);
auto& entry = _entries[part];
auto it = entry.find(vocbase);
if (it != _entries[part].end()) {
if (it != entry.end()) {
(*it).second->queriesToVelocyPack(builder);
}
}

View File

@ -93,7 +93,7 @@ void QueryRegistry::insert(QueryId id, Query* query, double ttl,
THROW_ARANGO_EXCEPTION(TRI_ERROR_SHUTTING_DOWN);
}
auto result = _queries[vocbase.name()].emplace(id, std::move(p));
auto result = _queries[vocbase.name()].try_emplace(id, std::move(p));
if (!result.second) {
THROW_ARANGO_EXCEPTION_MESSAGE(
TRI_ERROR_INTERNAL, "query with given vocbase and id already there");

View File

@ -182,7 +182,7 @@ void QuerySnippet::serializeIntoBuilder(ServerID const& server, ShardLocking& sh
// it needs to expose it's input register by all means
internalGather->setVarsUsedLater(_nodes.front()->getVarsUsedLater());
internalGather->setRegsToClear({});
nodeAliases.emplace(internalGather->id(), std::numeric_limits<size_t>::max());
nodeAliases.try_emplace(internalGather->id(), std::numeric_limits<size_t>::max());
ScatterNode* internalScatter = nullptr;
if (lastIsRemote) {
@ -194,7 +194,7 @@ void QuerySnippet::serializeIntoBuilder(ServerID const& server, ShardLocking& sh
internalScatter->addDependency(lastNode);
// Let the local Scatter node distribute data by SHARD
internalScatter->setScatterType(ScatterNode::ScatterType::SHARD);
nodeAliases.emplace(internalScatter->id(), std::numeric_limits<size_t>::max());
nodeAliases.try_emplace(internalScatter->id(), std::numeric_limits<size_t>::max());
if (_globalScatter->getType() == ExecutionNode::DISTRIBUTE) {
{
@ -232,7 +232,7 @@ void QuerySnippet::serializeIntoBuilder(ServerID const& server, ShardLocking& sh
DistributeConsumerNode* consumer =
createConsumerNode(plan, internalScatter, distIds[0]);
nodeAliases.emplace(consumer->id(), std::numeric_limits<size_t>::max());
nodeAliases.try_emplace(consumer->id(), std::numeric_limits<size_t>::max());
// now wire up the temporary nodes
TRI_ASSERT(_nodes.size() > 1);
ExecutionNode* secondToLast = _nodes[_nodes.size() - 2];
@ -258,7 +258,7 @@ void QuerySnippet::serializeIntoBuilder(ServerID const& server, ShardLocking& sh
DistributeConsumerNode* consumer =
createConsumerNode(plan, internalScatter, distIds[i]);
consumer->isResponsibleForInitializeCursor(false);
nodeAliases.emplace(consumer->id(), std::numeric_limits<size_t>::max());
nodeAliases.try_emplace(consumer->id(), std::numeric_limits<size_t>::max());
previous = consumer;
continue;
}
@ -274,7 +274,7 @@ void QuerySnippet::serializeIntoBuilder(ServerID const& server, ShardLocking& sh
clone->addDependency(previous);
}
TRI_ASSERT(clone->id() != current->id());
nodeAliases.emplace(clone->id(), current->id());
nodeAliases.try_emplace(clone->id(), current->id());
previous = clone;
}
TRI_ASSERT(previous != nullptr);

View File

@ -24,6 +24,7 @@
#include "RegexCache.h"
#include "Basics/Utf8Helper.h"
#include <Basics/StringUtils.h>
#include <Basics/tryEmplaceHelper.h>
#include <velocypack/Collection.h>
#include <velocypack/Dumper.h>
@ -94,20 +95,16 @@ icu::RegexMatcher* RegexCache::buildSplitMatcher(AqlValue const& splitExpression
icu::RegexMatcher* RegexCache::fromCache(
std::string const& pattern,
std::unordered_map<std::string, std::unique_ptr<icu::RegexMatcher>>& cache) {
auto it = cache.find(pattern);
if (it != cache.end()) {
return (*it).second.get();
}
auto matcher = arangodb::basics::Utf8Helper::DefaultUtf8Helper.buildMatcher(pattern);
auto p = matcher.get();
// insert into cache, no matter if pattern is valid or not
cache.emplace(pattern, std::move(matcher));
auto [matcherIter, res] = cache.try_emplace(
pattern,
arangodb::lazyConstruct([&]{
return std::unique_ptr<icu::RegexMatcher>(arangodb::basics::Utf8Helper::DefaultUtf8Helper.buildMatcher(pattern));
})
);
return p;
return matcherIter->second.get();
}
/// @brief compile a REGEX pattern from a string

View File

@ -109,7 +109,7 @@ void RegisterPlan::after(ExecutionNode* en) {
"unexpected cast result for DocumentProducingNode");
}
varInfo.emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
break;
}
@ -132,7 +132,7 @@ void RegisterPlan::after(ExecutionNode* en) {
auto ep = ExecutionNode::castTo<EnumerateListNode const*>(en);
TRI_ASSERT(ep != nullptr);
varInfo.emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
break;
}
@ -142,7 +142,7 @@ void RegisterPlan::after(ExecutionNode* en) {
nrRegs[depth]++;
auto ep = ExecutionNode::castTo<CalculationNode const*>(en);
TRI_ASSERT(ep != nullptr);
varInfo.emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
break;
}
@ -152,7 +152,7 @@ void RegisterPlan::after(ExecutionNode* en) {
nrRegs[depth]++;
auto ep = ExecutionNode::castTo<SubqueryNode const*>(en);
TRI_ASSERT(ep != nullptr);
varInfo.emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
subQueryNodes.emplace_back(en);
break;
@ -175,7 +175,7 @@ void RegisterPlan::after(ExecutionNode* en) {
// frame:
nrRegsHere[depth]++;
nrRegs[depth]++;
varInfo.emplace(p.first->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(p.first->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
}
for (auto const& p : ep->aggregateVariables()) {
@ -185,13 +185,13 @@ void RegisterPlan::after(ExecutionNode* en) {
// frame:
nrRegsHere[depth]++;
nrRegs[depth]++;
varInfo.emplace(p.first->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(p.first->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
}
if (ep->hasOutVariable()) {
nrRegsHere[depth]++;
nrRegs[depth]++;
varInfo.emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
}
break;
@ -218,13 +218,13 @@ void RegisterPlan::after(ExecutionNode* en) {
if (ep->getOutVariableOld() != nullptr) {
nrRegsHere[depth]++;
nrRegs[depth]++;
varInfo.emplace(ep->getOutVariableOld()->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(ep->getOutVariableOld()->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
}
if (ep->getOutVariableNew() != nullptr) {
nrRegsHere[depth]++;
nrRegs[depth]++;
varInfo.emplace(ep->getOutVariableNew()->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(ep->getOutVariableNew()->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
}
@ -274,7 +274,7 @@ void RegisterPlan::after(ExecutionNode* en) {
nrRegs.emplace_back(registerId);
for (auto& it : vars) {
varInfo.emplace(it->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(it->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
}
break;
@ -293,7 +293,7 @@ void RegisterPlan::after(ExecutionNode* en) {
nrRegs.emplace_back(registerId);
for (auto& it : vars) {
varInfo.emplace(it->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(it->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
}
break;
@ -316,7 +316,7 @@ void RegisterPlan::after(ExecutionNode* en) {
nrRegs[depth]++;
auto ep = ExecutionNode::castTo<SubqueryEndNode const*>(en);
TRI_ASSERT(ep != nullptr);
varInfo.emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(ep->outVariable()->id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
subQueryNodes.emplace_back(en);
break;
@ -331,7 +331,7 @@ void RegisterPlan::after(ExecutionNode* en) {
nrRegs.emplace_back(registerId);
auto ep = ExecutionNode::castTo<materialize::MaterializeNode const*>(en);
TRI_ASSERT(ep != nullptr);
varInfo.emplace(ep->outVariable().id, VarInfo(depth, totalNrRegs));
varInfo.try_emplace(ep->outVariable().id, VarInfo(depth, totalNrRegs));
totalNrRegs++;
break;
}

View File

@ -159,7 +159,7 @@ void ShardLocking::updateLocking(Collection const* col,
auto snippetPart = info.snippetInfo.find(snippetId);
if (snippetPart == info.snippetInfo.end()) {
std::tie(snippetPart, std::ignore) =
info.snippetInfo.emplace(snippetId, SnippetInformation{});
info.snippetInfo.try_emplace(snippetId, SnippetInformation{});
}
TRI_ASSERT(snippetPart != info.snippetInfo.end());
SnippetInformation& snip = snippetPart->second;

View File

@ -262,14 +262,14 @@ std::unique_ptr<ExecutionBlock> ShortestPathNode::createBlock(
if (usesVertexOutVariable()) {
auto it = varInfo.find(vertexOutVariable()->id);
TRI_ASSERT(it != varInfo.end());
outputRegisterMapping.emplace(ShortestPathExecutorInfos::OutputName::VERTEX,
outputRegisterMapping.try_emplace(ShortestPathExecutorInfos::OutputName::VERTEX,
it->second.registerId);
outputRegisters->emplace(it->second.registerId);
}
if (usesEdgeOutVariable()) {
auto it = varInfo.find(edgeOutVariable()->id);
TRI_ASSERT(it != varInfo.end());
outputRegisterMapping.emplace(ShortestPathExecutorInfos::OutputName::EDGE,
outputRegisterMapping.try_emplace(ShortestPathExecutorInfos::OutputName::EDGE,
it->second.registerId);
outputRegisters->emplace(it->second.registerId);
}

View File

@ -40,6 +40,7 @@
#include "Aql/TraversalExecutor.h"
#include "Aql/Variable.h"
#include "Basics/StringUtils.h"
#include "Basics/tryEmplaceHelper.h"
#include "Cluster/ClusterTraverser.h"
#ifdef USE_ENTERPRISE
#include "Enterprise/Cluster/SmartGraphTraverser.h"
@ -241,7 +242,7 @@ TraversalNode::TraversalNode(ExecutionPlan* plan, arangodb::velocypack::Slice co
if (list.isObject()) {
for (auto const& cond : VPackObjectIterator(list)) {
std::string key = cond.key.copyString();
_vertexConditions.emplace(StringUtils::uint64(key),
_vertexConditions.try_emplace(StringUtils::uint64(key),
new AstNode(plan->getAst(), cond.value));
}
}
@ -251,7 +252,7 @@ TraversalNode::TraversalNode(ExecutionPlan* plan, arangodb::velocypack::Slice co
for (auto const& cond : VPackObjectIterator(list)) {
std::string key = cond.key.copyString();
auto ecbuilder = std::make_unique<TraversalEdgeConditionBuilder>(this, cond.value);
_edgeConditions.emplace(StringUtils::uint64(key), std::move(ecbuilder));
_edgeConditions.try_emplace(StringUtils::uint64(key), std::move(ecbuilder));
}
}
@ -431,7 +432,7 @@ std::unique_ptr<ExecutionBlock> TraversalNode::createBlock(
TRI_ASSERT(it != varInfo.end());
TRI_ASSERT(it->second.registerId < RegisterPlan::MaxRegisterId);
outputRegisters->emplace(it->second.registerId);
outputRegisterMapping.emplace(TraversalExecutorInfos::OutputName::VERTEX,
outputRegisterMapping.try_emplace(TraversalExecutorInfos::OutputName::VERTEX,
it->second.registerId);
}
if (usesEdgeOutVariable()) {
@ -439,7 +440,7 @@ std::unique_ptr<ExecutionBlock> TraversalNode::createBlock(
TRI_ASSERT(it != varInfo.end());
TRI_ASSERT(it->second.registerId < RegisterPlan::MaxRegisterId);
outputRegisters->emplace(it->second.registerId);
outputRegisterMapping.emplace(TraversalExecutorInfos::OutputName::EDGE,
outputRegisterMapping.try_emplace(TraversalExecutorInfos::OutputName::EDGE,
it->second.registerId);
}
if (usesPathOutVariable()) {
@ -447,7 +448,7 @@ std::unique_ptr<ExecutionBlock> TraversalNode::createBlock(
TRI_ASSERT(it != varInfo.end());
TRI_ASSERT(it->second.registerId < RegisterPlan::MaxRegisterId);
outputRegisters->emplace(it->second.registerId);
outputRegisterMapping.emplace(TraversalExecutorInfos::OutputName::PATH,
outputRegisterMapping.try_emplace(TraversalExecutorInfos::OutputName::PATH,
it->second.registerId);
}
auto opts = static_cast<TraverserOptions*>(options());
@ -586,11 +587,11 @@ ExecutionNode* TraversalNode::clone(ExecutionPlan* plan, bool withDependencies,
// Copy the builder
auto ecBuilder =
std::make_unique<TraversalEdgeConditionBuilder>(this, it.second.get());
c->_edgeConditions.emplace(it.first, std::move(ecBuilder));
c->_edgeConditions.try_emplace(it.first, std::move(ecBuilder));
}
for (auto const& it : _vertexConditions) {
c->_vertexConditions.emplace(it.first, it.second->clone(_plan->getAst()));
c->_vertexConditions.try_emplace(it.first, it.second->clone(_plan->getAst()));
}
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
@ -673,7 +674,12 @@ void TraversalNode::prepareOptions() {
for (auto const& jt : _globalVertexConditions) {
it.second->addMember(jt);
}
opts->_vertexExpressions.emplace(it.first, new Expression(_plan, ast, it.second));
opts->_vertexExpressions.try_emplace(
it.first,
arangodb::lazyConstruct([&]{
return new Expression(_plan, ast, it.second);
})
);
}
if (!_globalVertexConditions.empty()) {
auto cond = _plan->getAst()->createNodeNaryOperator(NODE_TYPE_OPERATOR_NARY_AND);
@ -714,21 +720,27 @@ void TraversalNode::registerCondition(bool isConditionOnEdge, uint64_t condition
AstNode const* condition) {
Ast::getReferencedVariables(condition, _conditionVariables);
if (isConditionOnEdge) {
auto const& it = _edgeConditions.find(conditionLevel);
if (it == _edgeConditions.end()) {
auto builder = std::make_unique<TraversalEdgeConditionBuilder>(this);
builder->addConditionPart(condition);
_edgeConditions.emplace(conditionLevel, std::move(builder));
} else {
auto[it, emplaced] = _edgeConditions.try_emplace(
conditionLevel,
arangodb::lazyConstruct([&]()-> std::unique_ptr<TraversalEdgeConditionBuilder> {
auto builder = std::make_unique<TraversalEdgeConditionBuilder>(this);
builder->addConditionPart(condition);
return builder;
})
);
if (!emplaced) {
it->second->addConditionPart(condition);
}
} else {
auto const& it = _vertexConditions.find(conditionLevel);
if (it == _vertexConditions.end()) {
auto cond = _plan->getAst()->createNodeNaryOperator(NODE_TYPE_OPERATOR_NARY_AND);
cond->addMember(condition);
_vertexConditions.emplace(conditionLevel, cond);
} else {
auto [it, emplaced] = _vertexConditions.try_emplace(
conditionLevel,
arangodb::lazyConstruct([&]{
auto cond = _plan->getAst()->createNodeNaryOperator(NODE_TYPE_OPERATOR_NARY_AND);
cond->addMember(condition);
return cond;
})
);
if (!emplaced) {
it->second->addMember(condition);
}
}

View File

@ -53,7 +53,7 @@ std::unordered_map<VariableId, std::string const> VariableGenerator::variables(b
continue;
}
result.emplace(it.first, it.second->name);
result.try_emplace(it.first, it.second->name);
}
return result;
@ -69,7 +69,7 @@ Variable* VariableGenerator::createVariable(char const* name, size_t length, boo
TRI_ASSERT(variable->isUserDefined());
}
_variables.emplace(variable->id, variable.get());
_variables.try_emplace(variable->id, variable.get());
return variable.release();
}
@ -81,7 +81,7 @@ Variable* VariableGenerator::createVariable(std::string const& name, bool isUser
TRI_ASSERT(variable->isUserDefined());
}
_variables.emplace(variable->id, variable.get());
_variables.try_emplace(variable->id, variable.get());
return variable.release();
}
@ -90,7 +90,7 @@ Variable* VariableGenerator::createVariable(Variable const* original) {
std::unique_ptr<Variable> variable(original->clone());
// check if insertion into the table actually works.
auto inserted = _variables.emplace(variable->id, variable.get()).second;
auto inserted = _variables.try_emplace(variable->id, variable.get()).second;
if (!inserted) {
// variable was already present. this is unexpected...
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
@ -111,7 +111,7 @@ Variable* VariableGenerator::createVariable(VPackSlice const slice) {
return existing;
}
_variables.emplace(variable->id, variable.get());
_variables.try_emplace(variable->id, variable.get());
return variable.release();
}

View File

@ -163,13 +163,7 @@ auth::TokenCache::Entry auth::TokenCache::checkAuthenticationBasic(std::string c
{
WRITE_LOCKER(guard, _basicLock);
if (authorized) {
if (!_basicCache.emplace(secret, entry).second) {
// insertion did not work - probably another thread did insert the
// same data right now
// erase it and re-insert our version
_basicCache.erase(secret);
_basicCache.emplace(secret, entry);
}
_basicCache.insert_or_assign(std::move(secret), entry);
} else {
_basicCache.erase(secret);
}

View File

@ -31,6 +31,7 @@
#include "Basics/WriteLocker.h"
#include "Basics/system-functions.h"
#include "Basics/tri-strings.h"
#include "Basics/tryEmplaceHelper.h"
#include "Cluster/ServerState.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "Logger/LogMacros.h"
@ -429,7 +430,7 @@ void auth::User::grantDatabase(std::string const& dbname, auth::Level level) {
// grantDatabase is not supposed to change any rights on the
// collection level code which relies on the old behavior
// will need to be adjusted
_dbAccess.emplace(dbname, DBAuthContext(level, CollLevelMap()));
_dbAccess.try_emplace(dbname, DBAuthContext(level, CollLevelMap()));
}
}
@ -469,14 +470,17 @@ void auth::User::grantCollection(std::string const& dbname, std::string const& c
<< _username << ": Granting " << auth::convertFromAuthLevel(level)
<< " on " << dbname << "/" << cname;
auto it = _dbAccess.find(dbname);
if (it != _dbAccess.end()) {
it->second._collectionAccess[cname] = level;
} else {
auto[it, emplaced] = _dbAccess.try_emplace(
dbname,
arangodb::lazyConstruct([&]{
// do not overwrite wildcard access to a database, by granting more
// specific rights to a collection in a specific db
auth::Level lvl = auth::Level::UNDEFINED;
_dbAccess.emplace(dbname, DBAuthContext(lvl, CollLevelMap({{cname, level}})));
return DBAuthContext(lvl, CollLevelMap({{cname, level}}));
})
);
if (!emplaced) {
it->second._collectionAccess[cname] = level;
}
}

View File

@ -119,7 +119,7 @@ static auth::UserMap ParseUsers(VPackSlice const& slice) {
// otherwise all following update/replace/remove operations on the
// user will fail
auth::User user = auth::User::fromDocument(s);
result.emplace(user.username(), std::move(user));
result.try_emplace(user.username(), std::move(user));
}
return result;
}
@ -309,10 +309,10 @@ Result auth::UserManager::storeUserInternal(auth::User const& entry, bool replac
TRI_ASSERT(created.passwordHash() == entry.passwordHash());
TRI_ASSERT(!replace || created.key() == entry.key());
if (!_userCache.emplace(entry.username(), std::move(created)).second) {
if (!_userCache.try_emplace(entry.username(), std::move(created)).second) {
// insertion should always succeed, but...
_userCache.erase(entry.username());
_userCache.emplace(entry.username(), auth::User::fromDocument(userDoc));
_userCache.try_emplace(entry.username(), auth::User::fromDocument(userDoc));
}
#ifdef USE_ENTERPRISE
if (IsRole(entry.username())) {

View File

@ -150,7 +150,7 @@ std::shared_ptr<Cache> Manager::createCache(CacheType type, bool enableWindowedS
}
if (result.get() != nullptr) {
_caches.emplace(id, result);
_caches.try_emplace(id, result);
}
_lock.writeUnlock();

View File

@ -51,7 +51,7 @@ bool AgencyCallbackRegistry::registerCallback(std::shared_ptr<AgencyCallback> cb
WRITE_LOCKER(locker, _lock);
while (true) {
rand = RandomGenerator::interval(UINT32_MAX);
if (_endpoints.emplace(rand, cb).second) {
if (_endpoints.try_emplace(rand, cb).second) {
break;
}
}

View File

@ -29,6 +29,7 @@
#include "Basics/HybridLogicalClock.h"
#include "Basics/StringUtils.h"
#include "Basics/application-exit.h"
#include "Basics/tryEmplaceHelper.h"
#include "Cluster/ClusterFeature.h"
#include "Cluster/ClusterInfo.h"
#include "Cluster/ServerState.h"
@ -568,8 +569,12 @@ OperationID ClusterComm::asyncRequest(
auto ticketId = communicatorPtr->addRequest(std::move(newRequest));
result->operationID = ticketId;
responses.emplace(ticketId, AsyncResponse{TRI_microtime(), result,
std::move(communicatorPtr)});
responses.try_emplace(
ticketId,
arangodb::lazyConstruct([&] {
return AsyncResponse{TRI_microtime(), result, std::move(communicatorPtr)};
})
);
return ticketId;
}
@ -1116,7 +1121,7 @@ std::pair<ClusterCommResult*, HttpRequest*> ClusterComm::prepareRequest(
void ClusterComm::addAuthorization(std::unordered_map<std::string, std::string>* headers) {
if (_authenticationEnabled &&
headers->find(StaticStrings::Authorization) == headers->end()) {
headers->emplace(StaticStrings::Authorization, _jwtAuthorization);
headers->try_emplace(StaticStrings::Authorization, _jwtAuthorization);
}
}

View File

@ -465,7 +465,7 @@ class ClusterComm {
/// new instances or copy them, except we ourselves.
//////////////////////////////////////////////////////////////////////////////
ClusterComm(application_features::ApplicationServer&);
explicit ClusterComm(application_features::ApplicationServer&);
explicit ClusterComm(ClusterComm const&); // not implemented
void operator=(ClusterComm const&); // not implemented

View File

@ -652,7 +652,7 @@ void ClusterInfo::loadPlan() {
// On a coordinator we can only see databases that have been fully created
if (!(ServerState::instance()->isCoordinator() &&
database.value.hasKey(StaticStrings::DatabaseIsBuilding))) {
newDatabases.emplace(std::move(name), database.value);
newDatabases.try_emplace(std::move(name), database.value);
} else {
buildingDatabases.emplace(std::move(name));
}
@ -952,11 +952,11 @@ void ClusterInfo::loadPlan() {
if (!isBuilding) {
// register with name as well as with id:
databaseCollections.emplace(collectionName, newCollection);
databaseCollections.emplace(collectionId, newCollection);
databaseCollections.try_emplace(collectionName, newCollection);
databaseCollections.try_emplace(collectionId, newCollection);
}
newShardKeys.emplace(collectionId, std::make_shared<std::vector<std::string>>(
newShardKeys.try_emplace(collectionId, std::make_shared<std::vector<std::string>>(
newCollection->shardKeys()));
auto shardIDs = newCollection->shardIds();
@ -965,7 +965,7 @@ void ClusterInfo::loadPlan() {
for (auto const& p : *shardIDs) {
shards->push_back(p.first);
newShardServers.emplace(p.first, p.second);
newShardServers.try_emplace(p.first, p.second);
}
// Sort by the number in the shard ID ("s0000001" for example):
@ -977,7 +977,7 @@ void ClusterInfo::loadPlan() {
std::strtol(b.c_str() + 1, nullptr, 10);
} // comparator
);
newShards.emplace(collectionId, std::move(shards));
newShards.try_emplace(collectionId, std::move(shards));
} catch (std::exception const& ex) {
// The plan contains invalid collection information.
// This should not happen in healthy situations.
@ -1007,7 +1007,7 @@ void ClusterInfo::loadPlan() {
}
}
newCollections.emplace(std::move(databaseName), std::move(databaseCollections));
newCollections.try_emplace(std::move(databaseName), std::move(databaseCollections));
}
LOG_TOPIC("12dfa", DEBUG, Logger::CLUSTER)
<< "loadPlan done: wantedVersion=" << storedVersion
@ -1186,10 +1186,10 @@ void ClusterInfo::loadCurrent() {
for (auto const& serverSlicePair :
velocypack::ObjectIterator(databaseSlicePair.value)) {
serverList.emplace(serverSlicePair.key.copyString(), serverSlicePair.value);
serverList.try_emplace(serverSlicePair.key.copyString(), serverSlicePair.value);
}
newDatabases.emplace(database, serverList);
newDatabases.try_emplace(database, serverList);
}
}
@ -1226,13 +1226,13 @@ void ClusterInfo::loadCurrent() {
collectionDataCurrent->servers(shardID) // args
);
newShardIds.emplace(shardID, servers);
newShardIds.try_emplace(shardID, servers);
}
databaseCollections.emplace(collectionName, collectionDataCurrent);
databaseCollections.try_emplace(collectionName, collectionDataCurrent);
}
newCollections.emplace(databaseName, databaseCollections);
newCollections.try_emplace(databaseName, databaseCollections);
}
}
@ -1986,7 +1986,7 @@ Result ClusterInfo::createCollectionsCoordinator(
for (auto const& serv : VPackArrayIterator(pair.value)) {
serverIds.emplace_back(serv.copyString());
}
shardServers.emplace(shardID, serverIds);
shardServers.try_emplace(shardID, serverIds);
}
// The AgencyCallback will copy the closure will take responsibilty of it.
@ -3540,7 +3540,7 @@ void ClusterInfo::loadServers() {
if (serverSlice.isObject()) {
std::string alias = arangodb::basics::VelocyPackHelper::getStringValue(
serverSlice, "ShortName", "");
newAliases.emplace(std::make_pair(alias, serverId));
newAliases.try_emplace(std::move(alias), serverId);
}
} catch (...) {
}
@ -3548,10 +3548,10 @@ void ClusterInfo::loadServers() {
arangodb::basics::VelocyPackHelper::getStringValue(slice,
"timestamp",
"");
newServers.emplace(std::make_pair(serverId, server));
newAdvertisedEndpoints.emplace(std::make_pair(serverId, advertised));
newServers.try_emplace(serverId, server);
newAdvertisedEndpoints.try_emplace(serverId, advertised);
serverIds.emplace(serverId);
newTimestamps.emplace(std::make_pair(serverId, serverTimestamp));
newTimestamps.try_emplace(serverId, serverTimestamp);
}
}
@ -3755,8 +3755,7 @@ void ClusterInfo::loadCurrentCoordinators() {
decltype(_coordinators) newCoordinators;
for (auto const& coordinator : VPackObjectIterator(currentCoordinators)) {
newCoordinators.emplace(std::make_pair(coordinator.key.copyString(),
coordinator.value.copyString()));
newCoordinators.try_emplace(coordinator.key.copyString(), coordinator.value.copyString());
}
// Now set the new value:
@ -3811,7 +3810,7 @@ void ClusterInfo::loadCurrentMappings() {
static std::string const expectedPrefix{"Coordinator"};
if (shortName.size() > expectedPrefix.size() &&
shortName.substr(0, expectedPrefix.size()) == expectedPrefix) {
newCoordinatorIdMap.emplace(shortId, fullId);
newCoordinatorIdMap.try_emplace(shortId, fullId);
}
}
}
@ -3917,8 +3916,8 @@ void ClusterInfo::loadCurrentDBServers() {
}
}
newDBServers.emplace(std::make_pair(dbserver.key.copyString(),
dbserver.value.copyString()));
newDBServers.try_emplace(dbserver.key.copyString(),
dbserver.value.copyString());
}
// Now set the new value:
@ -4058,7 +4057,7 @@ std::unordered_map<ShardID, ServerID> ClusterInfo::getResponsibleServers(
}
// put leader into result
result.emplace(shardId, (*it).second->front());
result.try_emplace(shardId, (*it).second->front());
}
}
@ -4250,7 +4249,7 @@ std::unordered_map<ServerID, std::string> ClusterInfo::getServerAliases() {
READ_LOCKER(readLocker, _serversProt.lock);
std::unordered_map<std::string, std::string> ret;
for (const auto& i : _serverAliases) {
ret.emplace(i.second, i.first);
ret.try_emplace(i.second, i.first);
}
return ret;
}
@ -4259,7 +4258,7 @@ std::unordered_map<ServerID, std::string> ClusterInfo::getServerAdvertisedEndpoi
READ_LOCKER(readLocker, _serversProt.lock);
std::unordered_map<std::string, std::string> ret;
for (const auto& i : _serverAdvertisedEndpoints) {
ret.emplace(i.second, i.first);
ret.try_emplace(i.second, i.first);
}
return ret;
}
@ -4622,7 +4621,7 @@ ClusterInfo::ServersKnown::ServersKnown(VPackSlice const serversKnownSlice,
TRI_ASSERT(rebootIdSlice.isInteger());
if (rebootIdSlice.isInteger()) {
auto const rebootId = RebootId{rebootIdSlice.getNumericValue<uint64_t>()};
_serversKnown.emplace(std::move(serverId), rebootId);
_serversKnown.try_emplace(std::move(serverId), rebootId);
}
}
}
@ -4632,7 +4631,7 @@ ClusterInfo::ServersKnown::ServersKnown(VPackSlice const serversKnownSlice,
// ServersKnown but in ServersRegistered with a reboot ID of 0 as a fallback.
// We should be able to remove this in 3.6.
for (auto const& serverId : serverIds) {
auto const rv = _serversKnown.emplace(serverId, RebootId{0});
auto const rv = _serversKnown.try_emplace(serverId, RebootId{0});
LOG_TOPIC_IF("0acbd", INFO, Logger::CLUSTER, rv.second)
<< "Server " << serverId
<< " is in Current/ServersRegistered, but not in "
@ -4649,7 +4648,7 @@ ClusterInfo::ServersKnown::serversKnown() const noexcept {
std::unordered_map<ServerID, RebootId> ClusterInfo::ServersKnown::rebootIds() const {
std::unordered_map<ServerID, RebootId> rebootIds;
for (auto const& it : _serversKnown) {
rebootIds.emplace(it.first, it.second.rebootId());
rebootIds.try_emplace(it.first, it.second.rebootId());
}
return rebootIds;
}

View File

@ -355,7 +355,7 @@ void mergeResultsAllShards(std::vector<VPackSlice> const& results, VPackBuilder&
}
resultBody.close();
if (realNotFound > 0) {
errorCounter.emplace(TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND, realNotFound);
errorCounter.try_emplace(TRI_ERROR_ARANGO_DOCUMENT_NOT_FOUND, realNotFound);
}
}
@ -376,9 +376,9 @@ OperationResult handleCRUDShardResponsesFast(F&& func, CT const& opCtx,
int commError = network::fuerteToArangoErrorCode(res);
if (commError != TRI_ERROR_NO_ERROR) {
shardError.emplace(sId, commError);
shardError.try_emplace(sId, commError);
} else {
resultMap.emplace(sId, res.response->slice());
resultMap.try_emplace(sId, res.response->slice());
network::errorCodesFromHeaders(res.response->header.meta(), errorCounter, true);
code = res.response->statusCode();
}
@ -538,7 +538,7 @@ int distributeBabyOnShards(CrudOperationCtx& opCtx,
// We found the responsible shard. Add it to the list.
auto it = opCtx.shardMap.find(shardID);
if (it == opCtx.shardMap.end()) {
opCtx.shardMap.emplace(shardID, std::vector<VPackSlice>{value});
opCtx.shardMap.try_emplace(shardID, std::vector<VPackSlice>{value});
opCtx.reverseMapping.emplace_back(shardID, 0);
} else {
it->second.push_back(value);
@ -627,7 +627,7 @@ int distributeBabyOnShards(CreateOperationCtx& opCtx,
// We found the responsible shard. Add it to the list.
auto it = opCtx.shardMap.find(shardID);
if (it == opCtx.shardMap.end()) {
opCtx.shardMap.emplace(shardID, std::vector<std::pair<VPackSlice, std::string>>{{value, _key}});
opCtx.shardMap.try_emplace(shardID, std::vector<std::pair<VPackSlice, std::string>>{{value, _key}});
opCtx.reverseMapping.emplace_back(shardID, 0);
} else {
it->second.emplace_back(value, _key);
@ -705,7 +705,7 @@ static std::shared_ptr<std::unordered_map<std::string, std::vector<std::string>>
// determine shard id
std::string shardId = "s" + StringUtils::itoa(id + i);
shards->emplace(shardId, serverIds);
shards->try_emplace(shardId, serverIds);
}
return shards;
@ -768,7 +768,7 @@ static std::shared_ptr<std::unordered_map<std::string, std::vector<std::string>>
for (uint64_t i = 0; i < numberOfShards; ++i) {
// determine responsible server(s)
std::string shardId = "s" + StringUtils::itoa(id + i);
result->emplace(shardId, otherShardsMap->at(otherShards.at(i)));
result->try_emplace(std::move(shardId), otherShardsMap->at(otherShards.at(i)));
}
return result;
}
@ -821,7 +821,7 @@ network::Headers getForwardableRequestHeaders(arangodb::GeneralRequest* request)
key != "host" && key != "origin" && key != StaticStrings::HLCHeader &&
key != StaticStrings::ErrorCodes &&
key.substr(0, 14) != "access-control") {
result.emplace(key, (*it).second);
result.try_emplace(key, (*it).second);
}
++it;
}
@ -1196,7 +1196,7 @@ Result selectivityEstimatesOnCoordinator(ClusterFeature& feature, std::string co
for (auto const& p : *shards) {
network::Headers headers;
if (tid != 0) {
headers.emplace(StaticStrings::TransactionId, std::to_string(tid));
headers.try_emplace(StaticStrings::TransactionId, std::to_string(tid));
}
futures.emplace_back(
@ -1707,7 +1707,7 @@ Future<OperationResult> getDocumentOnCoordinator(transaction::Methods& trx,
TRI_ASSERT(it.second.size() == 1);
if (!options.ignoreRevs && slice.hasKey(StaticStrings::RevString)) {
headers.emplace("if-match", slice.get(StaticStrings::RevString).copyString());
headers.try_emplace("if-match", slice.get(StaticStrings::RevString).copyString());
}
VPackSlice keySlice = slice;
if (slice.isObject()) {
@ -1780,7 +1780,7 @@ Future<OperationResult> getDocumentOnCoordinator(transaction::Methods& trx,
network::Headers headers;
addTransactionHeaderForShard(trx, *shardIds, shard, headers);
if (addMatch) {
headers.emplace("if-match", slice.get(StaticStrings::RevString).copyString());
headers.try_emplace("if-match", slice.get(StaticStrings::RevString).copyString());
}
futures.emplace_back(network::sendRequestRetry(
@ -2073,14 +2073,14 @@ void fetchVerticesFromEngines(
cached = true;
}
// Protected by datalake
result.emplace(key, pair.value);
result.try_emplace(key, pair.value);
}
}
if (!forShortestPath) {
// Fill everything we did not find with NULL
for (auto const& v : vertexIds) {
result.emplace(v, VPackSlice::nullSlice());
result.try_emplace(v, VPackSlice::nullSlice());
}
vertexIds.clear();
}
@ -2745,7 +2745,7 @@ arangodb::Result matchBackupServersSlice(VPackSlice const planServers,
localCopy.end()) {
localCopy.erase(it);
} else {
match.emplace(plannedStr, std::string());
match.try_emplace(plannedStr, std::string());
}
}
// match all remaining

View File

@ -44,11 +44,10 @@ std::map<ShardID, DBServers, VersionSort> DistributeShardsLikeRepairer::readShar
for (auto const& dbServerIterator : ArrayIterator(shardIterator.value)) {
ServerID const dbServerId = dbServerIterator.copyString();
dbServers.emplace_back(dbServerId);
dbServers.emplace_back(std::move(dbServerId));
}
shardsById.emplace(std::make_pair(shardId, std::move(dbServers)));
shardsById.try_emplace(std::move(shardId), std::move(dbServers));
}
return shardsById;
@ -86,8 +85,8 @@ DistributeShardsLikeRepairer::readCollections(const Slice& collectionsByDatabase
uint64_t replicationFactor = 0;
bool deleted = false;
bool isSmart = false;
boost::optional<CollectionID> distributeShardsLike;
boost::optional<CollectionID> repairingDistributeShardsLike;
std::optional<CollectionID> distributeShardsLike;
std::optional<CollectionID> repairingDistributeShardsLike;
Slice shardsSlice;
std::map<std::string, Slice> residualAttributes;
@ -126,7 +125,7 @@ DistributeShardsLikeRepairer::readCollections(const Slice& collectionsByDatabase
_shardsById = shardsById
};
collections.emplace(std::make_pair(collectionId, std::move(collection)));
collections.try_emplace(std::move(collectionId), std::move(collection));
}
}
@ -171,7 +170,7 @@ std::vector<std::pair<CollectionID, Result>> DistributeShardsLikeRepairer::findC
continue;
}
struct Collection& proto = collections.at(collection.distributeShardsLike.get());
struct Collection& proto = collections.at(collection.distributeShardsLike.value());
LOG_TOPIC("994ab", TRACE, arangodb::Logger::CLUSTER)
<< "findCollectionsToFix: comparing against distributeShardsLike "
@ -220,7 +219,7 @@ std::vector<std::pair<CollectionID, Result>> DistributeShardsLikeRepairer::findC
return collectionsToFix;
}
boost::optional<ServerID const> DistributeShardsLikeRepairer::findFreeServer(
std::optional<ServerID const> DistributeShardsLikeRepairer::findFreeServer(
DBServers const& availableDbServers, DBServers const& shardDbServers) {
DBServers freeServer = serverSetDifference(availableDbServers, shardDbServers);
@ -228,7 +227,7 @@ boost::optional<ServerID const> DistributeShardsLikeRepairer::findFreeServer(
return freeServer[0];
}
return boost::none;
return std::nullopt;
}
DBServers DistributeShardsLikeRepairer::serverSetDifference(DBServers setA, DBServers setB) {
@ -327,7 +326,7 @@ ResultT<std::list<RepairOperation>> DistributeShardsLikeRepairer::fixLeader(
if (std::find(shardDbServers.begin(), shardDbServers.end(), protoLeader) !=
shardDbServers.end()) {
boost::optional<ServerID const> tmpServer =
std::optional<ServerID const> tmpServer =
findFreeServer(availableDbServers, shardDbServers);
if (!tmpServer) {
@ -337,7 +336,7 @@ ResultT<std::list<RepairOperation>> DistributeShardsLikeRepairer::fixLeader(
}
RepairOperation moveShardOperation =
createMoveShardOperation(collection, shardId, protoLeader, tmpServer.get(), false);
createMoveShardOperation(collection, shardId, protoLeader, tmpServer.value(), false);
repairOperations.emplace_back(moveShardOperation);
}
@ -411,7 +410,7 @@ ResultT<std::list<RepairOperation>> DistributeShardsLikeRepairer::fixShard(
repairOperations.emplace_back(moveShardOperation);
}
ResultT<boost::optional<FixServerOrderOperation>> maybeFixServerOrderOperationResult =
ResultT<std::optional<FixServerOrderOperation>> maybeFixServerOrderOperationResult =
createFixServerOrderOperation(collection, proto, shardId, protoShardId);
if (maybeFixServerOrderOperationResult.fail()) {
@ -421,7 +420,7 @@ ResultT<std::list<RepairOperation>> DistributeShardsLikeRepairer::fixShard(
if (auto const& maybeFixServerOrderOperation =
maybeFixServerOrderOperationResult.get()) {
FixServerOrderOperation const& fixServerOrderOperation =
maybeFixServerOrderOperation.get();
maybeFixServerOrderOperation.value();
repairOperations.emplace_back(fixServerOrderOperation);
}
@ -453,7 +452,7 @@ ResultT<std::map<CollectionID, ResultT<std::list<RepairOperation>>>> DistributeS
CollectionID const& collectionId = collectionIterator.first;
Result const& result = collectionIterator.second;
if (result.fail()) {
repairOperationsByCollection.emplace(collectionId, result);
repairOperationsByCollection.try_emplace(collectionId, result);
continue;
}
struct Collection& collection = collectionMap.at(collectionId);
@ -475,15 +474,15 @@ ResultT<std::map<CollectionID, ResultT<std::list<RepairOperation>>>> DistributeS
}
}
if (collection.distributeShardsLike && !failOnPurpose) {
protoId = collection.distributeShardsLike.get();
protoId = collection.distributeShardsLike.value();
} else if (collection.repairingDistributeShardsLike && !failOnPurpose) {
protoId = collection.repairingDistributeShardsLike.get();
protoId = collection.repairingDistributeShardsLike.value();
} else {
// This should never happen
LOG_TOPIC("2b82f", ERR, arangodb::Logger::CLUSTER)
<< "DistributeShardsLikeRepairer::repairDistributeShardsLike: "
<< "(repairing)distributeShardsLike missing in " << collection.fullName();
repairOperationsByCollection.emplace(collection.id,
repairOperationsByCollection.try_emplace(collection.id,
Result{TRI_ERROR_CLUSTER_REPAIRS_INCONSISTENT_ATTRIBUTES});
continue;
}
@ -492,7 +491,7 @@ ResultT<std::map<CollectionID, ResultT<std::list<RepairOperation>>>> DistributeS
auto beginRepairsOperation = createBeginRepairsOperation(collection, proto);
if (beginRepairsOperation.fail()) {
repairOperationsByCollection.emplace(collection.id,
repairOperationsByCollection.try_emplace(collection.id,
std::move(beginRepairsOperation).result());
continue;
}
@ -503,7 +502,7 @@ ResultT<std::map<CollectionID, ResultT<std::list<RepairOperation>>>> DistributeS
fixAllShardsOfCollection(collection, proto, availableDbServers);
if (shardRepairOperationsResult.fail()) {
repairOperationsByCollection.emplace(
repairOperationsByCollection.try_emplace(
collection.id, std::move(shardRepairOperationsResult).result());
continue;
}
@ -512,19 +511,19 @@ ResultT<std::map<CollectionID, ResultT<std::list<RepairOperation>>>> DistributeS
auto finishRepairsOperation = createFinishRepairsOperation(collection, proto);
if (finishRepairsOperation.fail()) {
repairOperationsByCollection.emplace(collection.id,
repairOperationsByCollection.try_emplace(collection.id,
std::move(finishRepairsOperation).result());
continue;
}
repairOperations.emplace_back(std::move(finishRepairsOperation.get()));
repairOperationsByCollection.emplace(collection.id, std::move(repairOperations));
repairOperationsByCollection.try_emplace(collection.id, std::move(repairOperations));
}
return repairOperationsByCollection;
}
ResultT<boost::optional<FixServerOrderOperation>> DistributeShardsLikeRepairer::createFixServerOrderOperation(
ResultT<std::optional<FixServerOrderOperation>> DistributeShardsLikeRepairer::createFixServerOrderOperation(
struct cluster_repairs::Collection& collection,
struct cluster_repairs::Collection const& proto, ShardID const& shardId,
ShardID const& protoShardId) {
@ -593,7 +592,7 @@ ResultT<boost::optional<FixServerOrderOperation>> DistributeShardsLikeRepairer::
<< "DistributeShardsLikeRepairer::createFixServerOrderOperation: "
<< "Order is already equal, doing nothing";
return {boost::none};
return {std::nullopt};
}
FixServerOrderOperation fixServerOrderOperation{
@ -617,9 +616,9 @@ ResultT<boost::optional<FixServerOrderOperation>> DistributeShardsLikeRepairer::
ResultT<BeginRepairsOperation> DistributeShardsLikeRepairer::createBeginRepairsOperation(
struct cluster_repairs::Collection& collection,
struct cluster_repairs::Collection const& proto) {
bool distributeShardsLikeExists = collection.distributeShardsLike.is_initialized();
bool distributeShardsLikeExists = collection.distributeShardsLike.has_value();
bool repairingDistributeShardsLikeExists =
collection.repairingDistributeShardsLike.is_initialized();
collection.repairingDistributeShardsLike.has_value();
bool exactlyOneDslAttrIsSet = distributeShardsLikeExists != repairingDistributeShardsLikeExists;
TRI_ASSERT(exactlyOneDslAttrIsSet);
@ -805,8 +804,8 @@ cluster_repairs::Collection::Collection(
tagged_argument<tag::collectionName, std::string> collectionName_,
tagged_argument<tag::replicationFactor, uint64_t> replicationFactor_,
tagged_argument<tag::deleted, bool> deleted_, tagged_argument<tag::isSmart, bool> isSmart_,
tagged_argument<tag::distributeShardsLike, boost::optional<CollectionID>> distributeShardsLike_,
tagged_argument<tag::repairingDistributeShardsLike, boost::optional<CollectionID>> repairingDistributeShardsLike_,
tagged_argument<tag::distributeShardsLike, std::optional<CollectionID>> distributeShardsLike_,
tagged_argument<tag::repairingDistributeShardsLike, std::optional<CollectionID>> repairingDistributeShardsLike_,
tagged_argument<tag::shardsById, std::map<ShardID, DBServers, VersionSort>> shardsById_)
: database(database_.value),
name(collectionName_.value),

View File

@ -26,8 +26,8 @@
#include <velocypack/Compare.h>
#include <velocypack/Slice.h>
#include <velocypack/velocypack-common.h>
#include <boost/optional.hpp>
#include <boost/variant.hpp>
#include <optional>
#include <variant>
#include "Agency/AgencyComm.h"
#include "ClusterInfo.h"
@ -70,8 +70,8 @@ struct Collection {
uint64_t replicationFactor;
bool deleted;
bool isSmart;
boost::optional<CollectionID> distributeShardsLike;
boost::optional<CollectionID> repairingDistributeShardsLike;
std::optional<CollectionID> distributeShardsLike;
std::optional<CollectionID> repairingDistributeShardsLike;
std::map<ShardID, DBServers, VersionSort> shardsById;
std::string inline fullName() const {
@ -87,8 +87,8 @@ struct Collection {
tagged_argument<tag::replicationFactor, uint64_t> replicationFactor_,
tagged_argument<tag::deleted, bool> deleted_,
tagged_argument<tag::isSmart, bool> isSmart_,
tagged_argument<tag::distributeShardsLike, boost::optional<CollectionID>> distributeShardsLike_,
tagged_argument<tag::repairingDistributeShardsLike, boost::optional<CollectionID>> repairingDistributeShardsLike_,
tagged_argument<tag::distributeShardsLike, std::optional<CollectionID>> distributeShardsLike_,
tagged_argument<tag::repairingDistributeShardsLike, std::optional<CollectionID>> repairingDistributeShardsLike_,
tagged_argument<tag::shardsById, std::map<ShardID, DBServers, VersionSort>> shardsById_);
};
@ -105,7 +105,7 @@ class DistributeShardsLikeRepairer {
ResultT<std::map<CollectionID, struct Collection>> static readCollections(
velocypack::Slice const& collectionsByDatabase);
boost::optional<ServerID const> static findFreeServer(DBServers const& availableDbServers,
std::optional<ServerID const> static findFreeServer(DBServers const& availableDbServers,
DBServers const& shardDbServers);
std::vector<std::pair<CollectionID, Result>> static findCollectionsToFix(
@ -136,7 +136,7 @@ class DistributeShardsLikeRepairer {
ShardID const& shardId,
ShardID const& protoShardId);
ResultT<boost::optional<FixServerOrderOperation>> static createFixServerOrderOperation(
ResultT<std::optional<FixServerOrderOperation>> static createFixServerOrderOperation(
struct Collection& collection, struct Collection const& proto,
ShardID const& shardId, ShardID const& protoShardId);

View File

@ -36,8 +36,8 @@ bool VersionSort::operator()(std::string const& a, std::string const& b) const {
auto compareResult =
std::lexicographical_compare(va.begin(), va.end(), vb.begin(), vb.end(),
[](CharOrInt const& a, CharOrInt const& b) -> bool {
if (a.which() != b.which()) {
return a.which() < b.which();
if (a.index() != b.index()) {
return a.index() < b.index();
}
return a < b;
});
@ -246,7 +246,7 @@ std::ostream& cluster_repairs::operator<<(std::ostream& ostream,
return ostream;
}
class StreamRepairOperationVisitor : public boost::static_visitor<std::ostream&> {
class StreamRepairOperationVisitor {
public:
StreamRepairOperationVisitor() = delete;
@ -273,7 +273,7 @@ class StreamRepairOperationVisitor : public boost::static_visitor<std::ostream&>
std::ostream& cluster_repairs::operator<<(std::ostream& ostream,
RepairOperation const& operation) {
auto visitor = StreamRepairOperationVisitor(ostream);
return boost::apply_visitor(visitor, operation);
return std::visit(visitor, operation);
}
std::string getExtendedIsoString(std::chrono::system_clock::time_point time_point) {
@ -293,7 +293,7 @@ std::string getExtendedIsoString(std::chrono::system_clock::time_point time_poin
return std::string(timeString);
}
class RepairOperationTypeStringVisitor : public boost::static_visitor<std::string> {
class RepairOperationTypeStringVisitor {
public:
std::string operator()(BeginRepairsOperation const& op) const {
return "BeginRepairsOperation";
@ -310,7 +310,7 @@ class RepairOperationTypeStringVisitor : public boost::static_visitor<std::strin
};
std::string cluster_repairs::getTypeAsString(RepairOperation const& op) {
return boost::apply_visitor(RepairOperationTypeStringVisitor(), op);
return std::visit(RepairOperationTypeStringVisitor(), op);
}
VPackBufferPtr MoveShardOperation::toVPackTodo(
@ -421,7 +421,7 @@ RepairOperationToTransactionVisitor::ReturnValueT RepairOperationToTransactionVi
operations.emplace_back(
AgencyOperation("Plan/Version", AgencySimpleOperationType::INCREMENT_OP));
return {AgencyWriteTransaction{operations, preconditions}, boost::none};
return {AgencyWriteTransaction{operations, preconditions}, std::nullopt};
}
RepairOperationToTransactionVisitor::ReturnValueT RepairOperationToTransactionVisitor::operator()(
@ -482,7 +482,7 @@ RepairOperationToTransactionVisitor::ReturnValueT RepairOperationToTransactionVi
operations.emplace_back(
AgencyOperation("Plan/Version", AgencySimpleOperationType::INCREMENT_OP));
return {AgencyWriteTransaction{operations, preconditions}, boost::none};
return {AgencyWriteTransaction{operations, preconditions}, std::nullopt};
}
RepairOperationToTransactionVisitor::ReturnValueT RepairOperationToTransactionVisitor::operator()(
@ -525,7 +525,7 @@ RepairOperationToTransactionVisitor::ReturnValueT RepairOperationToTransactionVi
AgencyOperation agencyOperation{agencyShardId, AgencyValueOperationType::SET,
protoDbServerSlice};
return {AgencyWriteTransaction{agencyOperation, agencyPreconditions}, boost::none};
return {AgencyWriteTransaction{agencyOperation, agencyPreconditions}, std::nullopt};
}
std::string RepairOperationToTransactionVisitor::agencyCollectionId(DatabaseID database,

View File

@ -23,11 +23,10 @@
#ifndef ARANGOD_CLUSTER_CLUSTER_REPAIR_OPERATIONS_H
#define ARANGOD_CLUSTER_CLUSTER_REPAIR_OPERATIONS_H
#include <boost/optional.hpp>
#include <boost/variant.hpp>
#include <velocypack/velocypack-common.h>
#include <map>
#include <optional>
#include <variant>
#include "ClusterInfo.h"
namespace arangodb {
@ -65,7 +64,7 @@ class VersionSort {
}
};
using CharOrInt = boost::variant<char, WrappedUInt64>;
using CharOrInt = std::variant<char, WrappedUInt64>;
std::vector<CharOrInt> static splitVersion(std::string const& str);
};
@ -153,9 +152,9 @@ keyword<tag::leader, std::string> _leader = decltype(_leader)::instance;
keyword<tag::followers, std::vector<std::string>> _followers = decltype(_followers)::instance;
keyword<tag::protoFollowers, std::vector<std::string>> _protoFollowers =
decltype(_protoFollowers)::instance;
keyword<tag::distributeShardsLike, boost::optional<CollectionID>> _distributeShardsLike =
keyword<tag::distributeShardsLike, std::optional<CollectionID>> _distributeShardsLike =
decltype(_distributeShardsLike)::instance;
keyword<tag::repairingDistributeShardsLike, boost::optional<CollectionID>> _repairingDistributeShardsLike =
keyword<tag::repairingDistributeShardsLike, std::optional<CollectionID>> _repairingDistributeShardsLike =
decltype(_repairingDistributeShardsLike)::instance;
keyword<tag::shardsById, std::map<ShardID, DBServers, VersionSort>> _shardsById =
decltype(_shardsById)::instance;
@ -319,7 +318,7 @@ std::ostream& operator<<(std::ostream& ostream, MoveShardOperation const& operat
std::ostream& operator<<(std::ostream& ostream, FixServerOrderOperation const& operation);
using RepairOperation =
boost::variant<BeginRepairsOperation const, FinishRepairsOperation const, MoveShardOperation const, FixServerOrderOperation const>;
std::variant<BeginRepairsOperation const, FinishRepairsOperation const, MoveShardOperation const, FixServerOrderOperation const>;
std::string getTypeAsString(RepairOperation const& op);
@ -327,9 +326,8 @@ std::ostream& operator<<(std::ostream& ostream, RepairOperation const& operation
// Converts any RepairOperation to a Transaction. If its a job (i.e. put in
// Target/ToDo/), it returns the corresponding job id as well.
class RepairOperationToTransactionVisitor
: public boost::static_visitor<std::pair<AgencyWriteTransaction, boost::optional<uint64_t>>> {
using ReturnValueT = std::pair<AgencyWriteTransaction, boost::optional<uint64_t>>;
class RepairOperationToTransactionVisitor {
using ReturnValueT = std::pair<AgencyWriteTransaction, std::optional<uint64_t>>;
public:
RepairOperationToTransactionVisitor(ClusterInfo&);
@ -364,7 +362,7 @@ class RepairOperationToTransactionVisitor
// Doesn't contain all data, some members are named differently.
// TODO Maybe it would still be good to add all members, at least for the
// functional tests?
class RepairOperationToVPackVisitor : public boost::static_visitor<void> {
class RepairOperationToVPackVisitor {
public:
RepairOperationToVPackVisitor() = delete;
explicit RepairOperationToVPackVisitor(VPackBuilder& builder);

View File

@ -142,7 +142,7 @@ Future<network::Response> beginTransactionRequest(TransactionState& state,
auto* pool = state.vocbase().server().getFeature<NetworkFeature>().pool();
network::Headers headers;
headers.emplace(StaticStrings::TransactionId, std::to_string(tid));
headers.try_emplace(StaticStrings::TransactionId, std::to_string(tid));
auto body = std::make_shared<std::string>(builder.slice().toJson());
return network::sendRequest(pool, "server:" + server, fuerte::RestVerb::Post,
"/_api/transaction/begin", std::move(buffer), reqOpts, std::move(headers));
@ -358,12 +358,12 @@ void addTransactionHeader(transaction::Methods const& trx,
transaction::isLeaderTransactionId(state.id()));
transaction::BuilderLeaser builder(trx.transactionContextPtr());
::buildTransactionBody(state, server, *builder.get());
headers.emplace(StaticStrings::TransactionBody, builder->toJson());
headers.emplace(arangodb::StaticStrings::TransactionId,
headers.try_emplace(StaticStrings::TransactionBody, builder->toJson());
headers.try_emplace(arangodb::StaticStrings::TransactionId,
std::to_string(tidPlus).append(" begin"));
state.addKnownServer(server); // remember server
} else {
headers.emplace(arangodb::StaticStrings::TransactionId, std::to_string(tidPlus));
headers.try_emplace(arangodb::StaticStrings::TransactionId, std::to_string(tidPlus));
}
}
template void addTransactionHeader<std::map<std::string, std::string>>(
@ -390,7 +390,7 @@ void addAQLTransactionHeader(transaction::Methods const& trx,
} else if (state.hasHint(transaction::Hints::Hint::GLOBAL_MANAGED)) {
transaction::BuilderLeaser builder(trx.transactionContextPtr());
::buildTransactionBody(state, server, *builder.get());
headers.emplace(StaticStrings::TransactionBody, builder->toJson());
headers.try_emplace(StaticStrings::TransactionBody, builder->toJson());
value.append(" begin"); // part of a managed transaction
} else {
TRI_ASSERT(false);
@ -399,7 +399,7 @@ void addAQLTransactionHeader(transaction::Methods const& trx,
} else if (state.hasHint(transaction::Hints::Hint::FROM_TOPLEVEL_AQL)) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "illegal AQL transaction state");
}
headers.emplace(arangodb::StaticStrings::TransactionId, std::move(value));
headers.try_emplace(arangodb::StaticStrings::TransactionId, std::move(value));
}
template void addAQLTransactionHeader<std::map<std::string, std::string>>(
transaction::Methods const&, ServerID const&, std::map<std::string, std::string>&);

View File

@ -1143,7 +1143,7 @@ bool HeartbeatThread::handlePlanChangeCoordinator(uint64_t currentPlanVersion) {
info.allowSystemDB(TRI_vocbase_t::IsSystemName(options.value.get("name").copyString()));
auto infoResult = info.load(options.value, VPackSlice::emptyArraySlice());
if(infoResult.fail()) {
if (infoResult.fail()) {
LOG_TOPIC("3fa12", ERR, Logger::HEARTBEAT) << "In agency database plan" << infoResult.errorMessage();
TRI_ASSERT(false);
}

View File

@ -474,7 +474,7 @@ arangodb::Result arangodb::maintenance::diffPlanLocal(
break;
}
}
} // else if(!shard.value.isArray()) - intentionally do nothing
} // else if (!shard.value.isArray()) - intentionally do nothing
}
}
}

View File

@ -610,7 +610,7 @@ arangodb::Result MaintenanceFeature::storeDBError(std::string const& database,
}
try {
_dbErrors.emplace(database, error);
_dbErrors.try_emplace(database, error);
} catch (std::exception const& e) {
return Result(TRI_ERROR_FAILED, e.what());
}
@ -666,19 +666,17 @@ arangodb::Result MaintenanceFeature::storeShardError(std::string const& database
arangodb::Result MaintenanceFeature::storeShardError(
std::string const& database, std::string const& collection,
std::string const& shard, std::shared_ptr<VPackBuffer<uint8_t>> error) {
std::string key = database + SLASH + collection + SLASH + shard;
std::string const key = database + SLASH + collection + SLASH + shard;
MUTEX_LOCKER(guard, _seLock);
auto const it = _shardErrors.find(key);
if (it != _shardErrors.end()) {
std::stringstream error;
error << "shard " << key << " already has pending error";
LOG_TOPIC("378fa", DEBUG, Logger::MAINTENANCE) << error.str();
return Result(TRI_ERROR_FAILED, error.str());
}
try {
_shardErrors.emplace(key, error);
auto [it, emplaced] = _shardErrors.try_emplace(std::move(key), std::move(error));
if (!emplaced) {
std::stringstream error;
error << "shard " << key << " already has pending error";
LOG_TOPIC("378fa", DEBUG, Logger::MAINTENANCE) << error.str();
return Result(TRI_ERROR_FAILED, error.str());
}
} catch (std::exception const& e) {
return Result(TRI_ERROR_FAILED, e.what());
}
@ -721,30 +719,26 @@ arangodb::Result MaintenanceFeature::storeIndexError(
std::string const& database, std::string const& collection, std::string const& shard,
std::string const& indexId, std::shared_ptr<VPackBuffer<uint8_t>> error) {
using buffer_t = std::shared_ptr<VPackBuffer<uint8_t>>;
std::string key = database + SLASH + collection + SLASH + shard;
std::string const key = database + SLASH + collection + SLASH + shard;
MUTEX_LOCKER(guard, _ieLock);
auto errorsIt = _indexErrors.find(key);
if (errorsIt == _indexErrors.end()) {
try {
_indexErrors.emplace(key, std::map<std::string, buffer_t>());
} catch (std::exception const& e) {
return Result(TRI_ERROR_FAILED, e.what());
}
}
auto& errors = _indexErrors.find(key)->second;
auto const it = errors.find(indexId);
if (it != errors.end()) {
std::stringstream error;
error << "index " << indexId << " for shard " << key << " already has pending error";
LOG_TOPIC("d3c92", DEBUG, Logger::MAINTENANCE) << error.str();
return Result(TRI_ERROR_FAILED, error.str());
}
decltype (_indexErrors.emplace(key)) emplace_result;
try {
errors.emplace(indexId, error);
emplace_result = _indexErrors.try_emplace(key, std::map<std::string, buffer_t>());
} catch (std::exception const& e) {
return Result(TRI_ERROR_FAILED, e.what());
}
auto& errors = emplace_result.first->second;
try {
auto [itr, emplaced] = errors.try_emplace(indexId, error);
if (!emplaced) {
std::stringstream error;
error << "index " << indexId << " for shard " << key << " already has pending error";
LOG_TOPIC("d3c92", DEBUG, Logger::MAINTENANCE) << error.str();
return Result(TRI_ERROR_FAILED, error.str());
}
} catch (std::exception const& e) {
return Result(TRI_ERROR_FAILED, e.what());
}

View File

@ -98,7 +98,7 @@ void RebootTracker::updateServerState(std::unordered_map<ServerID, RebootId> con
for (auto const& newIt : state) {
auto const& serverId = newIt.first;
auto const& rebootId = newIt.second;
auto rv = _rebootIds.emplace(serverId, rebootId);
auto const rv = _rebootIds.try_emplace(serverId, rebootId);
auto const inserted = rv.second;
// If we inserted a new server, we may NOT already have any callbacks for
// it!
@ -166,11 +166,9 @@ CallbackGuard RebootTracker::callMeOnChange(RebootTracker::PeerState const& peer
unregisterCallback(peerState, callbackId);
});
auto emplaceRv =
callbackMap.emplace(callbackId, DescriptedCallback{std::move(callback),
auto const [iterator, inserted] =
callbackMap.try_emplace(callbackId, DescriptedCallback{std::move(callback),
std::move(callbackDescription)});
auto const iterator = emplaceRv.first;
bool const inserted = emplaceRv.second;
TRI_ASSERT(inserted);
TRI_ASSERT(callbackId == iterator->first);

View File

@ -25,7 +25,7 @@
#include <type_traits>
#include <boost/optional.hpp>
#include <optional>
#include "Basics/Common.h"
#include "Basics/Result.h"
@ -72,21 +72,21 @@ class ResultT {
}
ResultT static error(int errorNumber) {
return ResultT(boost::none, errorNumber);
return ResultT(std::nullopt, errorNumber);
}
ResultT static error(int errorNumber, std::string const& errorMessage) {
return ResultT(boost::none, errorNumber, errorMessage);
return ResultT(std::nullopt, errorNumber, errorMessage);
}
ResultT static error(Result const& other) {
TRI_ASSERT(other.fail());
return ResultT(boost::none, other);
return ResultT(std::nullopt, other);
}
ResultT static error(Result&& other) {
TRI_ASSERT(other.fail());
return ResultT(boost::none, std::move(other));
return ResultT(std::nullopt, std::move(other));
}
// This is disabled if U is implicitly convertible to Result
@ -175,9 +175,9 @@ class ResultT {
return ok();
}
T const& get() const { return _val.get(); }
T const& get() const { return _val.value(); }
T& get() { return _val.get(); }
T& get() { return _val.value(); }
ResultT map(ResultT<T> (*fun)(T const& val)) const {
if (ok()) {
@ -222,24 +222,24 @@ class ResultT {
protected:
Result _result;
boost::optional<T> _val;
std::optional<T> _val;
ResultT(boost::optional<T>&& val_, int errorNumber)
ResultT(std::optional<T>&& val_, int errorNumber)
: _result(errorNumber), _val(std::move(val_)) {}
ResultT(boost::optional<T>&& val_, int errorNumber, std::string const& errorMessage)
ResultT(std::optional<T>&& val_, int errorNumber, std::string const& errorMessage)
: _result(errorNumber, errorMessage), _val(val_) {}
ResultT(boost::optional<T> const& val_, int errorNumber)
ResultT(std::optional<T> const& val_, int errorNumber)
: _result(errorNumber), _val(std::move(val_)) {}
ResultT(boost::optional<T> const& val_, int errorNumber, std::string const& errorMessage)
ResultT(std::optional<T> const& val_, int errorNumber, std::string const& errorMessage)
: _result(errorNumber, errorMessage), _val(val_) {}
ResultT(boost::optional<T>&& val_, Result result)
ResultT(std::optional<T>&& val_, Result result)
: _result(std::move(result)), _val(std::move(val_)) {}
ResultT(boost::optional<T>&& val_, Result&& result)
ResultT(std::optional<T>&& val_, Result&& result)
: _result(std::move(result)), _val(std::move(val_)) {}
};

View File

@ -451,12 +451,12 @@ bool ServerState::integrateIntoCluster(ServerState::RoleEnum role,
if (!endpointSlice.isString()) {
continue;
}
auto it2 = endpoints.emplace(endpointSlice.copyString(), serverId);
if (!it2.second && it2.first->first != serverId) {
auto const [idIter, emplaced] = endpoints.try_emplace(endpointSlice.copyString(), serverId);
if (!emplaced && idIter->first != serverId) {
// duplicate entry!
LOG_TOPIC("9a134", WARN, Logger::CLUSTER)
<< "found duplicate server entry for endpoint '"
<< endpointSlice.copyString() << "', already used by other server " << it2.first->second
<< endpointSlice.copyString() << "', already used by other server " << idIter->second
<< ". it looks like this is a (mis)configuration issue";
// anyway, continue with startup
}
@ -610,7 +610,7 @@ bool ServerState::checkIfAgencyInitialized(AgencyComm& comm,
bool ServerState::registerAtAgencyPhase1(AgencyComm& comm, ServerState::RoleEnum const& role) {
// if the agency is not initialized, there is no point in continuing.
if(!checkIfAgencyInitialized(comm, role)) {
if (!checkIfAgencyInitialized(comm, role)) {
return false;
}

View File

@ -124,7 +124,7 @@ BaseEngine::BaseEngine(TRI_vocbase_t& vocbase,
_collections.add(name, AccessMode::Type::READ);
shards.emplace_back(std::move(name));
}
_vertexShards.emplace(collection.key.copyString(), std::move(shards));
_vertexShards.try_emplace(collection.key.copyString(), std::move(shards));
}
// FIXME: in the future this needs to be replaced with

View File

@ -72,8 +72,8 @@ TraverserEngineID TraverserEngineRegistry::createNew(
info->_expires = TRI_microtime() + ttl;
WRITE_LOCKER(writeLocker, _lock);
TRI_ASSERT(_engines.find(id) == _engines.end());
_engines.emplace(id, info.get());
auto [it, emplaced] =_engines.try_emplace(id, info.get());
TRI_ASSERT(emplaced);
info.release();
return id;
}

View File

@ -267,7 +267,7 @@ void AsyncJobManager::initAsyncJob(std::shared_ptr<RestHandler> handler) {
WRITE_LOCKER(writeLocker, _lock);
_jobs.emplace(jobId, std::make_pair(std::move(user), ajr));
_jobs.try_emplace(jobId, std::move(user), std::move(ajr));
}
////////////////////////////////////////////////////////////////////////////////

View File

@ -71,7 +71,7 @@ void GeneralServer::registerTask(std::shared_ptr<CommTask> task) {
{
auto* t = task.get();
std::lock_guard<std::recursive_mutex> guard(_tasksLock);
_commTasks.emplace(t, std::move(task));
_commTasks.try_emplace(t, std::move(task));
}
t->start();
}

View File

@ -125,7 +125,7 @@ RestHandler* RestHandlerFactory::createHandler(application_features::Application
////////////////////////////////////////////////////////////////////////////////
void RestHandlerFactory::addHandler(std::string const& path, create_fptr func, void* data) {
if (!_constructors.emplace(path, std::make_pair(func, data)).second) {
if (!_constructors.try_emplace(path, func, data).second) {
// there should only be one handler for each path
THROW_ARANGO_EXCEPTION_MESSAGE(
TRI_ERROR_INTERNAL,

View File

@ -28,6 +28,7 @@
#include "Basics/Result.h"
#include "Basics/ScopeGuard.h"
#include "Basics/VelocyPackHelper.h"
#include "Basics/tryEmplaceHelper.h"
#include "Cluster/ServerState.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "GeneralServer/GeneralServer.h"
@ -99,16 +100,16 @@ bool VstCommTask<T>::readCallback(asio_ns::error_code ec) {
this->close();
return false;
}
// Inspect the data we've received so far.
auto recvBuffs = this->_protocol->buffer.data(); // no copy
auto cursor = asio_ns::buffer_cast<const uint8_t*>(recvBuffs);
auto available = asio_ns::buffer_size(recvBuffs);
// TODO technically buffer_cast is deprecated
size_t parsedBytes = 0;
while (true) {
vst::Chunk chunk;
vst::parser::ChunkState state = vst::parser::ChunkState::Invalid;
if (_vstVersion == vst::VST1_1) {
@ -116,29 +117,29 @@ bool VstCommTask<T>::readCallback(asio_ns::error_code ec) {
} else if (_vstVersion == vst::VST1_0) {
state = vst::parser::readChunkVST1_0(chunk, cursor, available);
}
if (vst::parser::ChunkState::Incomplete == state) {
break;
} else if (vst::parser::ChunkState::Invalid == state) { // actually should never happen
this->close();
return false; // stop read loop
}
// move cursors
cursor += chunk.header.chunkLength();
available -= chunk.header.chunkLength();
parsedBytes += chunk.header.chunkLength();
// Process chunk
if (!processChunk(chunk)) {
this->close();
return false; // stop read loop
}
}
// Remove consumed data from receive buffer.
this->_protocol->buffer.consume(parsedBytes);
return true; // continue read loop
}
@ -155,11 +156,11 @@ bool VstCommTask<T>::processChunk(fuerte::vst::Chunk const& chunk) {
<< "\"vst-request\"; chunk was empty, this=" << this;
return false; // close connection
}
if (chunk.header.isFirst()) {
RequestStatistics* stat = this->acquireStatistics(chunk.header.messageID());
RequestStatistics::SET_READ_START(stat, TRI_microtime());
// single chunk optimization
if (chunk.header.numberOfChunks() == 1) {
VPackBuffer<uint8_t> buffer; // TODO lease buffers ?
@ -168,18 +169,16 @@ bool VstCommTask<T>::processChunk(fuerte::vst::Chunk const& chunk) {
return processMessage(std::move(buffer), chunk.header.messageID());
}
}
Message* msg;
// Find stored message for this chunk.
auto it = _messages.find(chunk.header.messageID());
if (it == _messages.end()) {
auto tmp = std::make_unique<Message>();
msg = tmp.get();
_messages.emplace(chunk.header.messageID(), std::move(tmp));
} else {
msg = it->second.get();
}
auto [it, emplaced] = _messages.try_emplace(
chunk.header.messageID(),
arangodb::lazyConstruct([&]{
return std::make_unique<Message>();
})
);
Message* msg = it->second.get();
// returns false if message gets too big
if (!msg->addChunk(chunk)) {
LOG_TOPIC("695fd", WARN, Logger::REQUESTS)
@ -187,11 +186,11 @@ bool VstCommTask<T>::processChunk(fuerte::vst::Chunk const& chunk) {
<< "allowed, this=" << this;
return false; // close connection
}
if (!msg->assemble()) {
return true; // wait for more chunks
}
//this->_proto->timer.cancel();
auto guard = scopeGuard([&] {
_messages.erase(chunk.header.messageID());
@ -207,7 +206,7 @@ bool VstCommTask<T>::processMessage(velocypack::Buffer<uint8_t> buffer,
auto ptr = buffer.data();
auto len = buffer.byteSize();
// first part of the buffer contains the response buffer
std::size_t headerLength = 0;
MessageType mt = MessageType::Undefined;
@ -234,7 +233,7 @@ bool VstCommTask<T>::processMessage(velocypack::Buffer<uint8_t> buffer,
RequestStatistics::SET_SUPERUSER(stat);
}
} else if (mt == MessageType::Request) { // request
VPackSlice header(buffer.data());
// the handler will take ownership of this pointer
auto req = std::make_unique<VstRequest>(this->_connectionInfo,
@ -264,7 +263,7 @@ bool VstCommTask<T>::processMessage(velocypack::Buffer<uint8_t> buffer,
<< (req->databaseName().empty() ? "" : "/_db/" + req->databaseName())
<< (Logger::logRequestParameters() ? req->fullUrl() : req->requestPath())
<< "\"";
CommTask::Flow cont = this->prepareExecution(*req.get());
if (cont == CommTask::Flow::Continue) {
auto resp = std::make_unique<VstResponse>(rest::ResponseCode::SERVER_ERROR, messageId);
@ -293,7 +292,7 @@ void VstCommTask<T>::sendResponse(std::unique_ptr<GeneralResponse> baseRes, Requ
#endif
this->finishExecution(*baseRes);
auto resItem = std::make_unique<ResponseItem>();
response.writeMessageHeader(resItem->metadata);
resItem->response = std::move(baseRes);
@ -308,14 +307,14 @@ void VstCommTask<T>::sendResponse(std::unique_ptr<GeneralResponse> baseRes, Requ
vst::message::prepareForNetwork(_vstVersion, response.messageId(),
resItem->metadata, payload,
resItem->buffers);
if (stat != nullptr) {
LOG_TOPIC("cf80d", TRACE, Logger::REQUESTS)
<< "\"vst-request-statistics\",\"" << (void*)this << "\",\""
<< static_cast<int>(response.responseCode()) << ","
<< this->_connectionInfo.clientAddress << "\"," << stat->timingsCsv();
}
double const totalTime = RequestStatistics::ELAPSED_SINCE_READ_START(stat);
// and give some request information
@ -324,7 +323,7 @@ void VstCommTask<T>::sendResponse(std::unique_ptr<GeneralResponse> baseRes, Requ
<< this->_connectionInfo.clientAddress << "\",\""
<< static_cast<int>(response.responseCode()) << ","
<< "\"," << Logger::FIXED(totalTime, 6);
while (true) {
if (_writeQueue.push(resItem.get())) {
break;
@ -332,7 +331,7 @@ void VstCommTask<T>::sendResponse(std::unique_ptr<GeneralResponse> baseRes, Requ
cpu_relax();
}
resItem.release();
bool expected = _writing.load();
if (false == expected) {
if (_writing.compare_exchange_strong(expected, true)) {
@ -344,9 +343,9 @@ void VstCommTask<T>::sendResponse(std::unique_ptr<GeneralResponse> baseRes, Requ
template<SocketType T>
void VstCommTask<T>::doWrite() {
TRI_ASSERT(_writing.load() == true);
while(true) { // loop instead of using recursion
ResponseItem* tmp = nullptr;
if (!_writeQueue.pop(tmp)) {
// careful now, we need to consider that someone queues
@ -370,7 +369,7 @@ void VstCommTask<T>::doWrite() {
asio_ns::async_write(this->_protocol->socket, buffers,
[self(CommTask::shared_from_this()), rsp(std::move(item))]
(asio_ns::error_code ec, size_t transferred) {
auto* thisPtr = static_cast<VstCommTask<T>*>(self.get());
RequestStatistics::SET_WRITE_END(rsp->stat);
RequestStatistics::ADD_SENT_BYTES(rsp->stat, rsp->buffers[0].size() + rsp->buffers[1].size());
@ -383,7 +382,6 @@ void VstCommTask<T>::doWrite() {
}
rsp->stat->release();
});
break; // done
}
}
@ -439,26 +437,26 @@ bool VstCommTask<T>::Message::addChunk(fuerte::vst::Chunk const& chunk) {
expectedChunks = chunk.header.numberOfChunks();
expectedMsgSize = chunk.header.messageLength();
chunks.reserve(expectedChunks);
TRI_ASSERT(buffer.empty());
if (buffer.capacity() < chunk.header.messageLength()) {
buffer.reserve(chunk.header.messageLength() - buffer.capacity());
}
}
// verify total message body size limit
size_t newSize = buffer.size() + chunk.body.size();
if (newSize > CommTask::MaximalBodySize ||
(expectedMsgSize != 0 && expectedMsgSize < newSize)) {
return false; // error
}
uint8_t const* begin = reinterpret_cast<uint8_t const*>(chunk.body.data());
size_t offset = buffer.size();
buffer.append(begin, chunk.body.size());
// Add chunk to index list
chunks.push_back(ChunkInfo{chunk.header.index(), offset, chunk.body.size()});
return true;
}
@ -468,7 +466,7 @@ bool VstCommTask<T>::Message::assemble() {
if (expectedChunks == 0 || chunks.size() < expectedChunks) {
return false;
}
// fast-path: chunks received in-order
bool reject = false;
for (size_t i = 0; i < expectedChunks; i++) {
@ -480,12 +478,12 @@ bool VstCommTask<T>::Message::assemble() {
if (!reject) { // fast-path, chunks are in order
return true;
}
// We now have all chunks. Sort them by index.
std::sort(chunks.begin(), chunks.end(), [](auto const& a, auto const& b) {
return a.index < b.index;
});
// Combine chunk content
VPackBuffer<uint8_t> cp(std::move(buffer));
buffer.clear();

View File

@ -24,6 +24,7 @@
#include "AttributeWeightShortestPathFinder.h"
#include "Basics/Exceptions.h"
#include "Basics/tryEmplaceHelper.h"
#include "Graph/EdgeCursor.h"
#include "Graph/EdgeDocumentToken.h"
#include "Graph/ShortestPathOptions.h"
@ -272,16 +273,20 @@ bool AttributeWeightShortestPathFinder::shortestPath(arangodb::velocypack::Slice
}
void AttributeWeightShortestPathFinder::inserter(
std::unordered_map<arangodb::velocypack::StringRef, size_t>& candidates,
std::vector<std::unique_ptr<Step>>& result,
arangodb::velocypack::StringRef const& s, arangodb::velocypack::StringRef const& t,
double currentWeight, EdgeDocumentToken&& edge) {
auto cand = candidates.find(t);
if (cand == candidates.end()) {
// Add weight
std::unordered_map<arangodb::velocypack::StringRef, size_t>& candidates,
std::vector<std::unique_ptr<Step>>& result,
arangodb::velocypack::StringRef const& s, arangodb::velocypack::StringRef const& t,
double currentWeight, EdgeDocumentToken&& edge) {
auto [cand, emplaced] = candidates.try_emplace(
t,
arangodb::lazyConstruct([&]{
result.emplace_back(std::make_unique<Step>(t, s, currentWeight, std::move(edge)));
candidates.emplace(t, result.size() - 1);
} else {
return result.size() - 1;
})
);
if (!emplaced) {
// Compare weight
auto& old = result[cand->second];
auto oldWeight = old->weight();

View File

@ -23,6 +23,7 @@
#include "ConstantWeightShortestPathFinder.h"
#include "Basics/tryEmplaceHelper.h"
#include "Cluster/ServerState.h"
#include "Graph/EdgeCursor.h"
#include "Graph/EdgeDocumentToken.h"
@ -70,8 +71,8 @@ bool ConstantWeightShortestPathFinder::shortestPath(
_rightClosure.clear();
clearVisited();
_leftFound.emplace(start, nullptr);
_rightFound.emplace(end, nullptr);
_leftFound.try_emplace(start, nullptr);
_rightFound.try_emplace(end, nullptr);
_leftClosure.emplace_back(start);
_rightClosure.emplace_back(end);
@ -112,12 +113,20 @@ bool ConstantWeightShortestPathFinder::expandClosure(Closure& sourceClosure,
for (size_t i = 0; i < neighborsSize; ++i) {
auto const& n = _neighbors[i];
if (sourceSnippets.find(n) == sourceSnippets.end()) {
bool emplaced = false;
std::tie(std::ignore, emplaced) = sourceSnippets.try_emplace(
_neighbors[i],
arangodb::lazyConstruct([&]{
return new PathSnippet(v, std::move(_edges[i]));
})
);
if (emplaced) {
// NOTE: _edges[i] stays intact after move
// and is reset to a nullptr. So if we crash
// here no mem-leaks. or undefined behavior
// Just make sure _edges is not used after
sourceSnippets.emplace(n, new PathSnippet(v, std::move(_edges[i])));
auto targetFoundIt = targetSnippets.find(n);
if (targetFoundIt != targetSnippets.end()) {
result = n;

View File

@ -27,7 +27,6 @@
#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>
#include <array>
#include <boost/variant.hpp>
#include <utility>
#include "Aql/AstNode.h"
@ -101,7 +100,7 @@ Graph::Graph(velocypack::Slice const& slice)
"Persisted graph is invalid. It does not "
"have a _rev set. Please contact support.");
}
TRI_ASSERT(!_graphName.empty());
TRI_ASSERT(!_rev.empty());
@ -509,7 +508,9 @@ bool Graph::removeEdgeDefinition(std::string const& edgeDefinitionName) {
// Graph doesn't contain this edge definition, no need to do anything.
return false;
}
EdgeDefinition const oldEdgeDef = maybeOldEdgeDef.get();
// This fails if we do not copy.
// Why don't we just work with pointers, when we use optionals without values?
EdgeDefinition const oldEdgeDef = maybeOldEdgeDef.value();
_edgeColls.erase(edgeDefinitionName);
_edgeDefs.erase(edgeDefinitionName);
@ -534,7 +535,7 @@ ResultT<EdgeDefinition const*> Graph::addEdgeDefinition(EdgeDefinition const& ed
}
_edgeColls.emplace(collection);
_edgeDefs.emplace(collection, edgeDefinition);
_edgeDefs.try_emplace(collection, edgeDefinition);
TRI_ASSERT(hasEdgeCollection(collection));
for (auto const& it : edgeDefinition.getFrom()) {
addVertexCollection(it);
@ -682,11 +683,11 @@ void Graph::createCollectionOptions(VPackBuilder& builder, bool waitForSync) con
builder.add(StaticStrings::MinReplicationFactor, VPackValue(writeConcern()));
}
boost::optional<const EdgeDefinition&> Graph::getEdgeDefinition(std::string const& collectionName) const {
std::optional<std::reference_wrapper<const EdgeDefinition>> Graph::getEdgeDefinition(std::string const& collectionName) const {
auto it = edgeDefinitions().find(collectionName);
if (it == edgeDefinitions().end()) {
TRI_ASSERT(!hasEdgeCollection(collectionName));
return boost::none;
return {std::nullopt};
}
TRI_ASSERT(hasEdgeCollection(collectionName));

View File

@ -162,7 +162,7 @@ class Graph {
bool renameCollections(std::string const& oldName, std::string const& newName);
boost::optional<EdgeDefinition const&> getEdgeDefinition(std::string const& collectionName) const;
std::optional<std::reference_wrapper<EdgeDefinition const>> getEdgeDefinition(std::string const& collectionName) const;
virtual bool isSmart() const;

View File

@ -29,7 +29,6 @@
#include <velocypack/velocypack-aliases.h>
#include <array>
#include <boost/range/join.hpp>
#include <boost/variant.hpp>
#include <utility>
#include "Aql/AstNode.h"

View File

@ -28,7 +28,6 @@
#include <velocypack/velocypack-aliases.h>
#include <array>
#include <boost/range/join.hpp>
#include <boost/variant.hpp>
#include <utility>
#include "Aql/Query.h"
@ -470,22 +469,22 @@ OperationResult GraphOperations::addEdgeDefinition(VPackSlice edgeDefinitionSlic
// TODO are orphans allowed?
OperationResult GraphOperations::getVertex(std::string const& collectionName,
std::string const& key,
boost::optional<TRI_voc_rid_t> rev) {
std::optional<TRI_voc_rid_t> rev) {
return getDocument(collectionName, key, std::move(rev));
}
// TODO check if definitionName is an edge collection in _graph?
OperationResult GraphOperations::getEdge(const std::string& definitionName,
const std::string& key,
boost::optional<TRI_voc_rid_t> rev) {
std::optional<TRI_voc_rid_t> rev) {
return getDocument(definitionName, key, std::move(rev));
}
OperationResult GraphOperations::getDocument(std::string const& collectionName,
std::string const& key,
boost::optional<TRI_voc_rid_t> rev) {
std::optional<TRI_voc_rid_t> rev) {
OperationOptions options;
options.ignoreRevs = !rev.is_initialized();
options.ignoreRevs = !rev.has_value();
VPackBufferPtr searchBuffer = _getSearchSlice(key, rev);
VPackSlice search{searchBuffer->data()};
@ -511,13 +510,13 @@ OperationResult GraphOperations::getDocument(std::string const& collectionName,
}
GraphOperations::VPackBufferPtr GraphOperations::_getSearchSlice(std::string const& key,
boost::optional<TRI_voc_rid_t>& rev) const {
std::optional<TRI_voc_rid_t>& rev) const {
VPackBuilder builder;
{
VPackObjectBuilder guard(&builder);
builder.add(StaticStrings::KeyString, VPackValue(key));
if (rev) {
builder.add(StaticStrings::RevString, VPackValue(TRI_RidToString(rev.get())));
builder.add(StaticStrings::RevString, VPackValue(TRI_RidToString(rev.value())));
}
}
@ -526,20 +525,20 @@ GraphOperations::VPackBufferPtr GraphOperations::_getSearchSlice(std::string con
OperationResult GraphOperations::removeEdge(std::string const& definitionName,
std::string const& key,
boost::optional<TRI_voc_rid_t> rev,
std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld) {
return removeEdgeOrVertex(definitionName, key, rev, waitForSync, returnOld);
}
OperationResult GraphOperations::modifyDocument(
std::string const& collectionName, std::string const& key, VPackSlice document,
bool isPatch, boost::optional<TRI_voc_rid_t> rev, bool waitForSync,
bool isPatch, std::optional<TRI_voc_rid_t> rev, bool waitForSync,
bool returnOld, bool returnNew, bool keepNull, transaction::Methods& trx) {
// extract the revision, if single document variant and header given:
std::unique_ptr<VPackBuilder> builder;
VPackSlice keyInBody = document.get(StaticStrings::KeyString);
if ((rev && TRI_ExtractRevisionId(document) != rev.get()) || keyInBody.isNone() ||
if ((rev && TRI_ExtractRevisionId(document) != rev.value()) || keyInBody.isNone() ||
keyInBody.isNull() || (keyInBody.isString() && keyInBody.copyString() != key)) {
// We need to rewrite the document with the given revision and key:
builder = std::make_unique<VPackBuilder>();
@ -548,14 +547,14 @@ OperationResult GraphOperations::modifyDocument(
TRI_SanitizeObject(document, *builder);
builder->add(StaticStrings::KeyString, VPackValue(key));
if (rev) {
builder->add(StaticStrings::RevString, VPackValue(TRI_RidToString(rev.get())));
builder->add(StaticStrings::RevString, VPackValue(TRI_RidToString(rev.value())));
}
}
document = builder->slice();
}
OperationOptions options;
options.ignoreRevs = !rev.is_initialized();
options.ignoreRevs = !rev.has_value();
options.waitForSync = waitForSync;
options.returnNew = returnNew;
options.returnOld = returnOld;
@ -592,7 +591,7 @@ OperationResult GraphOperations::createDocument(transaction::Methods* trx,
OperationResult GraphOperations::updateEdge(const std::string& definitionName,
const std::string& key, VPackSlice document,
boost::optional<TRI_voc_rid_t> rev,
std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld,
bool returnNew, bool keepNull) {
OperationResult res;
@ -609,7 +608,7 @@ OperationResult GraphOperations::updateEdge(const std::string& definitionName,
OperationResult GraphOperations::replaceEdge(const std::string& definitionName,
const std::string& key, VPackSlice document,
boost::optional<TRI_voc_rid_t> rev,
std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld,
bool returnNew, bool keepNull) {
OperationResult res;
@ -769,7 +768,7 @@ OperationResult GraphOperations::createEdge(const std::string& definitionName,
OperationResult GraphOperations::updateVertex(const std::string& collectionName,
const std::string& key, VPackSlice document,
boost::optional<TRI_voc_rid_t> rev,
std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld,
bool returnNew, bool keepNull) {
std::vector<std::string> writeCollections;
@ -790,7 +789,7 @@ OperationResult GraphOperations::updateVertex(const std::string& collectionName,
OperationResult GraphOperations::replaceVertex(const std::string& collectionName,
const std::string& key, VPackSlice document,
boost::optional<TRI_voc_rid_t> rev,
std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld,
bool returnNew, bool keepNull) {
std::vector<std::string> writeCollections;
@ -829,12 +828,12 @@ OperationResult GraphOperations::createVertex(const std::string& collectionName,
OperationResult GraphOperations::removeEdgeOrVertex(const std::string& collectionName,
const std::string& key,
boost::optional<TRI_voc_rid_t> rev,
std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld) {
OperationOptions options;
options.waitForSync = waitForSync;
options.returnOld = returnOld;
options.ignoreRevs = !rev.is_initialized();
options.ignoreRevs = !rev.has_value();
VPackBufferPtr searchBuffer = _getSearchSlice(key, rev);
VPackSlice search{searchBuffer->data()};
@ -923,7 +922,7 @@ OperationResult GraphOperations::removeEdgeOrVertex(const std::string& collectio
OperationResult GraphOperations::removeVertex(const std::string& collectionName,
const std::string& key,
boost::optional<TRI_voc_rid_t> rev,
std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld) {
return removeEdgeOrVertex(collectionName, key, rev, waitForSync, returnOld);
}

View File

@ -72,37 +72,37 @@ class GraphOperations {
/// This is because in case of a precondition error during trx.document(),
/// the OperationResult may still be needed.
OperationResult getVertex(std::string const& collectionName, std::string const& key,
boost::optional<TRI_voc_rid_t> rev);
std::optional<TRI_voc_rid_t> rev);
/// @brief Get a single edge document from definitionName.
/// Similar to getVertex().
OperationResult getEdge(const std::string& definitionName, const std::string& key,
boost::optional<TRI_voc_rid_t> rev);
std::optional<TRI_voc_rid_t> rev);
/// @brief Remove a single edge document from definitionName.
OperationResult removeEdge(const std::string& definitionName, const std::string& key,
boost::optional<TRI_voc_rid_t> rev,
std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld);
/// @brief Remove a vertex and all incident edges in the graph
OperationResult removeVertex(const std::string& collectionName, const std::string& key,
boost::optional<TRI_voc_rid_t> rev,
std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld);
/// @brief Remove an edge or vertex and all incident edges in the graph
OperationResult removeEdgeOrVertex(const std::string& collectionName,
const std::string& key,
boost::optional<TRI_voc_rid_t> rev,
std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld);
OperationResult updateEdge(const std::string& definitionName,
const std::string& key, VPackSlice document,
boost::optional<TRI_voc_rid_t> rev, bool waitForSync,
std::optional<TRI_voc_rid_t> rev, bool waitForSync,
bool returnOld, bool returnNew, bool keepNull);
OperationResult replaceEdge(const std::string& definitionName,
const std::string& key, VPackSlice document,
boost::optional<TRI_voc_rid_t> rev, bool waitForSync,
std::optional<TRI_voc_rid_t> rev, bool waitForSync,
bool returnOld, bool returnNew, bool keepNull);
OperationResult createEdge(const std::string& definitionName, VPackSlice document,
@ -131,12 +131,12 @@ class GraphOperations {
OperationResult updateVertex(const std::string& collectionName,
const std::string& key, VPackSlice document,
boost::optional<TRI_voc_rid_t> rev, bool waitForSync,
std::optional<TRI_voc_rid_t> rev, bool waitForSync,
bool returnOld, bool returnNew, bool keepNull);
OperationResult replaceVertex(const std::string& collectionName,
const std::string& key, VPackSlice document,
boost::optional<TRI_voc_rid_t> rev, bool waitForSync,
std::optional<TRI_voc_rid_t> rev, bool waitForSync,
bool returnOld, bool returnNew, bool keepNull);
OperationResult createVertex(const std::string& collectionName, VPackSlice document,
@ -187,16 +187,16 @@ class GraphOperations {
using VPackBufferPtr = std::shared_ptr<velocypack::Buffer<uint8_t>>;
OperationResult getDocument(std::string const& collectionName, const std::string& key,
boost::optional<TRI_voc_rid_t> rev);
std::optional<TRI_voc_rid_t> rev);
/// @brief creates a vpack { _key: key } or { _key: key, _rev: rev }
/// (depending on whether rev is set)
VPackBufferPtr _getSearchSlice(const std::string& key,
boost::optional<TRI_voc_rid_t>& rev) const;
std::optional<TRI_voc_rid_t>& rev) const;
OperationResult modifyDocument(const std::string& collectionName,
const std::string& key, VPackSlice document,
bool isPatch, boost::optional<TRI_voc_rid_t> rev,
bool isPatch, std::optional<TRI_voc_rid_t> rev,
bool waitForSync, bool returnOld, bool returnNew,
bool keepNull, transaction::Methods& trx);

View File

@ -96,7 +96,7 @@ bool KShortestPathsFinder::computeShortestPath(VertexRef const& start, VertexRef
void KShortestPathsFinder::computeNeighbourhoodOfVertexCache(VertexRef vertex,
Direction direction,
std::vector<Step>*& res) {
auto lookup = _vertexCache.emplace(vertex, FoundVertex(vertex)).first;
auto lookup = _vertexCache.try_emplace(vertex, FoundVertex(vertex)).first;
auto& cache = lookup->second; // want to update the cached vertex in place
switch (direction) {

View File

@ -102,9 +102,9 @@ VPackSlice TraverserCache::lookupInCollection(arangodb::velocypack::StringRef id
std::string collectionName = id.substr(0,pos).toString();
auto const& map = _baseOptions->collectionToShard();
if(!map.empty()) {
if (!map.empty()) {
auto found = map.find(collectionName);
if ( found != map.end()) {
if (found != map.end()) {
collectionName = found->second;
}
}

View File

@ -28,6 +28,7 @@
#include "Aql/PruneExpressionEvaluator.h"
#include "Aql/Query.h"
#include "Basics/StringUtils.h"
#include "Basics/tryEmplaceHelper.h"
#include "Basics/VelocyPackHelper.h"
#include "Cluster/ClusterEdgeCursor.h"
#include "Graph/SingleServerTraverser.h"
@ -190,13 +191,13 @@ arangodb::traverser::TraverserOptions::TraverserOptions(arangodb::aql::Query* qu
size_t length = collections.length();
for (auto const& depth : VPackObjectIterator(read)) {
uint64_t d = basics::StringUtils::uint64(depth.key.copyString());
auto it = _depthLookupInfo.emplace(d, std::vector<LookupInfo>());
TRI_ASSERT(it.second);
auto [it, emplaced] = _depthLookupInfo.try_emplace(d, std::vector<LookupInfo>());
TRI_ASSERT(emplaced);
VPackSlice list = depth.value;
TRI_ASSERT(length == list.length());
it.first->second.reserve(length);
it->second.reserve(length);
for (size_t j = 0; j < length; ++j) {
it.first->second.emplace_back(query, list.at(j), collections.at(j));
it->second.emplace_back(query, list.at(j), collections.at(j));
}
}
}
@ -213,12 +214,17 @@ arangodb::traverser::TraverserOptions::TraverserOptions(arangodb::aql::Query* qu
for (auto const& info : VPackObjectIterator(read)) {
uint64_t d = basics::StringUtils::uint64(info.key.copyString());
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
auto it = _vertexExpressions.emplace(d, new aql::Expression(query->plan(),
bool emplaced = false;
std::tie(std::ignore, emplaced) = _vertexExpressions.try_emplace(d, new aql::Expression(query->plan(),
query->ast(), info.value));
TRI_ASSERT(it.second);
TRI_ASSERT(emplaced);
#else
_vertexExpressions.emplace(d, new aql::Expression(query->plan(),
query->ast(), info.value));
_vertexExpressions.try_emplace(
d,
arangodb::lazyConstruct([&]{
return new aql::Expression(query->plan(), query->ast(), info.value);
})
);
#endif
}
}

View File

@ -446,7 +446,7 @@ arangodb::aql::AqlValue aqlFnTokens(arangodb::aql::ExpressionContext* expression
iresearch::string_ref(arangodb::iresearch::IResearchAnalyzerFeature::identity()->name());
auto& server = arangodb::application_features::ApplicationServer::server();
if( args.size() > 1) {
if (args.size() > 1) {
auto& analyzers = server.getFeature<arangodb::iresearch::IResearchAnalyzerFeature>();
if (trx) {
auto sysVocbase =
@ -547,7 +547,7 @@ arangodb::aql::AqlValue aqlFnTokens(arangodb::aql::ExpressionContext* expression
default:
if (current.isNumber()) { // there are many "number" types. To adopt all current and future ones just
// deal with them all here in generic way
if(!numeric_analyzer) {
if (!numeric_analyzer) {
numeric_analyzer = std::make_unique<irs::numeric_token_stream>();
numeric_terms = numeric_analyzer->attributes().get<irs::term_attribute>().get();
if (ADB_UNLIKELY(!numeric_terms)) {
@ -1556,7 +1556,7 @@ AnalyzerPool::ptr IResearchAnalyzerFeature::get( // find analyzer
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "failed to create arangosearch static analyzer");
}
analyzers.emplace(
analyzers.try_emplace(
irs::make_hashed_ref(irs::string_ref(pool->name()), std::hash<irs::string_ref>()),
pool);
}
@ -1606,7 +1606,7 @@ AnalyzerPool::ptr IResearchAnalyzerFeature::get( // find analyzer
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "failed to create arangosearch static analyzer instance");
}
analyzers.emplace(
analyzers.try_emplace(
irs::make_hashed_ref(irs::string_ref(pool->name()), std::hash<irs::string_ref>()),
pool);
}
@ -1735,7 +1735,7 @@ arangodb::Result IResearchAnalyzerFeature::loadAnalyzers(
return arangodb::Result(); // db-server should not access cluster during inRecovery
}
} else if (arangodb::ServerState::instance()->isSingleServer()) { // single server
if(itr != _lastLoad.end()) {
if (itr != _lastLoad.end()) {
return arangodb::Result(); // do not reload on single-server
}
} else if (itr != _lastLoad.end() // had a previous load
@ -1912,23 +1912,23 @@ arangodb::Result IResearchAnalyzerFeature::loadAnalyzers(
// different database
if (split.first != vocbase->name()) {
auto result = analyzers.emplace(entry.first, entry.second);
auto [it, emplaced] = analyzers.try_emplace(entry.first, entry.second);
if (!result.second) { // existing entry
if (result.first->second // valid new entry
&& !equalAnalyzer(*(entry.second), result.first->second->type(), result.first->second->properties(), result.first->second->features())) {
if (!emplaced) { // existing entry
if (it->second // valid new entry
&& !equalAnalyzer(*(entry.second), it->second->type(), it->second->properties(), it->second->features())) {
return arangodb::Result( // result
TRI_ERROR_BAD_PARAMETER, // code
"name collision detected while re-registering a duplicate arangosearch analizer name '" + std::string(result.first->second->name()) +
"' type '" + std::string(result.first->second->type()) +
"' properties '" + result.first->second->properties().toString() +
"name collision detected while re-registering a duplicate arangosearch analizer name '" + std::string(it->second->name()) +
"' type '" + std::string(it->second->type()) +
"' properties '" + it->second->properties().toString() +
"', previous registration type '" + std::string(entry.second->type()) +
"' properties '" + entry.second->properties().toString() + "'"
);
}
result.first->second = entry.second; // reuse old analyzer pool to avoid duplicates in memmory
const_cast<Analyzers::key_type&>(result.first->first) = entry.first; // point key at old pool
it->second = entry.second; // reuse old analyzer pool to avoid duplicates in memmory
const_cast<Analyzers::key_type&>(it->first) = entry.first; // point key at old pool
}
continue; // done with this analyzer

View File

@ -591,7 +591,7 @@ bool IResearchLinkMeta::json( // append meta jSON
name = entry._pool->name(); // verbatim (assume already normalized)
}
analyzers.emplace(name, entry._pool);
analyzers.try_emplace(name, entry._pool);
analyzersBuilder.add(arangodb::velocypack::Value(std::move(name)));
}

View File

@ -286,7 +286,7 @@ void ScorerReplacer::replace(aql::CalculationNode& node) {
// create variable
auto* var = ast->variables()->createTemporaryVariable();
it = _dedup.emplace(key, var).first;
it = _dedup.try_emplace(key, var).first;
}
return ast->createNodeReference(it->second);

View File

@ -281,7 +281,7 @@ struct IResearchView::ViewFactory : public arangodb::ViewFactory {
: nullptr; // add placeholders to links, when the
// collection comes up it'll bring up the link
impl->_links.emplace(cid, link ? link->self()
impl->_links.try_emplace(cid, link ? link->self()
: nullptr); // add placeholders to links, when the link
// comes up it'll call link(...)
}
@ -676,7 +676,7 @@ arangodb::Result IResearchView::link(AsyncLinkPtr const& link) {
auto itr = _links.find(cid);
if (itr == _links.end()) {
_links.emplace(cid, link);
_links.try_emplace(cid, link);
} else if (arangodb::ServerState::instance()->isSingleServer() // single server
&& !itr->second) {
_links[cid] = link;

View File

@ -287,15 +287,12 @@ arangodb::Result IResearchViewCoordinator::link(IResearchLink const& link) {
WriteMutex mutex(_mutex); // '_collections' can be asynchronously read
SCOPED_LOCK(mutex);
auto entry = _collections.emplace( // emplace definition
std::piecewise_construct, // piecewise construct
std::forward_as_tuple(cid), // key
std::forward_as_tuple( // value
link.collection().name(), std::move(sanitizedBuilder) // args
)
auto [it, emplaced] = _collections.try_emplace( // emplace definition
cid, // key
link.collection().name(), std::move(sanitizedBuilder) // value
);
if (!entry.second) {
if (!emplaced) {
return arangodb::Result( // result
TRI_ERROR_ARANGO_DUPLICATE_IDENTIFIER, // code
std::string("duplicate entry while emplacing collection '") + std::to_string(cid) + "' into arangosearch View '" + name() + "'"

View File

@ -184,7 +184,7 @@ Result IndexFactory::emplace(std::string const& type, IndexTypeFactory const& fa
}
}
if (!_factories.emplace(type, &factory).second) {
if (!_factories.try_emplace(type, &factory).second) {
return arangodb::Result(TRI_ERROR_ARANGO_DUPLICATE_IDENTIFIER, std::string("index factory previously registered during index factory "
"registration for index type '") +
type +

View File

@ -483,7 +483,7 @@ bool SimpleAttributeEqualityMatcher::accessFitsIndex(
if (match) {
// mark ith attribute as being covered
_found.emplace(i, op);
_found.try_emplace(i, op);
TRI_IF_FAILURE("SimpleAttributeMatcher::accessFitsIndex") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}

View File

@ -148,7 +148,7 @@ static MMFilesDatafileStatisticsContainer* FindDatafileStats(OpenIteratorState*
}
auto stats = std::make_unique<MMFilesDatafileStatisticsContainer>();
state->_stats.emplace(fid, stats.get());
state->_stats.try_emplace(fid, stats.get());
return stats.release();
}

View File

@ -75,7 +75,7 @@ void MMFilesDatafileStatistics::create(TRI_voc_fid_t fid) {
LOG_TOPIC("e63cd", TRACE, arangodb::Logger::DATAFILES)
<< "creating statistics for datafile " << fid;
_stats.emplace(fid, stats.get());
_stats.try_emplace(fid, stats.get());
stats.release();
}
@ -97,7 +97,7 @@ void MMFilesDatafileStatistics::create(TRI_voc_fid_t fid,
LOG_TOPIC("82801", TRACE, arangodb::Logger::DATAFILES)
<< "creating statistics for datafile " << fid << " from initial data";
_stats.emplace(fid, stats.get());
_stats.try_emplace(fid, stats.get());
stats.release();
}

View File

@ -35,6 +35,7 @@
#include "Basics/build.h"
#include "Basics/encoding.h"
#include "Basics/files.h"
#include "Basics/tryEmplaceHelper.h"
#include "FeaturePhases/BasicFeaturePhaseServer.h"
#include "MMFiles/MMFilesCleanupThread.h"
#include "MMFiles/MMFilesCollection.h"
@ -99,13 +100,15 @@ static uint64_t getNumericFilenamePartFromDatafile(std::string const& filename)
/// @brief extract the numeric part from a filename
static uint64_t getNumericFilenamePartFromDatabase(std::string const& filename) {
auto size = filename.size();
auto data = filename.data();
char const* pos = strrchr(filename.c_str(), '-');
if (pos == nullptr) {
return 0;
}
return basics::StringUtils::uint64(pos + 1);
size -= std::distance(data, pos);
return basics::StringUtils::uint64(pos + 1, size);
}
static uint64_t getNumericFilenamePartFromDatafile(MMFilesDatafile const* datafile) {
@ -2591,7 +2594,7 @@ int MMFilesEngine::startCleanup(TRI_vocbase_t* vocbase) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
_cleanupThreads.emplace(vocbase, std::move(thread));
_cleanupThreads.try_emplace(vocbase, std::move(thread));
}
return TRI_ERROR_NO_ERROR;
@ -2634,21 +2637,22 @@ int MMFilesEngine::startCompactor(TRI_vocbase_t& vocbase) {
{
MUTEX_LOCKER(locker, _threadsLock);
auto it = _compactorThreads.find(&vocbase);
auto [it, emplaced] = _compactorThreads.try_emplace(
&vocbase,
arangodb::lazyConstruct([&]{
thread.reset(new MMFilesCompactorThread(vocbase));
if (!thread->start()) {
LOG_TOPIC("3addc", ERR, arangodb::Logger::COMPACTOR)
<< "could not start compactor thread";
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
return std::move(thread);
})
);
if (it != _compactorThreads.end()) {
if (!emplaced) {
return TRI_ERROR_INTERNAL;
}
thread.reset(new MMFilesCompactorThread(vocbase));
if (!thread->start()) {
LOG_TOPIC("3addc", ERR, arangodb::Logger::COMPACTOR)
<< "could not start compactor thread";
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
_compactorThreads.emplace(&vocbase, std::move(thread));
}
return TRI_ERROR_NO_ERROR;

View File

@ -97,7 +97,7 @@ MMFilesHashIndexLookupBuilder::MMFilesHashIndexLookupBuilder(
_inStorage->openArray();
}
valNode->toVelocyPackValue(*(_inStorage.get()));
_inPosition.emplace(j, std::make_pair(0, std::vector<arangodb::velocypack::Slice>()));
_inPosition.try_emplace(j, 0, std::vector<arangodb::velocypack::Slice>());
_usesIn = true;
storageOrder.emplace_back(j);
_mappingFieldCondition.push_back(nullptr);

View File

@ -980,7 +980,7 @@ void MMFilesLogfileManager::relinkLogfile(MMFilesWalLogfile* logfile) {
MMFilesWalLogfile::IdType const id = logfile->id();
WRITE_LOCKER(writeLocker, _logfilesLock);
_logfiles.emplace(id, logfile);
_logfiles.try_emplace(id, logfile);
}
// removes logfiles that are allowed to be removed
@ -1178,7 +1178,7 @@ TRI_voc_tick_t MMFilesLogfileManager::addLogfileBarrier(TRI_voc_tick_t databaseI
{
WRITE_LOCKER(barrierLock, _barriersLock);
_barriers.emplace(id, logfileBarrier.get());
_barriers.try_emplace(id, logfileBarrier.get());
}
logfileBarrier.release();
@ -2184,7 +2184,7 @@ int MMFilesLogfileManager::inventory() {
TRI_UpdateTickServer(static_cast<TRI_voc_tick_t>(id));
WRITE_LOCKER(writeLocker, _logfilesLock);
_logfiles.emplace(id, nullptr);
_logfiles.try_emplace(id, nullptr);
}
}
}
@ -2348,7 +2348,7 @@ int MMFilesLogfileManager::createReserveLogfile(uint32_t size) {
{
WRITE_LOCKER(writeLocker, _logfilesLock);
_logfiles.emplace(id, logfile.get());
_logfiles.try_emplace(id, logfile.get());
}
logfile.release();

View File

@ -69,7 +69,7 @@ void MMFilesTransactionContextData::pinData(LogicalCollection* collection) {
}
try {
_ditches.emplace(cid, ditch);
_ditches.try_emplace(cid, ditch);
} catch (...) {
ditch->ditches()->freeMMFilesDocumentDitch(ditch, true);
throw;

View File

@ -66,7 +66,7 @@ void MMFilesTransactionManager::registerTransaction(TRI_voc_tid_t transactionId,
WRITE_LOCKER(writeLocker, _transactions[bucket]._lock);
// insert into currently running list of transactions
_transactions[bucket]._activeTransactions.emplace(transactionId, std::move(data));
_transactions[bucket]._activeTransactions.try_emplace(transactionId, std::move(data));
}
// unregisters a transaction

View File

@ -165,7 +165,7 @@ WalAccessResult MMFilesWalAccess::openTransactions(WalAccess::Filter const& filt
TRI_ASSERT(tid > 0);
if (type == TRI_DF_MARKER_VPACK_BEGIN_TRANSACTION) {
transactions.emplace(tid, foundTick);
transactions.try_emplace(tid, foundTick);
} else if (type == TRI_DF_MARKER_VPACK_COMMIT_TRANSACTION ||
type == TRI_DF_MARKER_VPACK_ABORT_TRANSACTION) {
transactions.erase(tid);

View File

@ -137,7 +137,7 @@ TRI_vocbase_t* MMFilesWalRecoverState::useDatabase(TRI_voc_tick_t databaseId) {
return nullptr;
}
openedDatabases.emplace(databaseId, vocbase);
openedDatabases.try_emplace(databaseId, vocbase);
return vocbase;
}
@ -228,7 +228,7 @@ arangodb::LogicalCollection* MMFilesWalRecoverState::useCollection(TRI_vocbase_t
// disable secondary indexes for the moment
physical->useSecondaryIndexes(false);
openedCollections.emplace(collectionId, collection);
openedCollections.try_emplace(collectionId, collection);
res = TRI_ERROR_NO_ERROR;
return collection.get();
}
@ -398,7 +398,7 @@ bool MMFilesWalRecoverState::InitialScanMarker(MMFilesMarker const* marker, void
// it
TRI_voc_tick_t const databaseId = MMFilesDatafileHelper::DatabaseId(marker);
TRI_voc_tid_t const tid = MMFilesDatafileHelper::TransactionId(marker);
state->failedTransactions.emplace(tid, std::make_pair(databaseId, false));
state->failedTransactions.try_emplace(tid, std::make_pair(databaseId, false));
break;
}

View File

@ -83,7 +83,7 @@ static std::string const& nameFromCid(MMFilesReplicationDumpContext* dump, TRI_v
if (!name.empty()) {
// insert into cache
try {
dump->_collectionNames.emplace(cid, std::move(name));
dump->_collectionNames.try_emplace(cid, std::move(name));
// and look it up again
return nameFromCid(dump, cid);
@ -758,7 +758,7 @@ int MMFilesDetermineOpenTransactionsReplication(MMFilesReplicationDumpContext* d
TRI_ASSERT(tid > 0);
if (type == TRI_DF_MARKER_VPACK_BEGIN_TRANSACTION) {
transactions.emplace(tid, foundTick);
transactions.try_emplace(tid, foundTick);
} else if (type == TRI_DF_MARKER_VPACK_COMMIT_TRANSACTION ||
type == TRI_DF_MARKER_VPACK_ABORT_TRANSACTION) {
transactions.erase(tid);

View File

@ -48,19 +48,16 @@ ConnectionPool::~ConnectionPool() { shutdown(); }
/// note: it is the callers responsibility to ensure the endpoint
/// is always the same, we do not do any post-processing
network::ConnectionPtr ConnectionPool::leaseConnection(std::string const& endpoint) {
READ_LOCKER(guard, _lock);
auto it = _connections.find(endpoint);
if (it == _connections.end()) {
guard.unlock();
WRITE_LOCKER(wguard, _lock);
it = _connections.find(endpoint); // check again
if (it == _connections.end()) {
auto it2 = _connections.emplace(endpoint, std::make_unique<Bucket>());
it = it2.first;
}
return selectConnection(it->first, *(it->second));
auto tmp = std::make_unique<Bucket>(); //get memory outside lock
WRITE_LOCKER(wguard, _lock);
auto [it2, emplaced] = _connections.try_emplace(endpoint, std::move(tmp));
it = it2;
}
return selectConnection(it->first,*(it->second));
}
@ -82,7 +79,7 @@ void ConnectionPool::shutdown() {
WRITE_LOCKER(guard, _lock);
_connections.clear();
}
void ConnectionPool::removeBrokenConnections(Bucket& buck) {
auto it = buck.list.begin();
while (it != buck.list.end()) {
@ -112,7 +109,7 @@ void ConnectionPool::pruneConnections() {
if (buck.list.size() <= _config.minOpenConnections) {
continue;
}
// first remove old connections
auto it = buck.list.begin();
while (it != buck.list.end()) {
@ -132,16 +129,16 @@ void ConnectionPool::pruneConnections() {
}
it++;
}
// do not remove connections if there are less
if (buck.list.size() <= _config.maxOpenConnections) {
continue; // done
}
LOG_TOPIC("2d59a", DEBUG, Logger::COMMUNICATION)
<< "pruning extra connections to '" << pair.first
<< "' (" << buck.list.size() << ")";
// remove any remaining connections, they will be closed eventually
it = buck.list.begin();
while (it != buck.list.end()) {
@ -152,15 +149,15 @@ void ConnectionPool::pruneConnections() {
}
}
}
/// @brief cancel connections to this endpoint
void ConnectionPool::cancelConnections(std::string const& endpoint) {
fuerte::ConnectionBuilder builder;
builder.endpoint(endpoint);
builder.protocolType(_config.protocol); // always overwrite protocol
std::string normalized = builder.normalizedEndpoint();
WRITE_LOCKER(guard, _lock);
auto const& it = _connections.find(normalized);
if (it != _connections.end()) {
@ -214,7 +211,7 @@ ConnectionPtr ConnectionPool::selectConnection(std::string const& endpoint,
if (state == fuerte::Connection::State::Failed) {
continue;
}
size_t num = c.fuerte->requestsLeft();
if (_config.protocol == fuerte::ProtocolType::Http && num == 0) {
auto now = std::chrono::steady_clock::now();
@ -229,14 +226,14 @@ ConnectionPtr ConnectionPool::selectConnection(std::string const& endpoint,
return c.fuerte; // TODO: make (num <= 3) configurable ?
}
}
// no free connection found, so we add one
fuerte::ConnectionBuilder builder;
builder.endpoint(endpoint); // picks the socket type
builder.protocolType(_config.protocol); // always overwrite protocol
TRI_ASSERT(builder.socketType() != SocketType::Undefined);
std::shared_ptr<fuerte::Connection> fuerte = createConnection(builder);
bucket.list.push_back(Context{fuerte, std::chrono::steady_clock::now()});
return fuerte;

View File

@ -556,9 +556,9 @@ struct DMIDComputation : public VertexComputation<DMIDValue, float, DMIDMessage>
* This vertex is a global leader. Set Membership degree to
* 100%
*/
vertexState->membershipDegree.emplace(_id, 1.0f);
vertexState->membershipDegree.try_emplace(_id, 1.0f);
} else {
vertexState->membershipDegree.emplace(_id, 0.0f);
vertexState->membershipDegree.try_emplace(_id, 0.0f);
}
}
});

View File

@ -89,7 +89,7 @@ struct SLPAComputation : public VertexComputation<SLPAValue, int8_t, uint64_t> {
void compute(MessageIterator<uint64_t> const& messages) override {
SLPAValue* val = mutableVertexData();
if (globalSuperstep() == 0) {
val->memory.emplace(val->nodeId, 1);
val->memory.try_emplace(val->nodeId, 1);
val->numCommunities = 1;
}

View File

@ -497,7 +497,7 @@ static void resolveInfo(TRI_vocbase_t* vocbase, CollectionID const& collectionID
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND, collectionID);
}
collectionPlanIdMap.emplace(collectionID, std::to_string(lc->planId()));
collectionPlanIdMap.try_emplace(collectionID, std::to_string(lc->planId()));
allShards.push_back(collectionID);
serverMap[ss->getId()][collectionID].push_back(collectionID);
@ -508,7 +508,7 @@ static void resolveInfo(TRI_vocbase_t* vocbase, CollectionID const& collectionID
if (lc->deleted()) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND, collectionID);
}
collectionPlanIdMap.emplace(collectionID, std::to_string(lc->planId()));
collectionPlanIdMap.try_emplace(collectionID, std::to_string(lc->planId()));
std::shared_ptr<std::vector<ShardID>> shardIDs =
ci.getShardList(std::to_string(lc->id()));

View File

@ -180,7 +180,7 @@ void CombiningOutCache<M>::appendMessage(PregelShard shard,
if (it != vertexMap.end()) { // more than one message
_combiner->combine(vertexMap[key], data);
} else { // first message for this vertex
vertexMap.emplace(key, data);
vertexMap.try_emplace(key, data);
if (++(this->_containedMessages) >= this->_batchSize) {
// LOG_TOPIC("23bc7", INFO, Logger::PREGEL) << "Hit buffer limit";

Some files were not shown because too many files have changed in this diff Show More