diff options
author | Bynn Lee <bynn.lee@mongodb.com> | 2021-02-24 21:34:16 +0000 |
---|---|---|
committer | Evergreen Agent <no-reply@evergreen.mongodb.com> | 2021-02-25 01:55:59 +0000 |
commit | b8107b8e481ae7073d30304196a3028145c80634 (patch) | |
tree | cc954ce4d68fd790a38ef7f1fecc825c14f6d9b6 /src/mongo | |
parent | bff2d6e263a19c85eca7058ceb829ff55b1e2d63 (diff) | |
download | mongo-b8107b8e481ae7073d30304196a3028145c80634.tar.gz |
Revert "SERVER-43762 tighten the overload set for BSONObjBuilder::appendNumber"
This reverts commit 3307ba57eef2dfff9abe2413e39058ac9451ec04.
Diffstat (limited to 'src/mongo')
64 files changed, 389 insertions, 253 deletions
diff --git a/src/mongo/bson/bsonobjbuilder.h b/src/mongo/bson/bsonobjbuilder.h index a7860a45588..e7b6b4a89f3 100644 --- a/src/mongo/bson/bsonobjbuilder.h +++ b/src/mongo/bson/bsonobjbuilder.h @@ -249,6 +249,19 @@ public: typename = void> Derived& append(StringData fieldName, const T& n) = delete; + /** appends a number. if n < max(int)/2 then uses int, otherwise long long */ + Derived& appendIntOrLL(StringData fieldName, long long n) { + // extra () to avoid max macro on windows + static const long long maxInt = (std::numeric_limits<int>::max)() / 2; + static const long long minInt = -maxInt; + if (minInt < n && n < maxInt) { + append(fieldName, static_cast<int>(n)); + } else { + append(fieldName, n); + } + return static_cast<Derived&>(*this); + } + /** * appendNumber is a series of method for appending the smallest sensible type * mostly for JS @@ -261,16 +274,29 @@ public: return append(fieldName, d); } + Derived& appendNumber(StringData fieldName, size_t n) { + static const size_t maxInt = (1 << 30); + if (n < maxInt) + append(fieldName, static_cast<int>(n)); + else + append(fieldName, static_cast<long long>(n)); + return static_cast<Derived&>(*this); + } + Derived& appendNumber(StringData fieldName, Decimal128 decNumber) { return append(fieldName, decNumber); } Derived& appendNumber(StringData fieldName, long long llNumber) { - static const long long maxInt = std::numeric_limits<int>::max(); - static const long long minInt = std::numeric_limits<int>::min(); + static const long long maxInt = (1LL << 30); + static const long long minInt = -maxInt; + static const long long maxDouble = (1LL << 40); + static const long long minDouble = -maxDouble; - if (minInt <= llNumber && llNumber <= maxInt) { + if (minInt < llNumber && llNumber < maxInt) { append(fieldName, static_cast<int>(llNumber)); + } else if (minDouble < llNumber && llNumber < maxDouble) { + append(fieldName, static_cast<double>(llNumber)); } else { append(fieldName, llNumber); } diff --git a/src/mongo/bson/bsonobjbuilder_test.cpp b/src/mongo/bson/bsonobjbuilder_test.cpp index 08f0fb43fbd..c47bd71a199 100644 --- a/src/mongo/bson/bsonobjbuilder_test.cpp +++ b/src/mongo/bson/bsonobjbuilder_test.cpp @@ -40,6 +40,9 @@ namespace { using std::string; +const long long maxEncodableInt = (1 << 30) - 1; +const long long minEncodableInt = -maxEncodableInt; + const long long maxInt = (std::numeric_limits<int>::max)(); const long long minInt = (std::numeric_limits<int>::min)(); @@ -84,30 +87,112 @@ TEST(BSONObjBuilderTest, AppendUnsignedIsForbidden) { MONGO_STATIC_ASSERT(!isUnsignedAppendable<unsigned long>::value); MONGO_STATIC_ASSERT(!isUnsignedAppendable<unsigned long long>::value); MONGO_STATIC_ASSERT(!isUnsignedAppendable<uint64_t>::value); - MONGO_STATIC_ASSERT(!isUnsignedAppendable<size_t>::value); } /** - * current conversion ranges in appendNumber(long long n) - * int max/min in comments refer to max/min encodable constants - * n < int_min -----> long long + * current conversion ranges in appendIntOrLL(long long n) + * dbl/int max/min in comments refer to max/min encodable constants + * n < dbl_min -----> long long + * dbl_min <= n < int_min -----> double * int_min <= n <= int_max -----> int - * int_max < n -----> long long + * int_max < n <= dbl_max -----> double + * dbl_max < n -----> long long */ -TEST(BSONObjBuilderTest, AppendNumberLongLong) { +TEST(BSONObjBuilderTest, AppendIntOrLL) { struct { long long v; BSONType t; } data[] = {{0, mongo::NumberInt}, {-100, mongo::NumberInt}, {100, mongo::NumberInt}, - {minInt, mongo::NumberInt}, - {maxInt, mongo::NumberInt}, + {-(maxInt / 2 - 1), mongo::NumberInt}, + {maxInt / 2 - 1, mongo::NumberInt}, + {-(maxInt / 2), mongo::NumberLong}, + {maxInt / 2, mongo::NumberLong}, + {minEncodableInt, mongo::NumberLong}, + {maxEncodableInt, mongo::NumberLong}, + {minEncodableInt - 1, mongo::NumberLong}, + {maxEncodableInt + 1, mongo::NumberLong}, + {minInt, mongo::NumberLong}, + {maxInt, mongo::NumberLong}, {minInt - 1, mongo::NumberLong}, {maxInt + 1, mongo::NumberLong}, - {minEncodableDouble, mongo::NumberLong}, - {maxEncodableDouble, mongo::NumberLong}, + {minLongLong, mongo::NumberLong}, + {maxLongLong, mongo::NumberLong}, + {0, mongo::Undefined}}; + for (int i = 0; data[i].t != mongo::Undefined; i++) { + long long v = data[i].v; + BSONObjBuilder b; + b.appendIntOrLL("a", v); + BSONObj o = b.obj(); + ASSERT_EQUALS(o.nFields(), 1); + BSONElement e = o.getField("a"); + long long n = e.numberLong(); + ASSERT_EQUALS(n, v); + assertBSONTypeEquals(e.type(), data[i].t, v, i); + } +} + +/** + * current conversion ranges in appendNumber(size_t n) + * dbl/int max/min in comments refer to max/min encodable constants + * 0 <= n <= int_max -----> int + * int_max < n -----> long long + */ + +TEST(BSONObjBuilderTest, AppendNumberSizeT) { + struct { + size_t v; + BSONType t; + } data[] = {{0, mongo::NumberInt}, + {100, mongo::NumberInt}, + {maxEncodableInt, mongo::NumberInt}, + {maxEncodableInt + 1, mongo::NumberLong}, + {size_t(maxInt), mongo::NumberLong}, + {size_t(maxInt) + 1U, mongo::NumberLong}, + {(std::numeric_limits<size_t>::max)(), mongo::NumberLong}, + {0, mongo::Undefined}}; + for (int i = 0; data[i].t != mongo::Undefined; i++) { + size_t v = data[i].v; + BSONObjBuilder b; + b.appendNumber("a", v); + BSONObj o = b.obj(); + ASSERT_EQUALS(o.nFields(), 1); + BSONElement e = o.getField("a"); + size_t n = e.numberLong(); + ASSERT_EQUALS(n, v); + assertBSONTypeEquals(e.type(), data[i].t, v, i); + } +} + +/** + * current conversion ranges in appendNumber(long long n) + * dbl/int max/min in comments refer to max/min encodable constants + * n < dbl_min -----> long long + * dbl_min <= n < int_min -----> double + * int_min <= n <= int_max -----> int + * int_max < n <= dbl_max -----> double + * dbl_max < n -----> long long + */ + +TEST(BSONObjBuilderTest, AppendNumberLongLong) { + struct { + long long v; + BSONType t; + } data[] = {{0, mongo::NumberInt}, + {-100, mongo::NumberInt}, + {100, mongo::NumberInt}, + {minEncodableInt, mongo::NumberInt}, + {maxEncodableInt, mongo::NumberInt}, + {minEncodableInt - 1, mongo::NumberDouble}, + {maxEncodableInt + 1, mongo::NumberDouble}, + {minInt, mongo::NumberDouble}, + {maxInt, mongo::NumberDouble}, + {minInt - 1, mongo::NumberDouble}, + {maxInt + 1, mongo::NumberDouble}, + {minEncodableDouble, mongo::NumberDouble}, + {maxEncodableDouble, mongo::NumberDouble}, {minEncodableDouble - 1, mongo::NumberLong}, {maxEncodableDouble + 1, mongo::NumberLong}, {minDouble, mongo::NumberLong}, diff --git a/src/mongo/db/commands/drop_indexes.cpp b/src/mongo/db/commands/drop_indexes.cpp index 035ad1b0663..9a4ef95c51f 100644 --- a/src/mongo/db/commands/drop_indexes.cpp +++ b/src/mongo/db/commands/drop_indexes.cpp @@ -210,7 +210,7 @@ public: } } - result.appendNumber("nIndexesWas", static_cast<long long>(all.size())); + result.appendNumber("nIndexesWas", all.size()); std::unique_ptr<MultiIndexBlock> indexer = std::make_unique<MultiIndexBlock>(); indexer->setIndexBuildMethod(IndexBuildMethod::kForeground); diff --git a/src/mongo/db/commands/fail_point_cmd.cpp b/src/mongo/db/commands/fail_point_cmd.cpp index 0940c811d5a..47ce52bf3f1 100644 --- a/src/mongo/db/commands/fail_point_cmd.cpp +++ b/src/mongo/db/commands/fail_point_cmd.cpp @@ -101,7 +101,7 @@ public: BSONObjBuilder& result) override { const std::string failPointName(cmdObj.firstElement().str()); const auto timesEntered = setGlobalFailPoint(failPointName, cmdObj); - result.appendNumber("count", timesEntered); + result.appendIntOrLL("count", timesEntered); return true; } }; diff --git a/src/mongo/db/commands/generic_servers.cpp b/src/mongo/db/commands/generic_servers.cpp index e25588af7a4..342acc56b63 100644 --- a/src/mongo/db/commands/generic_servers.cpp +++ b/src/mongo/db/commands/generic_servers.cpp @@ -279,8 +279,7 @@ public: } typename RamLogType::LineIterator rl(ramlog); - result.appendNumber("totalLinesWritten", - static_cast<long long>(rl.getTotalLinesWritten())); + result.appendNumber("totalLinesWritten", rl.getTotalLinesWritten()); BSONArrayBuilder arr(result.subarrayStart("log")); while (rl.more()) diff --git a/src/mongo/db/commands/write_commands/write_commands.cpp b/src/mongo/db/commands/write_commands/write_commands.cpp index 33726d0c16d..33f4f719367 100644 --- a/src/mongo/db/commands/write_commands/write_commands.cpp +++ b/src/mongo/db/commands/write_commands/write_commands.cpp @@ -902,8 +902,7 @@ public: std::string help() const final { return "insert documents"; } -} // namespace -cmdInsert; +} cmdInsert; class CmdUpdate final : public WriteCommand<write_ops::UpdateReply> { public: diff --git a/src/mongo/db/curop.cpp b/src/mongo/db/curop.cpp index 6a2e0aead94..3898a2f98ab 100644 --- a/src/mongo/db/curop.cpp +++ b/src/mongo/db/curop.cpp @@ -1269,7 +1269,7 @@ void OpDebug::append(OperationContext* opCtx, b.append("remoteOpWaitMillis", durationCount<Milliseconds>(*remoteOpWaitTime)); } - b.appendNumber("millis", durationCount<Milliseconds>(executionTime)); + b.appendIntOrLL("millis", durationCount<Milliseconds>(executionTime)); if (!curop.getPlanSummary().empty()) { b.append("planSummary", curop.getPlanSummary()); @@ -1546,10 +1546,10 @@ std::function<BSONObj(ProfileFilter::Args)> OpDebug::appendStaged(StringSet requ // the profiler (OpDebug::append) and the log file (OpDebug::report), so for the profile filter // we support both names. addIfNeeded("millis", [](auto field, auto args, auto& b) { - b.appendNumber(field, durationCount<Milliseconds>(args.op.executionTime)); + b.appendIntOrLL(field, durationCount<Milliseconds>(args.op.executionTime)); }); addIfNeeded("durationMillis", [](auto field, auto args, auto& b) { - b.appendNumber(field, durationCount<Milliseconds>(args.op.executionTime)); + b.appendIntOrLL(field, durationCount<Milliseconds>(args.op.executionTime)); }); addIfNeeded("planSummary", [](auto field, auto args, auto& b) { diff --git a/src/mongo/db/exec/sbe/stages/branch.cpp b/src/mongo/db/exec/sbe/stages/branch.cpp index 90d07536f80..36715084bd9 100644 --- a/src/mongo/db/exec/sbe/stages/branch.cpp +++ b/src/mongo/db/exec/sbe/stages/branch.cpp @@ -184,13 +184,11 @@ std::unique_ptr<PlanStageStats> BranchStage::getStats(bool includeDebugInfo) con if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("numTested", static_cast<long long>(_specificStats.numTested)); - bob.appendNumber("thenBranchOpens", static_cast<long long>(_specificStats.thenBranchOpens)); - bob.appendNumber("thenBranchCloses", - static_cast<long long>(_specificStats.thenBranchCloses)); - bob.appendNumber("elseBranchOpens", static_cast<long long>(_specificStats.elseBranchOpens)); - bob.appendNumber("elseBranchCloses", - static_cast<long long>(_specificStats.elseBranchCloses)); + bob.appendNumber("numTested", _specificStats.numTested); + bob.appendNumber("thenBranchOpens", _specificStats.thenBranchOpens); + bob.appendNumber("thenBranchCloses", _specificStats.thenBranchCloses); + bob.appendNumber("elseBranchOpens", _specificStats.elseBranchOpens); + bob.appendNumber("elseBranchCloses", _specificStats.elseBranchCloses); bob.append("filter", DebugPrinter{}.print(_filter->debugPrint())); bob.append("thenSlots", _inputThenVals); bob.append("elseSlots", _inputElseVals); diff --git a/src/mongo/db/exec/sbe/stages/bson_scan.cpp b/src/mongo/db/exec/sbe/stages/bson_scan.cpp index 154d7d4552c..f3222d6c04a 100644 --- a/src/mongo/db/exec/sbe/stages/bson_scan.cpp +++ b/src/mongo/db/exec/sbe/stages/bson_scan.cpp @@ -145,7 +145,7 @@ std::unique_ptr<PlanStageStats> BSONScanStage::getStats(bool includeDebugInfo) c if (includeDebugInfo) { BSONObjBuilder bob; if (_recordSlot) { - bob.appendNumber("recordSlot", static_cast<long long>(*_recordSlot)); + bob.appendIntOrLL("recordSlot", *_recordSlot); } bob.append("field", _fields); bob.append("outputSlots", _vars); diff --git a/src/mongo/db/exec/sbe/stages/check_bounds.cpp b/src/mongo/db/exec/sbe/stages/check_bounds.cpp index c1d4707e10a..0b8738a95b5 100644 --- a/src/mongo/db/exec/sbe/stages/check_bounds.cpp +++ b/src/mongo/db/exec/sbe/stages/check_bounds.cpp @@ -140,10 +140,10 @@ std::unique_ptr<PlanStageStats> CheckBoundsStage::getStats(bool includeDebugInfo if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("seeks", static_cast<long long>(_specificStats.seeks)); - bob.appendNumber("inKeySlot", static_cast<long long>(_inKeySlot)); - bob.appendNumber("inRecordIdSlot", static_cast<long long>(_inRecordIdSlot)); - bob.appendNumber("outSlot", static_cast<long long>(_outSlot)); + bob.appendNumber("seeks", _specificStats.seeks); + bob.appendIntOrLL("inKeySlot", _inKeySlot); + bob.appendIntOrLL("inRecordIdSlot", _inRecordIdSlot); + bob.appendIntOrLL("outSlot", _outSlot); ret->debugInfo = bob.obj(); } diff --git a/src/mongo/db/exec/sbe/stages/filter.h b/src/mongo/db/exec/sbe/stages/filter.h index a3ee0355146..66760acf2f5 100644 --- a/src/mongo/db/exec/sbe/stages/filter.h +++ b/src/mongo/db/exec/sbe/stages/filter.h @@ -138,7 +138,7 @@ public: if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("numTested", static_cast<long long>(_specificStats.numTested)); + bob.appendNumber("numTested", _specificStats.numTested); bob.append("filter", DebugPrinter{}.print(_filter->debugPrint())); ret->debugInfo = bob.obj(); } diff --git a/src/mongo/db/exec/sbe/stages/ix_scan.cpp b/src/mongo/db/exec/sbe/stages/ix_scan.cpp index 430b19c2ee5..db48badf335 100644 --- a/src/mongo/db/exec/sbe/stages/ix_scan.cpp +++ b/src/mongo/db/exec/sbe/stages/ix_scan.cpp @@ -327,19 +327,19 @@ std::unique_ptr<PlanStageStats> IndexScanStage::getStats(bool includeDebugInfo) if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("numReads", static_cast<long long>(_specificStats.numReads)); - bob.appendNumber("seeks", static_cast<long long>(_specificStats.seeks)); + bob.appendNumber("numReads", _specificStats.numReads); + bob.appendNumber("seeks", _specificStats.seeks); if (_recordSlot) { - bob.appendNumber("recordSlot", static_cast<long long>(*_recordSlot)); + bob.appendIntOrLL("recordSlot", *_recordSlot); } if (_recordIdSlot) { - bob.appendNumber("recordIdSlot", static_cast<long long>(*_recordIdSlot)); + bob.appendIntOrLL("recordIdSlot", *_recordIdSlot); } if (_seekKeySlotLow) { - bob.appendNumber("seekKeySlotLow", static_cast<long long>(*_seekKeySlotLow)); + bob.appendIntOrLL("seekKeySlotLow", *_seekKeySlotLow); } if (_seekKeySlotHigh) { - bob.appendNumber("seekKeySlotHigh", static_cast<long long>(*_seekKeySlotHigh)); + bob.appendIntOrLL("seekKeySlotHigh", *_seekKeySlotHigh); } bob.append("outputSlots", _vars); bob.append("indexKeysToInclude", _indexKeysToInclude.to_string()); diff --git a/src/mongo/db/exec/sbe/stages/loop_join.cpp b/src/mongo/db/exec/sbe/stages/loop_join.cpp index 98f0f3e0085..0205cd9e2f0 100644 --- a/src/mongo/db/exec/sbe/stages/loop_join.cpp +++ b/src/mongo/db/exec/sbe/stages/loop_join.cpp @@ -166,8 +166,8 @@ std::unique_ptr<PlanStageStats> LoopJoinStage::getStats(bool includeDebugInfo) c if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("innerOpens", static_cast<long long>(_specificStats.innerOpens)); - bob.appendNumber("innerCloses", static_cast<long long>(_specificStats.innerCloses)); + bob.appendNumber("innerOpens", _specificStats.innerOpens); + bob.appendNumber("innerCloses", _specificStats.innerCloses); bob.append("outerProjects", _outerProjects); bob.append("outerCorrelated", _outerCorrelated); if (_predicate) { diff --git a/src/mongo/db/exec/sbe/stages/makeobj.cpp b/src/mongo/db/exec/sbe/stages/makeobj.cpp index 2c46aa48f80..7d8c73743bb 100644 --- a/src/mongo/db/exec/sbe/stages/makeobj.cpp +++ b/src/mongo/db/exec/sbe/stages/makeobj.cpp @@ -381,9 +381,9 @@ std::unique_ptr<PlanStageStats> MakeObjStageBase<O>::getStats(bool includeDebugI if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("objSlot", static_cast<long long>(_objSlot)); + bob.appendIntOrLL("objSlot", _objSlot); if (_rootSlot) { - bob.appendNumber("rootSlot", static_cast<long long>(*_rootSlot)); + bob.appendIntOrLL("rootSlot", *_rootSlot); } if (_fieldBehavior) { bob.append("fieldBehavior", *_fieldBehavior == FieldBehavior::drop ? "drop" : "keep"); diff --git a/src/mongo/db/exec/sbe/stages/scan.cpp b/src/mongo/db/exec/sbe/stages/scan.cpp index 9e411a87135..2e8ded40b82 100644 --- a/src/mongo/db/exec/sbe/stages/scan.cpp +++ b/src/mongo/db/exec/sbe/stages/scan.cpp @@ -289,15 +289,15 @@ std::unique_ptr<PlanStageStats> ScanStage::getStats(bool includeDebugInfo) const if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("numReads", static_cast<long long>(_specificStats.numReads)); + bob.appendNumber("numReads", _specificStats.numReads); if (_recordSlot) { - bob.appendNumber("recordSlot", static_cast<long long>(*_recordSlot)); + bob.appendIntOrLL("recordSlot", *_recordSlot); } if (_recordIdSlot) { - bob.appendNumber("recordIdSlot", static_cast<long long>(*_recordIdSlot)); + bob.appendIntOrLL("recordIdSlot", *_recordIdSlot); } if (_seekKeySlot) { - bob.appendNumber("seekKeySlot", static_cast<long long>(*_seekKeySlot)); + bob.appendIntOrLL("seekKeySlot", *_seekKeySlot); } bob.append("fields", _fields); bob.append("outputSlots", _vars); diff --git a/src/mongo/db/exec/sbe/stages/sort.cpp b/src/mongo/db/exec/sbe/stages/sort.cpp index 13bae045aae..7126dbea9fc 100644 --- a/src/mongo/db/exec/sbe/stages/sort.cpp +++ b/src/mongo/db/exec/sbe/stages/sort.cpp @@ -236,9 +236,8 @@ std::unique_ptr<PlanStageStats> SortStage::getStats(bool includeDebugInfo) const if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("memLimit", static_cast<long long>(_specificStats.maxMemoryUsageBytes)); - bob.appendNumber("totalDataSizeSorted", - static_cast<long long>(_specificStats.totalDataSizeBytes)); + bob.appendIntOrLL("memLimit", _specificStats.maxMemoryUsageBytes); + bob.appendIntOrLL("totalDataSizeSorted", _specificStats.totalDataSizeBytes); bob.appendBool("usedDisk", _specificStats.spills > 0); BSONObjBuilder childrenBob(bob.subobjStart("orderBySlots")); diff --git a/src/mongo/db/exec/sbe/stages/spool.cpp b/src/mongo/db/exec/sbe/stages/spool.cpp index caffc5c77d7..e0a51b28748 100644 --- a/src/mongo/db/exec/sbe/stages/spool.cpp +++ b/src/mongo/db/exec/sbe/stages/spool.cpp @@ -126,7 +126,7 @@ std::unique_ptr<PlanStageStats> SpoolEagerProducerStage::getStats(bool includeDe if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("spoolId", static_cast<long long>(_spoolId)); + bob.appendIntOrLL("spoolId", _spoolId); bob.append("outputSlots", _vals); ret->debugInfo = bob.obj(); } @@ -273,7 +273,7 @@ std::unique_ptr<PlanStageStats> SpoolLazyProducerStage::getStats(bool includeDeb if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("spoolId", static_cast<long long>(_spoolId)); + bob.appendIntOrLL("spoolId", _spoolId); bob.append("outputSlots", _vals); if (_predicate) { bob.append("filter", DebugPrinter{}.print(_predicate->debugPrint())); diff --git a/src/mongo/db/exec/sbe/stages/spool.h b/src/mongo/db/exec/sbe/stages/spool.h index d6eabed2026..995b10076a0 100644 --- a/src/mongo/db/exec/sbe/stages/spool.h +++ b/src/mongo/db/exec/sbe/stages/spool.h @@ -225,7 +225,7 @@ public: if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("spoolId", static_cast<long long>(_spoolId)); + bob.appendIntOrLL("spoolId", _spoolId); bob.append("outputSlots", _vals); ret->debugInfo = bob.obj(); } diff --git a/src/mongo/db/exec/sbe/stages/text_match.cpp b/src/mongo/db/exec/sbe/stages/text_match.cpp index 23afc8b5aa0..25c2e21c53d 100644 --- a/src/mongo/db/exec/sbe/stages/text_match.cpp +++ b/src/mongo/db/exec/sbe/stages/text_match.cpp @@ -116,8 +116,8 @@ std::unique_ptr<PlanStageStats> TextMatchStage::getStats(bool includeDebugInfo) if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("inputSlot", static_cast<long long>(_inputSlot)); - bob.appendNumber("outputSlot", static_cast<long long>(_outputSlot)); + bob.appendIntOrLL("inputSlot", _inputSlot); + bob.appendIntOrLL("outputSlot", _outputSlot); ret->debugInfo = bob.obj(); } diff --git a/src/mongo/db/exec/sbe/stages/traverse.cpp b/src/mongo/db/exec/sbe/stages/traverse.cpp index f222e8addc2..0d87e043aa3 100644 --- a/src/mongo/db/exec/sbe/stages/traverse.cpp +++ b/src/mongo/db/exec/sbe/stages/traverse.cpp @@ -274,14 +274,14 @@ std::unique_ptr<PlanStageStats> TraverseStage::getStats(bool includeDebugInfo) c if (includeDebugInfo) { DebugPrinter printer; BSONObjBuilder bob; - bob.appendNumber("innerOpens", static_cast<long long>(_specificStats.innerOpens)); - bob.appendNumber("innerCloses", static_cast<long long>(_specificStats.innerCloses)); - bob.appendNumber("inputSlot", static_cast<long long>(_inField)); - bob.appendNumber("outputSlot", static_cast<long long>(_outField)); - bob.appendNumber("outputSlotInner", static_cast<long long>(_outFieldInner)); + bob.appendNumber("innerOpens", _specificStats.innerOpens); + bob.appendNumber("innerCloses", _specificStats.innerCloses); + bob.appendIntOrLL("inputSlot", _inField); + bob.appendIntOrLL("outputSlot", _outField); + bob.appendIntOrLL("outputSlotInner", _outFieldInner); bob.append("correlatedSlots", _correlatedSlots); if (_nestedArraysDepth) { - bob.appendNumber("nestedArraysDepth", static_cast<long long>(*_nestedArraysDepth)); + bob.appendNumber("nestedArraysDepth", *_nestedArraysDepth); } if (_fold) { bob.append("fold", printer.print(_fold->debugPrint())); diff --git a/src/mongo/db/exec/sbe/stages/unique.cpp b/src/mongo/db/exec/sbe/stages/unique.cpp index 4437df5908d..a03162ebc35 100644 --- a/src/mongo/db/exec/sbe/stages/unique.cpp +++ b/src/mongo/db/exec/sbe/stages/unique.cpp @@ -99,8 +99,8 @@ std::unique_ptr<PlanStageStats> UniqueStage::getStats(bool includeDebugInfo) con if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("dupsTested", static_cast<long long>(_specificStats.dupsTested)); - bob.appendNumber("dupsDropped", static_cast<long long>(_specificStats.dupsDropped)); + bob.appendNumber("dupsTested", _specificStats.dupsTested); + bob.appendNumber("dupsDropped", _specificStats.dupsDropped); bob.append("keySlots", _keySlots); ret->debugInfo = bob.obj(); } diff --git a/src/mongo/db/exec/sbe/stages/unwind.cpp b/src/mongo/db/exec/sbe/stages/unwind.cpp index 63f3af745d1..3616517942a 100644 --- a/src/mongo/db/exec/sbe/stages/unwind.cpp +++ b/src/mongo/db/exec/sbe/stages/unwind.cpp @@ -166,10 +166,10 @@ std::unique_ptr<PlanStageStats> UnwindStage::getStats(bool includeDebugInfo) con if (includeDebugInfo) { BSONObjBuilder bob; - bob.appendNumber("inputSlot", static_cast<long long>(_inField)); - bob.appendNumber("outSlot", static_cast<long long>(_outField)); - bob.appendNumber("outIndexSlot", static_cast<long long>(_outIndex)); - bob.appendNumber("preserveNullAndEmptyArrays", _preserveNullAndEmptyArrays); + bob.appendIntOrLL("inputSlot", _inField); + bob.appendIntOrLL("outSlot", _outField); + bob.appendIntOrLL("outIndexSlot", _outIndex); + bob.appendIntOrLL("preserveNullAndEmptyArrays", _preserveNullAndEmptyArrays); ret->debugInfo = bob.obj(); } diff --git a/src/mongo/db/matcher/doc_validation_error.cpp b/src/mongo/db/matcher/doc_validation_error.cpp index 95d54a5f0f1..164bb3d16c2 100644 --- a/src/mongo/db/matcher/doc_validation_error.cpp +++ b/src/mongo/db/matcher/doc_validation_error.cpp @@ -465,8 +465,7 @@ void finishLogicalOperatorChildError(const ListOfMatchExpression* expr, if (ctx->haveLatestCompleteError()) { if (operatorsWithOrderedClauses.find(tag) != operatorsWithOrderedClauses.end()) { BSONObjBuilder subBuilder = ctx->getCurrentArrayBuilder().subobjStart(); - subBuilder.appendNumber("index", - static_cast<long long>(ctx->getCurrentChildIndex())); + subBuilder.appendNumber("index", ctx->getCurrentChildIndex()); ctx->appendLatestCompleteError(&subBuilder); subBuilder.done(); } else { diff --git a/src/mongo/db/pipeline/accumulator_js_test.cpp b/src/mongo/db/pipeline/accumulator_js_test.cpp index 953b4ce475a..92e11e592a8 100644 --- a/src/mongo/db/pipeline/accumulator_js_test.cpp +++ b/src/mongo/db/pipeline/accumulator_js_test.cpp @@ -230,7 +230,7 @@ TEST_F(MapReduceFixture, InternalJsReduceFailsIfExtraArgumentsAreSpecified) { TEST_F(MapReduceFixture, InternalJsReduceFailsIfEvalArgumentNotOfTypeStringOrCode) { BSONObjBuilder codeTypeInt; - codeTypeInt.appendNumber("eval", 1); + codeTypeInt.appendIntOrLL("eval", 1); codeTypeInt.append("data", BSON("k" << std::string("foo") << "v" << Value(2))); BSONObjBuilder wrapInt; wrapInt.append("$_internalJsReduce", codeTypeInt.obj()); diff --git a/src/mongo/db/pipeline/resume_token.cpp b/src/mongo/db/pipeline/resume_token.cpp index 5d3a5e78d4c..2272bf1d434 100644 --- a/src/mongo/db/pipeline/resume_token.cpp +++ b/src/mongo/db/pipeline/resume_token.cpp @@ -105,7 +105,7 @@ ResumeToken::ResumeToken(const ResumeTokenData& data) { if (data.version >= 1) { builder.appendNumber("", data.tokenType); } - builder.appendNumber("", static_cast<long long>(data.txnOpIndex)); + builder.appendNumber("", data.txnOpIndex); if (data.version >= 1) { builder.appendBool("", data.fromInvalidate); } diff --git a/src/mongo/db/query/explain.cpp b/src/mongo/db/query/explain.cpp index f8218b6651b..330e2709a6d 100644 --- a/src/mongo/db/query/explain.cpp +++ b/src/mongo/db/query/explain.cpp @@ -168,7 +168,7 @@ void generateSinglePlanExecutionInfo(const PlanExplainer::PlanStatsDetails& deta auto&& [stats, summary] = details; invariant(summary); - out->appendNumber("nReturned", static_cast<long long>(summary->nReturned)); + out->appendNumber("nReturned", summary->nReturned); // Time elapsed could might be either precise or approximate. if (totalTimeMillis) { @@ -177,8 +177,8 @@ void generateSinglePlanExecutionInfo(const PlanExplainer::PlanStatsDetails& deta out->appendNumber("executionTimeMillisEstimate", summary->executionTimeMillisEstimate); } - out->appendNumber("totalKeysExamined", static_cast<long long>(summary->totalKeysExamined)); - out->appendNumber("totalDocsExamined", static_cast<long long>(summary->totalDocsExamined)); + out->appendNumber("totalKeysExamined", summary->totalKeysExamined); + out->appendNumber("totalDocsExamined", summary->totalDocsExamined); if (summary->planFailed) { out->appendBool("failed", true); diff --git a/src/mongo/db/query/plan_explainer_impl.cpp b/src/mongo/db/query/plan_explainer_impl.cpp index b5ffc341545..9a6193fa715 100644 --- a/src/mongo/db/query/plan_explainer_impl.cpp +++ b/src/mongo/db/query/plan_explainer_impl.cpp @@ -193,18 +193,18 @@ void statsToBSON(const PlanStageStats& stats, // Some top-level exec stats get pulled out of the root stage. if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("nReturned", static_cast<long long>(stats.common.advanced)); + bob->appendNumber("nReturned", stats.common.advanced); // Include executionTimeMillis if it was recorded. if (stats.common.executionTimeMillis) { bob->appendNumber("executionTimeMillisEstimate", *stats.common.executionTimeMillis); } - bob->appendNumber("works", static_cast<long long>(stats.common.works)); - bob->appendNumber("advanced", static_cast<long long>(stats.common.advanced)); - bob->appendNumber("needTime", static_cast<long long>(stats.common.needTime)); - bob->appendNumber("needYield", static_cast<long long>(stats.common.needYield)); - bob->appendNumber("saveState", static_cast<long long>(stats.common.yields)); - bob->appendNumber("restoreState", static_cast<long long>(stats.common.unyields)); + bob->appendNumber("works", stats.common.works); + bob->appendNumber("advanced", stats.common.advanced); + bob->appendNumber("needTime", stats.common.needTime); + bob->appendNumber("needYield", stats.common.needYield); + bob->appendNumber("saveState", stats.common.yields); + bob->appendNumber("restoreState", stats.common.unyields); if (stats.common.failed) bob->appendBool("failed", stats.common.failed); bob->appendNumber("isEOF", stats.common.isEOF); @@ -215,12 +215,12 @@ void statsToBSON(const PlanStageStats& stats, AndHashStats* spec = static_cast<AndHashStats*>(stats.specific.get()); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("memUsage", static_cast<long long>(spec->memUsage)); - bob->appendNumber("memLimit", static_cast<long long>(spec->memLimit)); + bob->appendNumber("memUsage", spec->memUsage); + bob->appendNumber("memLimit", spec->memLimit); for (size_t i = 0; i < spec->mapAfterChild.size(); ++i) { bob->appendNumber(std::string(str::stream() << "mapAfterChild_" << i), - static_cast<long long>(spec->mapAfterChild[i])); + spec->mapAfterChild[i]); } } } else if (STAGE_AND_SORTED == stats.stageType) { @@ -229,7 +229,7 @@ void statsToBSON(const PlanStageStats& stats, if (verbosity >= ExplainOptions::Verbosity::kExecStats) { for (size_t i = 0; i < spec->failedAnd.size(); ++i) { bob->appendNumber(std::string(str::stream() << "failedAnd_" << i), - static_cast<long long>(spec->failedAnd[i])); + spec->failedAnd[i]); } } } else if (STAGE_COLLSCAN == stats.stageType) { @@ -248,7 +248,7 @@ void statsToBSON(const PlanStageStats& stats, [&](const char* str, int size) { bob->append("maxRecord", OID::from(str)); }); } if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("docsExamined", static_cast<long long>(spec->docsTested)); + bob->appendNumber("docsExamined", spec->docsTested); } } else if (STAGE_COUNT == stats.stageType) { CountStats* spec = static_cast<CountStats*>(stats.specific.get()); @@ -261,7 +261,7 @@ void statsToBSON(const PlanStageStats& stats, CountScanStats* spec = static_cast<CountScanStats*>(stats.specific.get()); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("keysExamined", static_cast<long long>(spec->keysExamined)); + bob->appendNumber("keysExamined", spec->keysExamined); } bob->append("keyPattern", spec->keyPattern); @@ -288,7 +288,7 @@ void statsToBSON(const PlanStageStats& stats, DeleteStats* spec = static_cast<DeleteStats*>(stats.specific.get()); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("nWouldDelete", static_cast<long long>(spec->docsDeleted)); + bob->appendNumber("nWouldDelete", spec->docsDeleted); } } else if (STAGE_DISTINCT_SCAN == stats.stageType) { DistinctScanStats* spec = static_cast<DistinctScanStats*>(stats.specific.get()); @@ -315,7 +315,7 @@ void statsToBSON(const PlanStageStats& stats, } if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("keysExamined", static_cast<long long>(spec->keysExamined)); + bob->appendNumber("keysExamined", spec->keysExamined); } } else if (STAGE_ENSURE_SORTED == stats.stageType) { EnsureSortedStats* spec = static_cast<EnsureSortedStats*>(stats.specific.get()); @@ -326,8 +326,8 @@ void statsToBSON(const PlanStageStats& stats, } else if (STAGE_FETCH == stats.stageType) { FetchStats* spec = static_cast<FetchStats*>(stats.specific.get()); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("docsExamined", static_cast<long long>(spec->docsExamined)); - bob->appendNumber("alreadyHasObj", static_cast<long long>(spec->alreadyHasObj)); + bob->appendNumber("docsExamined", spec->docsExamined); + bob->appendNumber("alreadyHasObj", spec->alreadyHasObj); } } else if (STAGE_GEO_NEAR_2D == stats.stageType || STAGE_GEO_NEAR_2DSPHERE == stats.stageType) { NearStats* spec = static_cast<NearStats*>(stats.specific.get()); @@ -353,8 +353,8 @@ void statsToBSON(const PlanStageStats& stats, } else if (STAGE_IDHACK == stats.stageType) { IDHackStats* spec = static_cast<IDHackStats*>(stats.specific.get()); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("keysExamined", static_cast<long long>(spec->keysExamined)); - bob->appendNumber("docsExamined", static_cast<long long>(spec->docsExamined)); + bob->appendNumber("keysExamined", spec->keysExamined); + bob->appendNumber("docsExamined", spec->docsExamined); } } else if (STAGE_IXSCAN == stats.stageType) { IndexScanStats* spec = static_cast<IndexScanStats*>(stats.specific.get()); @@ -381,21 +381,21 @@ void statsToBSON(const PlanStageStats& stats, } if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("keysExamined", static_cast<long long>(spec->keysExamined)); - bob->appendNumber("seeks", static_cast<long long>(spec->seeks)); - bob->appendNumber("dupsTested", static_cast<long long>(spec->dupsTested)); - bob->appendNumber("dupsDropped", static_cast<long long>(spec->dupsDropped)); + bob->appendNumber("keysExamined", spec->keysExamined); + bob->appendNumber("seeks", spec->seeks); + bob->appendNumber("dupsTested", spec->dupsTested); + bob->appendNumber("dupsDropped", spec->dupsDropped); } } else if (STAGE_OR == stats.stageType) { OrStats* spec = static_cast<OrStats*>(stats.specific.get()); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("dupsTested", static_cast<long long>(spec->dupsTested)); - bob->appendNumber("dupsDropped", static_cast<long long>(spec->dupsDropped)); + bob->appendNumber("dupsTested", spec->dupsTested); + bob->appendNumber("dupsDropped", spec->dupsDropped); } } else if (STAGE_LIMIT == stats.stageType) { LimitStats* spec = static_cast<LimitStats*>(stats.specific.get()); - bob->appendNumber("limitAmount", static_cast<long long>(spec->limit)); + bob->appendNumber("limitAmount", spec->limit); } else if (isProjectionStageType(stats.stageType)) { ProjectionStats* spec = static_cast<ProjectionStats*>(stats.specific.get()); bob->append("transformBy", spec->projObj); @@ -410,25 +410,24 @@ void statsToBSON(const PlanStageStats& stats, ShardingFilterStats* spec = static_cast<ShardingFilterStats*>(stats.specific.get()); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("chunkSkips", static_cast<long long>(spec->chunkSkips)); + bob->appendNumber("chunkSkips", spec->chunkSkips); } } else if (STAGE_SKIP == stats.stageType) { SkipStats* spec = static_cast<SkipStats*>(stats.specific.get()); - bob->appendNumber("skipAmount", static_cast<long long>(spec->skip)); + bob->appendNumber("skipAmount", spec->skip); } else if (isSortStageType(stats.stageType)) { SortStats* spec = static_cast<SortStats*>(stats.specific.get()); bob->append("sortPattern", spec->sortPattern); - bob->appendNumber("memLimit", static_cast<long long>(spec->maxMemoryUsageBytes)); + bob->appendIntOrLL("memLimit", spec->maxMemoryUsageBytes); if (spec->limit > 0) { - bob->appendNumber("limitAmount", static_cast<long long>(spec->limit)); + bob->appendIntOrLL("limitAmount", spec->limit); } bob->append("type", stats.stageType == STAGE_SORT_SIMPLE ? "simple" : "default"); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("totalDataSizeSorted", - static_cast<long long>(spec->totalDataSizeBytes)); + bob->appendIntOrLL("totalDataSizeSorted", spec->totalDataSizeBytes); bob->appendBool("usedDisk", (spec->spills > 0)); } } else if (STAGE_SORT_MERGE == stats.stageType) { @@ -436,8 +435,8 @@ void statsToBSON(const PlanStageStats& stats, bob->append("sortPattern", spec->sortPattern); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("dupsTested", static_cast<long long>(spec->dupsTested)); - bob->appendNumber("dupsDropped", static_cast<long long>(spec->dupsDropped)); + bob->appendNumber("dupsTested", spec->dupsTested); + bob->appendNumber("dupsDropped", spec->dupsDropped); } } else if (STAGE_TEXT == stats.stageType) { TextStats* spec = static_cast<TextStats*>(stats.specific.get()); @@ -450,21 +449,21 @@ void statsToBSON(const PlanStageStats& stats, TextMatchStats* spec = static_cast<TextMatchStats*>(stats.specific.get()); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("docsRejected", static_cast<long long>(spec->docsRejected)); + bob->appendNumber("docsRejected", spec->docsRejected); } } else if (STAGE_TEXT_OR == stats.stageType) { TextOrStats* spec = static_cast<TextOrStats*>(stats.specific.get()); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("docsExamined", static_cast<long long>(spec->fetches)); + bob->appendNumber("docsExamined", spec->fetches); } } else if (STAGE_UPDATE == stats.stageType) { UpdateStats* spec = static_cast<UpdateStats*>(stats.specific.get()); if (verbosity >= ExplainOptions::Verbosity::kExecStats) { - bob->appendNumber("nMatched", static_cast<long long>(spec->nMatched)); - bob->appendNumber("nWouldModify", static_cast<long long>(spec->nModified)); - bob->appendNumber("nWouldUpsert", static_cast<long long>(spec->nUpserted)); + bob->appendNumber("nMatched", spec->nMatched); + bob->appendNumber("nWouldModify", spec->nModified); + bob->appendNumber("nWouldUpsert", spec->nUpserted); } } diff --git a/src/mongo/db/query/plan_explainer_sbe.cpp b/src/mongo/db/query/plan_explainer_sbe.cpp index 0f9df195196..f6cb563cb20 100644 --- a/src/mongo/db/query/plan_explainer_sbe.cpp +++ b/src/mongo/db/query/plan_explainer_sbe.cpp @@ -53,7 +53,7 @@ void statsToBSON(const QuerySolutionNode* node, } bob->append("stage", stageTypeToString(node->getType())); - bob->appendNumber("planNodeId", static_cast<long long>(node->nodeId())); + bob->appendNumber("planNodeId", static_cast<size_t>(node->nodeId())); // Display the BSON representation of the filter, if there is one. if (node->filter) { @@ -123,7 +123,7 @@ void statsToBSON(const QuerySolutionNode* node, } case STAGE_LIMIT: { auto ln = static_cast<const LimitNode*>(node); - bob->appendNumber("limitAmount", ln->limit); + bob->appendIntOrLL("limitAmount", ln->limit); break; } case STAGE_PROJECTION_DEFAULT: @@ -135,17 +135,17 @@ void statsToBSON(const QuerySolutionNode* node, } case STAGE_SKIP: { auto sn = static_cast<const SkipNode*>(node); - bob->appendNumber("skipAmount", sn->skip); + bob->appendIntOrLL("skipAmount", sn->skip); break; } case STAGE_SORT_SIMPLE: case STAGE_SORT_DEFAULT: { auto sn = static_cast<const SortNode*>(node); bob->append("sortPattern", sn->pattern); - bob->appendNumber("memLimit", static_cast<long long>(sn->maxMemoryUsageBytes)); + bob->appendIntOrLL("memLimit", sn->maxMemoryUsageBytes); if (sn->limit > 0) { - bob->appendNumber("limitAmount", static_cast<long long>(sn->limit)); + bob->appendIntOrLL("limitAmount", sn->limit); } bob->append("type", node->getType() == STAGE_SORT_SIMPLE ? "simple" : "default"); @@ -211,19 +211,19 @@ void statsToBSON(const sbe::PlanStageStats* stats, auto stageType = stats->common.stageType; bob->append("stage", stageType); - bob->appendNumber("planNodeId", static_cast<long long>(stats->common.nodeId)); + bob->appendNumber("planNodeId", static_cast<size_t>(stats->common.nodeId)); // Some top-level exec stats get pulled out of the root stage. - bob->appendNumber("nReturned", static_cast<long long>(stats->common.advances)); + bob->appendNumber("nReturned", stats->common.advances); // Include executionTimeMillis if it was recorded. if (stats->common.executionTimeMillis) { bob->appendNumber("executionTimeMillisEstimate", *stats->common.executionTimeMillis); } - bob->appendNumber("advances", static_cast<long long>(stats->common.advances)); - bob->appendNumber("opens", static_cast<long long>(stats->common.opens)); - bob->appendNumber("closes", static_cast<long long>(stats->common.closes)); - bob->appendNumber("saveState", static_cast<long long>(stats->common.yields)); - bob->appendNumber("restoreState", static_cast<long long>(stats->common.unyields)); + bob->appendNumber("advances", stats->common.advances); + bob->appendNumber("opens", stats->common.opens); + bob->appendNumber("closes", stats->common.closes); + bob->appendNumber("saveState", stats->common.yields); + bob->appendNumber("restoreState", stats->common.unyields); bob->appendNumber("isEOF", stats->common.isEOF); // Include any extra debug info if present. diff --git a/src/mongo/db/repl/all_database_cloner.cpp b/src/mongo/db/repl/all_database_cloner.cpp index 4987ef3e937..fe79124d0e3 100644 --- a/src/mongo/db/repl/all_database_cloner.cpp +++ b/src/mongo/db/repl/all_database_cloner.cpp @@ -298,8 +298,8 @@ BSONObj AllDatabaseCloner::Stats::toBSON() const { } void AllDatabaseCloner::Stats::append(BSONObjBuilder* builder) const { - builder->appendNumber("databasesToClone", static_cast<long long>(databasesToClone)); - builder->appendNumber("databasesCloned", static_cast<long long>(databasesCloned)); + builder->appendNumber("databasesToClone", databasesToClone); + builder->appendNumber("databasesCloned", databasesCloned); for (auto&& db : databaseStats) { BSONObjBuilder dbBuilder(builder->subobjStart(db.dbname)); db.append(&dbBuilder); diff --git a/src/mongo/db/repl/apply_ops_test.cpp b/src/mongo/db/repl/apply_ops_test.cpp index faf8be5e827..a61db70a0b6 100644 --- a/src/mongo/db/repl/apply_ops_test.cpp +++ b/src/mongo/db/repl/apply_ops_test.cpp @@ -130,7 +130,7 @@ Status getStatusFromApplyOpsResult(const BSONObj& result) { BSONObjBuilder builder; builder.appendElements(result); auto code = result.getIntField("code"); - builder.appendNumber("ok", code == 0); + builder.appendIntOrLL("ok", code == 0); auto newResult = builder.obj(); return getStatusFromCommandResult(newResult); } diff --git a/src/mongo/db/repl/collection_cloner.cpp b/src/mongo/db/repl/collection_cloner.cpp index 35b1ddf6d7b..9d85f779fae 100644 --- a/src/mongo/db/repl/collection_cloner.cpp +++ b/src/mongo/db/repl/collection_cloner.cpp @@ -524,10 +524,10 @@ BSONObj CollectionCloner::Stats::toBSON() const { } void CollectionCloner::Stats::append(BSONObjBuilder* builder) const { - builder->appendNumber(kDocumentsToCopyFieldName, static_cast<long long>(documentToCopy)); - builder->appendNumber(kDocumentsCopiedFieldName, static_cast<long long>(documentsCopied)); - builder->appendNumber("indexes", static_cast<long long>(indexes)); - builder->appendNumber("fetchedBatches", static_cast<long long>(fetchedBatches)); + builder->appendNumber(kDocumentsToCopyFieldName, documentToCopy); + builder->appendNumber(kDocumentsCopiedFieldName, documentsCopied); + builder->appendNumber("indexes", indexes); + builder->appendNumber("fetchedBatches", fetchedBatches); builder->appendNumber("bytesToCopy", bytesToCopy); if (bytesToCopy) { builder->appendNumber("approxBytesCopied", approxBytesCopied); @@ -541,7 +541,7 @@ void CollectionCloner::Stats::append(BSONObjBuilder* builder) const { builder->appendNumber("elapsedMillis", elapsedMillis); } } - builder->appendNumber("receivedBatches", static_cast<long long>(receivedBatches)); + builder->appendNumber("receivedBatches", receivedBatches); } } // namespace repl diff --git a/src/mongo/db/repl/database_cloner.cpp b/src/mongo/db/repl/database_cloner.cpp index e4c2772e0be..3686d5a2cb1 100644 --- a/src/mongo/db/repl/database_cloner.cpp +++ b/src/mongo/db/repl/database_cloner.cpp @@ -194,8 +194,8 @@ BSONObj DatabaseCloner::Stats::toBSON() const { } void DatabaseCloner::Stats::append(BSONObjBuilder* builder) const { - builder->appendNumber("collections", static_cast<long long>(collections)); - builder->appendNumber("clonedCollections", static_cast<long long>(clonedCollections)); + builder->appendNumber("collections", collections); + builder->appendNumber("clonedCollections", clonedCollections); if (start != Date_t()) { builder->appendDate("start", start); if (end != Date_t()) { diff --git a/src/mongo/db/repl/hello_response.cpp b/src/mongo/db/repl/hello_response.cpp index a62463cca33..89ae3426073 100644 --- a/src/mongo/db/repl/hello_response.cpp +++ b/src/mongo/db/repl/hello_response.cpp @@ -177,11 +177,11 @@ void HelloResponse::addToBSON(BSONObjBuilder* builder, bool useLegacyResponseFie builder->append(kBuildIndexesFieldName, _buildIndexes); if (_secondaryDelaySecsSet) { if (useLegacyResponseFields) { - builder->appendNumber(kSlaveDelayFieldName, - durationCount<Seconds>(_secondaryDelaySecs)); + builder->appendIntOrLL(kSlaveDelayFieldName, + durationCount<Seconds>(_secondaryDelaySecs)); } else { - builder->appendNumber(kSecondaryDelaySecsFieldName, - durationCount<Seconds>(_secondaryDelaySecs)); + builder->appendIntOrLL(kSecondaryDelaySecsFieldName, + durationCount<Seconds>(_secondaryDelaySecs)); } } if (_tagsSet) { diff --git a/src/mongo/db/repl/initial_syncer.cpp b/src/mongo/db/repl/initial_syncer.cpp index 35656252427..1a896967971 100644 --- a/src/mongo/db/repl/initial_syncer.cpp +++ b/src/mongo/db/repl/initial_syncer.cpp @@ -440,7 +440,7 @@ void InitialSyncer::_appendInitialSyncProgressMinimal_inlock(BSONObjBuilder* bob (long long)remainingInitialSyncEstimatedMillis); } } - bob->appendNumber("appliedOps", static_cast<long long>(_initialSyncState->appliedOps)); + bob->appendNumber("appliedOps", _initialSyncState->appliedOps); if (!_initialSyncState->beginApplyingTimestamp.isNull()) { bob->append("initialSyncOplogStart", _initialSyncState->beginApplyingTimestamp); } diff --git a/src/mongo/db/repl/primary_only_service.cpp b/src/mongo/db/repl/primary_only_service.cpp index ddfab769e8c..6973cbb119d 100644 --- a/src/mongo/db/repl/primary_only_service.cpp +++ b/src/mongo/db/repl/primary_only_service.cpp @@ -218,8 +218,7 @@ void PrimaryOnlyServiceRegistry::onStepDown() { void PrimaryOnlyServiceRegistry::reportServiceInfoForServerStatus(BSONObjBuilder* result) noexcept { BSONObjBuilder subBuilder(result->subobjStart("primaryOnlyServices")); for (auto& service : _servicesByName) { - subBuilder.appendNumber(service.first, - static_cast<long long>(service.second->getNumberOfInstances())); + subBuilder.appendNumber(service.first, service.second->getNumberOfInstances()); } } diff --git a/src/mongo/db/repl/repl_set_config_validators.h b/src/mongo/db/repl/repl_set_config_validators.h index c02cfb1ee15..70c01988412 100644 --- a/src/mongo/db/repl/repl_set_config_validators.h +++ b/src/mongo/db/repl/repl_set_config_validators.h @@ -71,7 +71,7 @@ Status validateReplicaSetIdNotNull(OID replicaSetId); * For serialization and deserialization of certain values in the IDL. */ inline void smallExactInt64Append(std::int64_t value, StringData fieldName, BSONObjBuilder* bob) { - bob->appendNumber(fieldName, static_cast<long long>(value)); + bob->appendIntOrLL(fieldName, value); } inline std::int64_t parseSmallExactInt64(const BSONElement& element) { diff --git a/src/mongo/db/repl/repl_set_heartbeat_args_v1.cpp b/src/mongo/db/repl/repl_set_heartbeat_args_v1.cpp index a8dfb7ec6ae..8169f1e3760 100644 --- a/src/mongo/db/repl/repl_set_heartbeat_args_v1.cpp +++ b/src/mongo/db/repl/repl_set_heartbeat_args_v1.cpp @@ -169,14 +169,14 @@ void ReplSetHeartbeatArgsV1::addToBSON(BSONObjBuilder* builder) const { if (_checkEmpty) { builder->append(kCheckEmptyFieldName, _checkEmpty); } - builder->appendNumber(kConfigVersionFieldName, _configVersion); - builder->appendNumber(kConfigTermFieldName, _configTerm); + builder->appendIntOrLL(kConfigVersionFieldName, _configVersion); + builder->appendIntOrLL(kConfigTermFieldName, _configTerm); if (_hasHeartbeatVersion) { - builder->appendNumber(kHeartbeatVersionFieldName, _hasHeartbeatVersion); + builder->appendIntOrLL(kHeartbeatVersionFieldName, _hasHeartbeatVersion); } builder->append(kSenderHostFieldName, _hasSender ? _senderHost.toString() : ""); - builder->appendNumber(kSenderIdFieldName, _senderId); - builder->appendNumber(kTermFieldName, _term); + builder->appendIntOrLL(kSenderIdFieldName, _senderId); + builder->appendIntOrLL(kTermFieldName, _term); // TODO SERVER-49382: Remove this FCV check when 5.0 becomes last-lts. if (serverGlobalParams.featureCompatibility.isVersionInitialized() && diff --git a/src/mongo/db/repl/repl_set_heartbeat_response.cpp b/src/mongo/db/repl/repl_set_heartbeat_response.cpp index ea169eae737..c77d454f00c 100644 --- a/src/mongo/db/repl/repl_set_heartbeat_response.cpp +++ b/src/mongo/db/repl/repl_set_heartbeat_response.cpp @@ -77,7 +77,7 @@ void ReplSetHeartbeatResponse::addToBSON(BSONObjBuilder* builder) const { *builder << kConfigFieldName << _config.toBSON(); } if (_stateSet) { - builder->appendNumber(kMemberStateFieldName, _state.s); + builder->appendIntOrLL(kMemberStateFieldName, _state.s); } if (_configVersion != -1) { *builder << kConfigVersionFieldName << _configVersion; diff --git a/src/mongo/db/repl/repl_set_request_votes_args.cpp b/src/mongo/db/repl/repl_set_request_votes_args.cpp index 10f815d6edc..7978b26987f 100644 --- a/src/mongo/db/repl/repl_set_request_votes_args.cpp +++ b/src/mongo/db/repl/repl_set_request_votes_args.cpp @@ -125,9 +125,9 @@ void ReplSetRequestVotesArgs::addToBSON(BSONObjBuilder* builder) const { builder->append(kSetNameFieldName, _setName); builder->append(kDryRunFieldName, _dryRun); builder->append(kTermFieldName, _term); - builder->appendNumber(kCandidateIndexFieldName, _candidateIndex); - builder->appendNumber(kConfigVersionFieldName, _cfgVer); - builder->appendNumber(kConfigTermFieldName, _cfgTerm); + builder->appendIntOrLL(kCandidateIndexFieldName, _candidateIndex); + builder->appendIntOrLL(kConfigVersionFieldName, _cfgVer); + builder->appendIntOrLL(kConfigTermFieldName, _cfgTerm); _lastAppliedOpTime.append(builder, kLastAppliedOpTimeFieldName); } diff --git a/src/mongo/db/repl/replication_info.cpp b/src/mongo/db/repl/replication_info.cpp index 18d33e220f7..ba7c3131844 100644 --- a/src/mongo/db/repl/replication_info.cpp +++ b/src/mongo/db/repl/replication_info.cpp @@ -405,10 +405,9 @@ public: } result.appendNumber(HelloCommandReply::kMaxBsonObjectSizeFieldName, BSONObjMaxUserSize); - result.appendNumber(HelloCommandReply::kMaxMessageSizeBytesFieldName, - static_cast<long long>(MaxMessageSizeBytes)); + result.appendNumber(HelloCommandReply::kMaxMessageSizeBytesFieldName, MaxMessageSizeBytes); result.appendNumber(HelloCommandReply::kMaxWriteBatchSizeFieldName, - static_cast<long long>(write_ops::kMaxWriteBatchSize)); + write_ops::kMaxWriteBatchSize); result.appendDate(HelloCommandReply::kLocalTimeFieldName, jsTime()); result.append(HelloCommandReply::kLogicalSessionTimeoutMinutesFieldName, localLogicalSessionTimeoutMinutes); diff --git a/src/mongo/db/repl/tenant_all_database_cloner.cpp b/src/mongo/db/repl/tenant_all_database_cloner.cpp index 85c580ef3b7..c60df54b868 100644 --- a/src/mongo/db/repl/tenant_all_database_cloner.cpp +++ b/src/mongo/db/repl/tenant_all_database_cloner.cpp @@ -256,7 +256,7 @@ BSONObj TenantAllDatabaseCloner::Stats::toBSON() const { } void TenantAllDatabaseCloner::Stats::append(BSONObjBuilder* builder) const { - builder->appendNumber("databasesCloned", static_cast<long long>(databasesCloned)); + builder->appendNumber("databasesCloned", databasesCloned); for (auto&& db : databaseStats) { BSONObjBuilder dbBuilder(builder->subobjStart(db.dbname)); db.append(&dbBuilder); diff --git a/src/mongo/db/repl/tenant_collection_cloner.cpp b/src/mongo/db/repl/tenant_collection_cloner.cpp index 9a724df617a..3725f3bbbba 100644 --- a/src/mongo/db/repl/tenant_collection_cloner.cpp +++ b/src/mongo/db/repl/tenant_collection_cloner.cpp @@ -549,10 +549,10 @@ BSONObj TenantCollectionCloner::Stats::toBSON() const { } void TenantCollectionCloner::Stats::append(BSONObjBuilder* builder) const { - builder->appendNumber(kDocumentsToCopyFieldName, static_cast<long long>(documentToCopy)); - builder->appendNumber(kDocumentsCopiedFieldName, static_cast<long long>(documentsCopied)); - builder->appendNumber("indexes", static_cast<long long>(indexes)); - builder->appendNumber("insertedBatches", static_cast<long long>(insertedBatches)); + builder->appendNumber(kDocumentsToCopyFieldName, documentToCopy); + builder->appendNumber(kDocumentsCopiedFieldName, documentsCopied); + builder->appendNumber("indexes", indexes); + builder->appendNumber("insertedBatches", insertedBatches); if (start != Date_t()) { builder->appendDate("start", start); if (end != Date_t()) { @@ -562,7 +562,7 @@ void TenantCollectionCloner::Stats::append(BSONObjBuilder* builder) const { builder->appendNumber("elapsedMillis", elapsedMillis); } } - builder->appendNumber("receivedBatches", static_cast<long long>(receivedBatches)); + builder->appendNumber("receivedBatches", receivedBatches); } Timestamp TenantCollectionCloner::getOperationTime_forTest() { diff --git a/src/mongo/db/repl/tenant_database_cloner.cpp b/src/mongo/db/repl/tenant_database_cloner.cpp index 81b1a7c0eec..1cc44329cb3 100644 --- a/src/mongo/db/repl/tenant_database_cloner.cpp +++ b/src/mongo/db/repl/tenant_database_cloner.cpp @@ -322,8 +322,8 @@ BSONObj TenantDatabaseCloner::Stats::toBSON() const { } void TenantDatabaseCloner::Stats::append(BSONObjBuilder* builder) const { - builder->appendNumber("collections", static_cast<long long>(collections)); - builder->appendNumber("clonedCollections", static_cast<long long>(clonedCollections)); + builder->appendNumber("collections", collections); + builder->appendNumber("clonedCollections", clonedCollections); if (start != Date_t()) { builder->appendDate("start", start); if (end != Date_t()) { diff --git a/src/mongo/db/repl/topology_coordinator.cpp b/src/mongo/db/repl/topology_coordinator.cpp index ede2650481d..e7bf9e67d2e 100644 --- a/src/mongo/db/repl/topology_coordinator.cpp +++ b/src/mongo/db/repl/topology_coordinator.cpp @@ -1872,8 +1872,8 @@ void TopologyCoordinator::prepareStatusResponse(const ReplSetStatusArgs& rsStatu bb.appendDate("electionDate", Date_t::fromDurationSinceEpoch(Seconds(_electionTime.getSecs()))); } - bb.appendNumber("configVersion", static_cast<long long>(_rsConfig.getConfigVersion())); - bb.appendNumber("configTerm", static_cast<long long>(_rsConfig.getConfigTerm())); + bb.appendIntOrLL("configVersion", _rsConfig.getConfigVersion()); + bb.appendIntOrLL("configTerm", _rsConfig.getConfigTerm()); bb.append("self", true); bb.append("lastHeartbeatMessage", ""); membersOut.push_back(bb.obj()); @@ -1935,8 +1935,8 @@ void TopologyCoordinator::prepareStatusResponse(const ReplSetStatusArgs& rsStatu "electionDate", Date_t::fromDurationSinceEpoch(Seconds(it->getElectionTime().getSecs()))); } - bb.appendNumber("configVersion", it->getConfigVersion()); - bb.appendNumber("configTerm", it->getConfigTerm()); + bb.appendIntOrLL("configVersion", it->getConfigVersion()); + bb.appendIntOrLL("configTerm", it->getConfigTerm()); membersOut.push_back(bb.obj()); } } diff --git a/src/mongo/db/storage/devnull/ephemeral_catalog_record_store.cpp b/src/mongo/db/storage/devnull/ephemeral_catalog_record_store.cpp index f39c325863d..704394515d6 100644 --- a/src/mongo/db/storage/devnull/ephemeral_catalog_record_store.cpp +++ b/src/mongo/db/storage/devnull/ephemeral_catalog_record_store.cpp @@ -558,8 +558,8 @@ void EphemeralForTestRecordStore::appendCustomStats(OperationContext* opCtx, double scale) const { result->appendBool("capped", _isCapped); if (_isCapped) { - result->appendNumber("max", static_cast<long long>(_cappedMaxDocs)); - result->appendNumber("maxSize", _cappedMaxSize / scale); + result->appendIntOrLL("max", _cappedMaxDocs); + result->appendIntOrLL("maxSize", _cappedMaxSize / scale); } } diff --git a/src/mongo/db/storage/ephemeral_for_test/ephemeral_for_test_record_store.cpp b/src/mongo/db/storage/ephemeral_for_test/ephemeral_for_test_record_store.cpp index a58e83c90e8..c8360651df7 100644 --- a/src/mongo/db/storage/ephemeral_for_test/ephemeral_for_test_record_store.cpp +++ b/src/mongo/db/storage/ephemeral_for_test/ephemeral_for_test_record_store.cpp @@ -290,8 +290,8 @@ void RecordStore::appendCustomStats(OperationContext* opCtx, double scale) const { result->appendBool("capped", _isCapped); if (_isCapped) { - result->appendNumber("max", static_cast<long long>(_cappedMaxDocs)); - result->appendNumber("maxSize", _cappedMaxSize / scale); + result->appendIntOrLL("max", _cappedMaxDocs); + result->appendIntOrLL("maxSize", _cappedMaxSize / scale); } } diff --git a/src/mongo/db/storage/wiredtiger/wiredtiger_record_store.cpp b/src/mongo/db/storage/wiredtiger/wiredtiger_record_store.cpp index 4785eda902f..71ea46ded3f 100644 --- a/src/mongo/db/storage/wiredtiger/wiredtiger_record_store.cpp +++ b/src/mongo/db/storage/wiredtiger/wiredtiger_record_store.cpp @@ -1946,10 +1946,10 @@ void WiredTigerRecordStore::appendCustomStats(OperationContext* opCtx, double scale) const { result->appendBool("capped", _isCapped); if (_isCapped) { - result->appendNumber("max", static_cast<long long>(_cappedMaxDocs)); - result->appendNumber("maxSize", static_cast<long long>(_cappedMaxSize / scale)); - result->appendNumber("sleepCount", _cappedSleep.load()); - result->appendNumber("sleepMS", _cappedSleepMS.load()); + result->appendIntOrLL("max", _cappedMaxDocs); + result->appendIntOrLL("maxSize", static_cast<long long>(_cappedMaxSize / scale)); + result->appendIntOrLL("sleepCount", _cappedSleep.load()); + result->appendIntOrLL("sleepMS", _cappedSleepMS.load()); } WiredTigerSession* session = WiredTigerRecoveryUnit::get(opCtx)->getSessionNoTxn(); WT_SESSION* s = session->getSession(); diff --git a/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp b/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp index 2d0b7998e5d..c5c1ced6c79 100644 --- a/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp +++ b/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp @@ -303,7 +303,7 @@ Status WiredTigerUtil::getApplicationMetadata(OperationContext* opCtx, bob->appendBool(key, valueItem.val); break; case WT_CONFIG_ITEM::WT_CONFIG_ITEM_NUM: - bob->appendNumber(key, static_cast<long long>(valueItem.val)); + bob->appendIntOrLL(key, valueItem.val); break; default: bob->append(key, StringData(valueItem.str, valueItem.len)); diff --git a/src/mongo/db/timeseries/bucket_catalog.cpp b/src/mongo/db/timeseries/bucket_catalog.cpp index 173973109ff..9be99db0702 100644 --- a/src/mongo/db/timeseries/bucket_catalog.cpp +++ b/src/mongo/db/timeseries/bucket_catalog.cpp @@ -978,11 +978,9 @@ public: } BSONObjBuilder builder; - builder.appendNumber("numBuckets", static_cast<long long>(bucketCatalog._buckets.size())); - builder.appendNumber("numOpenBuckets", - static_cast<long long>(bucketCatalog._bucketIds.size())); - builder.appendNumber("numIdleBuckets", - static_cast<long long>(bucketCatalog._numberOfIdleBuckets())); + builder.appendNumber("numBuckets", bucketCatalog._buckets.size()); + builder.appendNumber("numOpenBuckets", bucketCatalog._bucketIds.size()); + builder.appendNumber("numIdleBuckets", bucketCatalog._numberOfIdleBuckets()); builder.appendNumber("memoryUsage", static_cast<long long>(bucketCatalog._memoryUsage.load())); return builder.obj(); diff --git a/src/mongo/dbtests/jsobjtests.cpp b/src/mongo/dbtests/jsobjtests.cpp index 99f984e0c87..c3e754b8771 100644 --- a/src/mongo/dbtests/jsobjtests.cpp +++ b/src/mongo/dbtests/jsobjtests.cpp @@ -561,6 +561,49 @@ public: } }; +struct AppendIntOrLL { + void run() { + const long long billion = 1000 * 1000 * 1000; + + BSONObjBuilder b; + b.appendIntOrLL("i1", 1); + b.appendIntOrLL("i2", -1); + b.appendIntOrLL("i3", 1 * billion); + b.appendIntOrLL("i4", -1 * billion); + + b.appendIntOrLL("L1", 2 * billion); + b.appendIntOrLL("L2", -2 * billion); + b.appendIntOrLL("L3", 4 * billion); + b.appendIntOrLL("L4", -4 * billion); + b.appendIntOrLL("L5", 16 * billion); + b.appendIntOrLL("L6", -16 * billion); + + BSONObj o = b.obj(); + + ASSERT(o["i1"].type() == NumberInt); + ASSERT(o["i1"].number() == 1); + ASSERT(o["i2"].type() == NumberInt); + ASSERT(o["i2"].number() == -1); + ASSERT(o["i3"].type() == NumberInt); + ASSERT(o["i3"].number() == 1 * billion); + ASSERT(o["i4"].type() == NumberInt); + ASSERT(o["i4"].number() == -1 * billion); + + ASSERT(o["L1"].isNumber()); + ASSERT(o["L1"].number() == 2 * billion); + ASSERT(o["L2"].isNumber()); + ASSERT(o["L2"].number() == -2 * billion); + ASSERT(o["L3"].type() == NumberLong); + ASSERT(o["L3"].number() == 4 * billion); + ASSERT(o["L4"].type() == NumberLong); + ASSERT(o["L4"].number() == -4 * billion); + ASSERT(o["L5"].type() == NumberLong); + ASSERT(o["L5"].number() == 16 * billion); + ASSERT(o["L6"].type() == NumberLong); + ASSERT(o["L6"].number() == -16 * billion); + } +}; + struct AppendNumber { void run() { BSONObjBuilder b; @@ -576,7 +619,7 @@ struct AppendNumber { ASSERT(o["a"].type() == NumberInt); ASSERT(o["b"].type() == NumberDouble); ASSERT(o["c"].type() == NumberInt); - ASSERT(o["d"].type() == NumberLong); + ASSERT(o["d"].type() == NumberDouble); ASSERT(o["e"].type() == NumberLong); ASSERT(o["f"].type() == NumberDecimal); } @@ -1965,6 +2008,7 @@ public: add<BSONObjTests::MultiKeySortOrder>(); add<BSONObjTests::Nan>(); add<BSONObjTests::AsTempObj>(); + add<BSONObjTests::AppendIntOrLL>(); add<BSONObjTests::AppendNumber>(); add<BSONObjTests::ToStringNumber>(); add<BSONObjTests::AppendAs>(); diff --git a/src/mongo/dbtests/mock/mock_replica_set.cpp b/src/mongo/dbtests/mock/mock_replica_set.cpp index 358c880de45..53fd2d0a8cd 100644 --- a/src/mongo/dbtests/mock/mock_replica_set.cpp +++ b/src/mongo/dbtests/mock/mock_replica_set.cpp @@ -249,8 +249,8 @@ void MockReplicaSet::mockIsMasterCmd() { } if (member->getSecondaryDelay().count()) { - builder.appendNumber("secondaryDelaySecs", - durationCount<Seconds>(member->getSecondaryDelay())); + builder.appendIntOrLL("secondaryDelaySecs", + durationCount<Seconds>(member->getSecondaryDelay())); } if (member->isHidden()) { diff --git a/src/mongo/embedded/embedded_ismaster.cpp b/src/mongo/embedded/embedded_ismaster.cpp index 35568085720..94f1a557ee1 100644 --- a/src/mongo/embedded/embedded_ismaster.cpp +++ b/src/mongo/embedded/embedded_ismaster.cpp @@ -76,9 +76,8 @@ public: result.appendBool("ismaster", true); result.appendNumber("maxBsonObjectSize", BSONObjMaxUserSize); - result.appendNumber("maxMessageSizeBytes", static_cast<long long>(MaxMessageSizeBytes)); - result.appendNumber("maxWriteBatchSize", - static_cast<long long>(write_ops::kMaxWriteBatchSize)); + result.appendNumber("maxMessageSizeBytes", MaxMessageSizeBytes); + result.appendNumber("maxWriteBatchSize", write_ops::kMaxWriteBatchSize); result.appendDate("localTime", jsTime()); result.append("logicalSessionTimeoutMinutes", localLogicalSessionTimeoutMinutes); result.appendNumber("connectionId", opCtx->getClient()->getConnectionId()); diff --git a/src/mongo/executor/connection_pool_stats.cpp b/src/mongo/executor/connection_pool_stats.cpp index 843a19a1a27..06694697113 100644 --- a/src/mongo/executor/connection_pool_stats.cpp +++ b/src/mongo/executor/connection_pool_stats.cpp @@ -77,21 +77,20 @@ void ConnectionPoolStats::updateStatsForHost(std::string pool, } void ConnectionPoolStats::appendToBSON(mongo::BSONObjBuilder& result, bool forFTDC) { - result.appendNumber("totalInUse", static_cast<long long>(totalInUse)); - result.appendNumber("totalAvailable", static_cast<long long>(totalAvailable)); - result.appendNumber("totalCreated", static_cast<long long>(totalCreated)); - result.appendNumber("totalRefreshing", static_cast<long long>(totalRefreshing)); + result.appendNumber("totalInUse", totalInUse); + result.appendNumber("totalAvailable", totalAvailable); + result.appendNumber("totalCreated", totalCreated); + result.appendNumber("totalRefreshing", totalRefreshing); if (forFTDC) { BSONObjBuilder poolBuilder(result.subobjStart("connectionsInUsePerPool")); for (const auto& pool : statsByPool) { BSONObjBuilder poolInfo(poolBuilder.subobjStart(pool.first)); auto& poolStats = pool.second; - poolInfo.appendNumber("poolInUse", static_cast<long long>(poolStats.inUse)); + poolInfo.appendNumber("poolInUse", poolStats.inUse); for (const auto& host : poolStats.statsByHost) { auto hostStats = host.second; - poolInfo.appendNumber(host.first.toString(), - static_cast<long long>(hostStats.inUse)); + poolInfo.appendNumber(host.first.toString(), hostStats.inUse); } } @@ -107,18 +106,18 @@ void ConnectionPoolStats::appendToBSON(mongo::BSONObjBuilder& result, bool forFT for (const auto& pool : statsByPool) { BSONObjBuilder poolInfo(poolBuilder.subobjStart(pool.first)); auto& poolStats = pool.second; - poolInfo.appendNumber("poolInUse", static_cast<long long>(poolStats.inUse)); - poolInfo.appendNumber("poolAvailable", static_cast<long long>(poolStats.available)); - poolInfo.appendNumber("poolCreated", static_cast<long long>(poolStats.created)); - poolInfo.appendNumber("poolRefreshing", static_cast<long long>(poolStats.refreshing)); + poolInfo.appendNumber("poolInUse", poolStats.inUse); + poolInfo.appendNumber("poolAvailable", poolStats.available); + poolInfo.appendNumber("poolCreated", poolStats.created); + poolInfo.appendNumber("poolRefreshing", poolStats.refreshing); for (const auto& host : poolStats.statsByHost) { BSONObjBuilder hostInfo(poolInfo.subobjStart(host.first.toString())); auto& hostStats = host.second; - hostInfo.appendNumber("inUse", static_cast<long long>(hostStats.inUse)); - hostInfo.appendNumber("available", static_cast<long long>(hostStats.available)); - hostInfo.appendNumber("created", static_cast<long long>(hostStats.created)); - hostInfo.appendNumber("refreshing", static_cast<long long>(hostStats.refreshing)); + hostInfo.appendNumber("inUse", hostStats.inUse); + hostInfo.appendNumber("available", hostStats.available); + hostInfo.appendNumber("created", hostStats.created); + hostInfo.appendNumber("refreshing", hostStats.refreshing); } } } @@ -127,10 +126,10 @@ void ConnectionPoolStats::appendToBSON(mongo::BSONObjBuilder& result, bool forFT for (auto&& host : statsByHost) { BSONObjBuilder hostInfo(hostBuilder.subobjStart(host.first.toString())); auto hostStats = host.second; - hostInfo.appendNumber("inUse", static_cast<long long>(hostStats.inUse)); - hostInfo.appendNumber("available", static_cast<long long>(hostStats.available)); - hostInfo.appendNumber("created", static_cast<long long>(hostStats.created)); - hostInfo.appendNumber("refreshing", static_cast<long long>(hostStats.refreshing)); + hostInfo.appendNumber("inUse", hostStats.inUse); + hostInfo.appendNumber("available", hostStats.available); + hostInfo.appendNumber("created", hostStats.created); + hostInfo.appendNumber("refreshing", hostStats.refreshing); } } } diff --git a/src/mongo/executor/thread_pool_task_executor.cpp b/src/mongo/executor/thread_pool_task_executor.cpp index d1787313d76..f81ebd7c9ad 100644 --- a/src/mongo/executor/thread_pool_task_executor.cpp +++ b/src/mongo/executor/thread_pool_task_executor.cpp @@ -252,18 +252,16 @@ void ThreadPoolTaskExecutor::appendDiagnosticBSON(BSONObjBuilder* b) const { // ThreadPool details // TODO: fill in BSONObjBuilder poolCounters(b->subobjStart("pool")); - poolCounters.appendNumber("inProgressCount", - static_cast<long long>(_poolInProgressQueue.size())); + poolCounters.appendIntOrLL("inProgressCount", _poolInProgressQueue.size()); poolCounters.done(); // Queues BSONObjBuilder queues(b->subobjStart("queues")); - queues.appendNumber("networkInProgress", - static_cast<long long>(_networkInProgressQueue.size())); - queues.appendNumber("sleepers", static_cast<long long>(_sleepersQueue.size())); + queues.appendIntOrLL("networkInProgress", _networkInProgressQueue.size()); + queues.appendIntOrLL("sleepers", _sleepersQueue.size()); queues.done(); - b->appendNumber("unsignaledEvents", static_cast<long long>(_unsignaledEvents.size())); + b->appendIntOrLL("unsignaledEvents", _unsignaledEvents.size()); b->append("shuttingDown", _inShutdown_inlock()); b->append("networkInterface", _net->getDiagnosticString()); } diff --git a/src/mongo/idl/basic_types.h b/src/mongo/idl/basic_types.h index 35516add195..1df3606aecd 100644 --- a/src/mongo/idl/basic_types.h +++ b/src/mongo/idl/basic_types.h @@ -179,7 +179,7 @@ public: } auto intVal = stdx::get_if<std::int64_t>(&_w); invariant(intVal); - builder->appendNumber("w", static_cast<long long>(*intVal)); + builder->appendIntOrLL("w", *intVal); } WriteConcernW() : _w{1}, _usedDefault{true} {}; diff --git a/src/mongo/platform/mutex.cpp b/src/mongo/platform/mutex.cpp index 8766b3dc20b..eb2501000c2 100644 --- a/src/mongo/platform/mutex.cpp +++ b/src/mongo/platform/mutex.cpp @@ -38,7 +38,7 @@ void Identity::serialize(BSONObjBuilder* bob) const { bob->append("name"_sd, name()); size_t id = index(); - bob->appendNumber("latchId"_sd, static_cast<long long>(id)); + bob->appendNumber("latchId"_sd, id); auto& hal = level(); invariant(hal); @@ -48,7 +48,7 @@ void Identity::serialize(BSONObjBuilder* bob) const { invariant(loc); size_t line = loc->line(); bob->append("file"_sd, loc->file_name()); - bob->appendNumber("line"_sd, static_cast<long long>(line)); + bob->appendNumber("line"_sd, line); } Mutex::Mutex(std::shared_ptr<Data> data) : _data{std::move(data)} { diff --git a/src/mongo/rpc/op_msg_integration_test.cpp b/src/mongo/rpc/op_msg_integration_test.cpp index 75bd7fa4e65..9228220d88b 100644 --- a/src/mongo/rpc/op_msg_integration_test.cpp +++ b/src/mongo/rpc/op_msg_integration_test.cpp @@ -133,7 +133,7 @@ TEST(OpMsg, DocumentSequenceLargeDocumentMultiInsertWorks) { OpMsgBuilder::DocSequenceBuilder sequenceBuilder = msgBuilder.beginDocSequence("documents"); for (size_t docID = 0; docID < 3; docID++) { BSONObjBuilder docBuilder = sequenceBuilder.appendBuilder(); - docBuilder.appendNumber("_id", static_cast<long long>(docID)); + docBuilder.appendNumber("_id", docID); std::string data(15000000, 'a'); docBuilder.append("data", std::move(data)); } diff --git a/src/mongo/rpc/reply_builder_test.cpp b/src/mongo/rpc/reply_builder_test.cpp index 63bfbf47386..3b472bab4f0 100644 --- a/src/mongo/rpc/reply_builder_test.cpp +++ b/src/mongo/rpc/reply_builder_test.cpp @@ -101,7 +101,7 @@ BSONObj buildCommand() { << "Bar")); a.done(); - cursorBuilder.appendNumber("id", 1); + cursorBuilder.appendIntOrLL("id", 1); cursorBuilder.append("ns", "test.$cmd.blah"); commandReplyBob.append("cursor", cursorBuilder.done()); return commandReplyBob.obj(); diff --git a/src/mongo/s/commands/cluster_hello_cmd.cpp b/src/mongo/s/commands/cluster_hello_cmd.cpp index b5a6b3903d8..69040ef342d 100644 --- a/src/mongo/s/commands/cluster_hello_cmd.cpp +++ b/src/mongo/s/commands/cluster_hello_cmd.cpp @@ -172,10 +172,9 @@ public: } result.appendNumber(HelloCommandReply::kMaxBsonObjectSizeFieldName, BSONObjMaxUserSize); - result.appendNumber(HelloCommandReply::kMaxMessageSizeBytesFieldName, - static_cast<long long>(MaxMessageSizeBytes)); + result.appendNumber(HelloCommandReply::kMaxMessageSizeBytesFieldName, MaxMessageSizeBytes); result.appendNumber(HelloCommandReply::kMaxWriteBatchSizeFieldName, - static_cast<long long>(write_ops::kMaxWriteBatchSize)); + write_ops::kMaxWriteBatchSize); result.appendDate(HelloCommandReply::kLocalTimeFieldName, jsTime()); result.append(HelloCommandReply::kLogicalSessionTimeoutMinutesFieldName, localLogicalSessionTimeoutMinutes); diff --git a/src/mongo/s/query/cluster_cursor_manager.cpp b/src/mongo/s/query/cluster_cursor_manager.cpp index d5744416e46..9ebc8c45e38 100644 --- a/src/mongo/s/query/cluster_cursor_manager.cpp +++ b/src/mongo/s/query/cluster_cursor_manager.cpp @@ -818,12 +818,12 @@ BSONObj ClusterCursorManager::dumpNssToContainerMap() const { BSONObjBuilder nssToContainer(bob.subobjStart("nssToContainer")); for (auto&& [nss, cursorContainer] : _namespaceToContainerMap) { BSONObjBuilder nssBob(nssToContainer.subobjStart(nss.toString())); - nssBob.appendNumber("containerPrefix", - static_cast<long long>(cursorContainer.containerPrefix)); + nssBob.appendIntOrLL("containerPrefix", + static_cast<int64_t>(cursorContainer.containerPrefix)); BSONArrayBuilder cursors(nssBob.subarrayStart("cursors")); for (auto&& [cursorId, cursorEntry] : cursorContainer.entryMap) { BSONObjBuilder cursorBob(cursors.subobjStart()); - cursorBob.appendNumber("id", cursorId); + cursorBob.appendIntOrLL("id", cursorId); cursorBob.append("lastActive", cursorEntry.getLastActive()); } } @@ -839,7 +839,7 @@ BSONObj ClusterCursorManager::dumpCursorIdToNssMap() const { BSONArrayBuilder cursorIdPrefixToNss(bob.subarrayStart("cursorIdPrefixToNss")); for (auto&& [cursorIdPrefix, nss] : _cursorIdPrefixToNamespaceMap) { BSONObjBuilder bob(cursorIdPrefixToNss.subobjStart()); - bob.appendNumber("cursorIdPrefix", static_cast<long long>(cursorIdPrefix)); + bob.appendIntOrLL("cursorIdPrefix", static_cast<int64_t>(cursorIdPrefix)); bob.append("nss", nss.toString()); } } @@ -857,7 +857,7 @@ BSONObj ClusterCursorManager::dumpInternalLog() const { BSONObjBuilder bob(logBuilder.subobjStart()); const auto& logEntry = _log.events[i]; if (logEntry.cursorId) { - bob.appendNumber("cursorId", *logEntry.cursorId); + bob.appendIntOrLL("cursorId", *logEntry.cursorId); } bob.append("type", LogEvent::typeToString(logEntry.type)); diff --git a/src/mongo/unittest/unittest.cpp b/src/mongo/unittest/unittest.cpp index b7b8b5201b0..df6cca3383a 100644 --- a/src/mongo/unittest/unittest.cpp +++ b/src/mongo/unittest/unittest.cpp @@ -119,7 +119,7 @@ public: BSONObjBuilder bob; bob.append("name", _name); bob.append("tests", _tests); - bob.appendNumber("fails", static_cast<long long>(_fails.size())); + bob.appendNumber("fails", _fails.size()); bob.append("asserts", _asserts); bob.append("time", Milliseconds(_millis).toBSON()); { diff --git a/src/mongo/util/heap_profiler.cpp b/src/mongo/util/heap_profiler.cpp index 74b3902fc42..7c39be5e84d 100644 --- a/src/mongo/util/heap_profiler.cpp +++ b/src/mongo/util/heap_profiler.cpp @@ -586,12 +586,11 @@ private: // Stats subsection. BSONObjBuilder statsBuilder(builder.subobjStart("stats")); - statsBuilder.appendNumber("totalActiveBytes", static_cast<long long>(totalActiveBytes)); - statsBuilder.appendNumber("bytesAllocated", static_cast<long long>(bytesAllocated)); - statsBuilder.appendNumber("numStacks", static_cast<long long>(stackHashTable.size())); - statsBuilder.appendNumber("currentObjEntries", static_cast<long long>(objHashTable.size())); - statsBuilder.appendNumber("maxObjEntriesUsed", - static_cast<long long>(objHashTable.maxSizeSeen())); + statsBuilder.appendNumber("totalActiveBytes", totalActiveBytes); + statsBuilder.appendNumber("bytesAllocated", bytesAllocated); + statsBuilder.appendNumber("numStacks", stackHashTable.size()); + statsBuilder.appendNumber("currentObjEntries", objHashTable.size()); + statsBuilder.appendNumber("maxObjEntriesUsed", objHashTable.maxSizeSeen()); statsBuilder.doneFast(); // Guard against races updating the StackInfo bson representation. @@ -636,8 +635,7 @@ private: std::ostringstream shortName; shortName << "stack" << stackInfo->stackNum; BSONObjBuilder stackBuilder(stacksBuilder.subobjStart(shortName.str())); - stackBuilder.appendNumber("activeBytes", - static_cast<long long>(stackInfo->activeBytes)); + stackBuilder.appendNumber("activeBytes", stackInfo->activeBytes); } stacksBuilder.doneFast(); diff --git a/src/mongo/util/tcmalloc_server_status_section.cpp b/src/mongo/util/tcmalloc_server_status_section.cpp index 5e789289c35..63fa8228ec2 100644 --- a/src/mongo/util/tcmalloc_server_status_section.cpp +++ b/src/mongo/util/tcmalloc_server_status_section.cpp @@ -114,8 +114,7 @@ public: "tcmalloc.transfer_cache_free_bytes", &transfer) && MallocExtension::instance()->GetNumericProperty("tcmalloc.thread_cache_free_bytes", &thread)) { - sub.appendNumber("total_free_bytes", - static_cast<long long>(central + transfer + thread)); + sub.appendNumber("total_free_bytes", central + transfer + thread); } appendNumericPropertyIfAvailable( sub, "central_cache_free_bytes", "tcmalloc.central_cache_free_bytes"); @@ -178,7 +177,7 @@ private: const char* property) { size_t value; if (MallocExtension::instance()->GetNumericProperty(property, &value)) - builder.appendNumber(bsonName, static_cast<long long>(value)); + builder.appendNumber(bsonName, value); } #if MONGO_HAVE_GPERFTOOLS_SIZE_CLASS_STATS @@ -188,14 +187,14 @@ private: ->first; BSONObjBuilder doc; - doc.appendNumber("bytes_per_object", static_cast<long long>(stats->bytes_per_obj)); - doc.appendNumber("pages_per_span", static_cast<long long>(stats->pages_per_span)); - doc.appendNumber("num_spans", static_cast<long long>(stats->num_spans)); - doc.appendNumber("num_thread_objs", static_cast<long long>(stats->num_thread_objs)); - doc.appendNumber("num_central_objs", static_cast<long long>(stats->num_central_objs)); - doc.appendNumber("num_transfer_objs", static_cast<long long>(stats->num_transfer_objs)); - doc.appendNumber("free_bytes", static_cast<long long>(stats->free_bytes)); - doc.appendNumber("allocated_bytes", static_cast<long long>(stats->alloc_bytes)); + doc.appendNumber("bytes_per_object", stats->bytes_per_obj); + doc.appendNumber("pages_per_span", stats->pages_per_span); + doc.appendNumber("num_spans", stats->num_spans); + doc.appendNumber("num_thread_objs", stats->num_thread_objs); + doc.appendNumber("num_central_objs", stats->num_central_objs); + doc.appendNumber("num_transfer_objs", stats->num_transfer_objs); + doc.appendNumber("free_bytes", stats->free_bytes); + doc.appendNumber("allocated_bytes", stats->alloc_bytes); builder.append(doc.obj()); } @@ -206,11 +205,11 @@ private: ->second; BSONObjBuilder doc; - doc.appendNumber("pages", static_cast<long long>(stats->pages)); - doc.appendNumber("normal_spans", static_cast<long long>(stats->normal_spans)); - doc.appendNumber("unmapped_spans", static_cast<long long>(stats->unmapped_spans)); - doc.appendNumber("normal_bytes", static_cast<long long>(stats->normal_bytes)); - doc.appendNumber("unmapped_bytes", static_cast<long long>(stats->unmapped_bytes)); + doc.appendNumber("pages", stats->pages); + doc.appendNumber("normal_spans", stats->normal_spans); + doc.appendNumber("unmapped_spans", stats->unmapped_spans); + doc.appendNumber("normal_bytes", stats->normal_bytes); + doc.appendNumber("unmapped_bytes", stats->unmapped_bytes); builder.append(doc.obj()); } diff --git a/src/mongo/util/tcmalloc_set_parameter.cpp b/src/mongo/util/tcmalloc_set_parameter.cpp index 3bf03f9e19f..d8ab1f3939f 100644 --- a/src/mongo/util/tcmalloc_set_parameter.cpp +++ b/src/mongo/util/tcmalloc_set_parameter.cpp @@ -98,7 +98,7 @@ StatusWith<size_t> validateTCMallocValue(StringData name, const BSONElement& new OperationContext*, BSONObjBuilder& b, const std::string& name) { \ auto swValue = getProperty(k##cls##PropertyName); \ if (swValue.isOK()) { \ - b.appendNumber(name, static_cast<long long>(swValue.getValue())); \ + b.appendNumber(name, swValue.getValue()); \ } \ } \ Status TCMalloc##cls##ServerParameter::set(const BSONElement& newValueElement) { \ |