/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * . * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/util/itoa.h" #include #include #include "mongo/base/string_data.h" #include "mongo/platform/bits.h" #include "mongo/util/assert_util.h" #include "mongo/util/itoa_table_4.h" // Generated by generate_itoa_table.py namespace mongo { namespace { constexpr std::size_t kTableDigits = 4; constexpr std::size_t pow10(std::size_t n) { return n ? 10 * pow10(n - 1) : 1; } constexpr std::size_t kTableSize = pow10(kTableDigits); // Cheesing gTable initializer out to Python and CPP due to compiler-imposed constexpr // complexity restrictions (clang, msvc). C'est la vie. See `generate_itoa_table.py`. constexpr struct { std::uint8_t n; char s[kTableDigits]; } gTable[] = { #define EXPAND_PACK_(...) __VA_ARGS__ #define MAKE_ENTRY_(n, digitPack) \ { n, EXPAND_PACK_ digitPack } #define COMMA_ , ITOA_TABLE_EXPAND_4(MAKE_ENTRY_, COMMA_) #undef COMMA_ #undef MAKE_ENTRY_ #undef EXPAND_PACK_ }; static_assert(std::extent_v == kTableSize, "gTable has correct size."); } // namespace ItoA::ItoA(std::uint64_t val) { if (val < kTableSize) { const auto& e = gTable[val]; std::size_t n = e.n; _str = StringData(std::end(e.s) - n, n); return; } char* p = std::end(_buf); while (val >= kTableSize) { std::size_t idx = val % kTableSize; val /= kTableSize; const auto& e = gTable[idx]; p -= kTableDigits; memcpy(p, std::end(e.s) - kTableDigits, kTableDigits); } const auto& e = gTable[val]; auto n = e.n; p -= n; memcpy(p, std::end(e.s) - n, n); _str = StringData(p, std::end(_buf) - p); } } // namespace mongo