// Copyright 2022 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_BASE_STRING_FORMAT_H_ #define V8_BASE_STRING_FORMAT_H_ #include <array> #include <limits> #include <string_view> #include <tuple> #include "src/base/logging.h" #include "src/base/platform/platform.h" namespace v8::base { // Implementation detail, do not use outside this header. The public interface // is below. namespace impl { template <const std::string_view&... strs> struct JoinedStringViews { … }; template <typename T> struct FormattedStringPart { … }; template <> struct FormattedStringPart<int> { … }; template <> struct FormattedStringPart<size_t> { … }; FormattedStringPart<char[N]>; template <const std::string_view& kFormat, int kMaxLen, typename... Parts> std::array<char, kMaxLen> PrintFormattedStringToArray(Parts... parts) { … } } // namespace impl // `FormattedString` allows to format strings with statically known number and // type of constituents. // The class stores all values that should be printed, and generates the final // string via `SNPrintF` into a `std::array`, without any dynamic memory // allocation. The format string is computed statically. // This makes this class not only very performant, but also suitable for // situations where we do not want to perform any memory allocation (like for // reporting OOM or fatal errors). // // Use like this: // auto message = FormattedString{} << "Cannot allocate " << size << " bytes"; // V8::FatalProcessOutOfMemory(nullptr, message.PrintToArray().data()); // // This code is compiled into the equivalent of // std::array<char, 34> message_arr; // int chars = SNPrintF(message_arr.data(), 34, "%s%d%s", "Cannot allocate ", // size, " bytes"); // CHECK(chars >= 0 && chars < 34); // V8::FatalProcessOutOfMemory(nullptr, message_arr.data()); template <typename... Ts> class FormattedString { … }; // Add an explicit deduction guide for empty template parameters (fixes // clang's -Wctad-maybe-unsupported warning). Non-empty formatted strings // explicitly declare template parameters anyway. <deduction guide for FormattedString>(); } // namespace v8::base #endif // V8_BASE_STRING_FORMAT_H_