str_format.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. //
  2. // Copyright 2018 The Abseil Authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. // -----------------------------------------------------------------------------
  17. // File: str_format.h
  18. // -----------------------------------------------------------------------------
  19. //
  20. // The `str_format` library is a typesafe replacement for the family of
  21. // `printf()` string formatting routines within the `<cstdio>` standard library
  22. // header. Like the `printf` family, `str_format` uses a "format string" to
  23. // perform argument substitutions based on types. See the `FormatSpec` section
  24. // below for format string documentation.
  25. //
  26. // Example:
  27. //
  28. // TString s = y_absl::StrFormat(
  29. // "%s %s You have $%d!", "Hello", name, dollars);
  30. //
  31. // The library consists of the following basic utilities:
  32. //
  33. // * `y_absl::StrFormat()`, a type-safe replacement for `std::sprintf()`, to
  34. // write a format string to a `string` value.
  35. // * `y_absl::StrAppendFormat()` to append a format string to a `string`
  36. // * `y_absl::StreamFormat()` to more efficiently write a format string to a
  37. // stream, such as`std::cout`.
  38. // * `y_absl::PrintF()`, `y_absl::FPrintF()` and `y_absl::SNPrintF()` as
  39. // drop-in replacements for `std::printf()`, `std::fprintf()` and
  40. // `std::snprintf()`.
  41. //
  42. // Note: An `y_absl::SPrintF()` drop-in replacement is not supported as it
  43. // is generally unsafe due to buffer overflows. Use `y_absl::StrFormat` which
  44. // returns the string as output instead of expecting a pre-allocated buffer.
  45. //
  46. // Additionally, you can provide a format string (and its associated arguments)
  47. // using one of the following abstractions:
  48. //
  49. // * A `FormatSpec` class template fully encapsulates a format string and its
  50. // type arguments and is usually provided to `str_format` functions as a
  51. // variadic argument of type `FormatSpec<Arg...>`. The `FormatSpec<Args...>`
  52. // template is evaluated at compile-time, providing type safety.
  53. // * A `ParsedFormat` instance, which encapsulates a specific, pre-compiled
  54. // format string for a specific set of type(s), and which can be passed
  55. // between API boundaries. (The `FormatSpec` type should not be used
  56. // directly except as an argument type for wrapper functions.)
  57. //
  58. // The `str_format` library provides the ability to output its format strings to
  59. // arbitrary sink types:
  60. //
  61. // * A generic `Format()` function to write outputs to arbitrary sink types,
  62. // which must implement a `FormatRawSink` interface.
  63. //
  64. // * A `FormatUntyped()` function that is similar to `Format()` except it is
  65. // loosely typed. `FormatUntyped()` is not a template and does not perform
  66. // any compile-time checking of the format string; instead, it returns a
  67. // boolean from a runtime check.
  68. //
  69. // In addition, the `str_format` library provides extension points for
  70. // augmenting formatting to new types. See "StrFormat Extensions" below.
  71. #ifndef Y_ABSL_STRINGS_STR_FORMAT_H_
  72. #define Y_ABSL_STRINGS_STR_FORMAT_H_
  73. #include <cstdint>
  74. #include <cstdio>
  75. #include <util/generic/string.h>
  76. #include <type_traits>
  77. #include "y_absl/base/attributes.h"
  78. #include "y_absl/base/config.h"
  79. #include "y_absl/base/nullability.h"
  80. #include "y_absl/strings/internal/str_format/arg.h" // IWYU pragma: export
  81. #include "y_absl/strings/internal/str_format/bind.h" // IWYU pragma: export
  82. #include "y_absl/strings/internal/str_format/checker.h" // IWYU pragma: export
  83. #include "y_absl/strings/internal/str_format/extension.h" // IWYU pragma: export
  84. #include "y_absl/strings/internal/str_format/parser.h" // IWYU pragma: export
  85. #include "y_absl/strings/string_view.h"
  86. #include "y_absl/types/span.h"
  87. namespace y_absl {
  88. Y_ABSL_NAMESPACE_BEGIN
  89. // UntypedFormatSpec
  90. //
  91. // A type-erased class that can be used directly within untyped API entry
  92. // points. An `UntypedFormatSpec` is specifically used as an argument to
  93. // `FormatUntyped()`.
  94. //
  95. // Example:
  96. //
  97. // y_absl::UntypedFormatSpec format("%d");
  98. // TString out;
  99. // CHECK(y_absl::FormatUntyped(&out, format, {y_absl::FormatArg(1)}));
  100. class UntypedFormatSpec {
  101. public:
  102. UntypedFormatSpec() = delete;
  103. UntypedFormatSpec(const UntypedFormatSpec&) = delete;
  104. UntypedFormatSpec& operator=(const UntypedFormatSpec&) = delete;
  105. explicit UntypedFormatSpec(string_view s) : spec_(s) {}
  106. protected:
  107. explicit UntypedFormatSpec(
  108. y_absl::Nonnull<const str_format_internal::ParsedFormatBase*> pc)
  109. : spec_(pc) {}
  110. private:
  111. friend str_format_internal::UntypedFormatSpecImpl;
  112. str_format_internal::UntypedFormatSpecImpl spec_;
  113. };
  114. // FormatStreamed()
  115. //
  116. // Takes a streamable argument and returns an object that can print it
  117. // with '%s'. Allows printing of types that have an `operator<<` but no
  118. // intrinsic type support within `StrFormat()` itself.
  119. //
  120. // Example:
  121. //
  122. // y_absl::StrFormat("%s", y_absl::FormatStreamed(obj));
  123. template <typename T>
  124. str_format_internal::StreamedWrapper<T> FormatStreamed(const T& v) {
  125. return str_format_internal::StreamedWrapper<T>(v);
  126. }
  127. // FormatCountCapture
  128. //
  129. // This class provides a way to safely wrap `StrFormat()` captures of `%n`
  130. // conversions, which denote the number of characters written by a formatting
  131. // operation to this point, into an integer value.
  132. //
  133. // This wrapper is designed to allow safe usage of `%n` within `StrFormat(); in
  134. // the `printf()` family of functions, `%n` is not safe to use, as the `int *`
  135. // buffer can be used to capture arbitrary data.
  136. //
  137. // Example:
  138. //
  139. // int n = 0;
  140. // TString s = y_absl::StrFormat("%s%d%n", "hello", 123,
  141. // y_absl::FormatCountCapture(&n));
  142. // EXPECT_EQ(8, n);
  143. class FormatCountCapture {
  144. public:
  145. explicit FormatCountCapture(y_absl::Nonnull<int*> p) : p_(p) {}
  146. private:
  147. // FormatCountCaptureHelper is used to define FormatConvertImpl() for this
  148. // class.
  149. friend struct str_format_internal::FormatCountCaptureHelper;
  150. // Unused() is here because of the false positive from -Wunused-private-field
  151. // p_ is used in the templated function of the friend FormatCountCaptureHelper
  152. // class.
  153. y_absl::Nonnull<int*> Unused() { return p_; }
  154. y_absl::Nonnull<int*> p_;
  155. };
  156. // FormatSpec
  157. //
  158. // The `FormatSpec` type defines the makeup of a format string within the
  159. // `str_format` library. It is a variadic class template that is evaluated at
  160. // compile-time, according to the format string and arguments that are passed to
  161. // it.
  162. //
  163. // You should not need to manipulate this type directly. You should only name it
  164. // if you are writing wrapper functions which accept format arguments that will
  165. // be provided unmodified to functions in this library. Such a wrapper function
  166. // might be a class method that provides format arguments and/or internally uses
  167. // the result of formatting.
  168. //
  169. // For a `FormatSpec` to be valid at compile-time, it must be provided as
  170. // either:
  171. //
  172. // * A `constexpr` literal or `y_absl::string_view`, which is how it is most often
  173. // used.
  174. // * A `ParsedFormat` instantiation, which ensures the format string is
  175. // valid before use. (See below.)
  176. //
  177. // Example:
  178. //
  179. // // Provided as a string literal.
  180. // y_absl::StrFormat("Welcome to %s, Number %d!", "The Village", 6);
  181. //
  182. // // Provided as a constexpr y_absl::string_view.
  183. // constexpr y_absl::string_view formatString = "Welcome to %s, Number %d!";
  184. // y_absl::StrFormat(formatString, "The Village", 6);
  185. //
  186. // // Provided as a pre-compiled ParsedFormat object.
  187. // // Note that this example is useful only for illustration purposes.
  188. // y_absl::ParsedFormat<'s', 'd'> formatString("Welcome to %s, Number %d!");
  189. // y_absl::StrFormat(formatString, "TheVillage", 6);
  190. //
  191. // A format string generally follows the POSIX syntax as used within the POSIX
  192. // `printf` specification. (Exceptions are noted below.)
  193. //
  194. // (See http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html)
  195. //
  196. // In specific, the `FormatSpec` supports the following type specifiers:
  197. // * `c` for characters
  198. // * `s` for strings
  199. // * `d` or `i` for integers
  200. // * `o` for unsigned integer conversions into octal
  201. // * `x` or `X` for unsigned integer conversions into hex
  202. // * `u` for unsigned integers
  203. // * `f` or `F` for floating point values into decimal notation
  204. // * `e` or `E` for floating point values into exponential notation
  205. // * `a` or `A` for floating point values into hex exponential notation
  206. // * `g` or `G` for floating point values into decimal or exponential
  207. // notation based on their precision
  208. // * `p` for pointer address values
  209. // * `n` for the special case of writing out the number of characters
  210. // written to this point. The resulting value must be captured within an
  211. // `y_absl::FormatCountCapture` type.
  212. // * `v` for values using the default format for a deduced type. These deduced
  213. // types include many of the primitive types denoted here as well as
  214. // user-defined types containing the proper extensions. (See below for more
  215. // information.)
  216. //
  217. // Implementation-defined behavior:
  218. // * A null pointer provided to "%s" or "%p" is output as "(nil)".
  219. // * A non-null pointer provided to "%p" is output in hex as if by %#x or
  220. // %#lx.
  221. //
  222. // NOTE: `o`, `x\X` and `u` will convert signed values to their unsigned
  223. // counterpart before formatting.
  224. //
  225. // Examples:
  226. // "%c", 'a' -> "a"
  227. // "%c", 32 -> " "
  228. // "%s", "C" -> "C"
  229. // "%s", TString("C++") -> "C++"
  230. // "%d", -10 -> "-10"
  231. // "%o", 10 -> "12"
  232. // "%x", 16 -> "10"
  233. // "%f", 123456789 -> "123456789.000000"
  234. // "%e", .01 -> "1.00000e-2"
  235. // "%a", -3.0 -> "-0x1.8p+1"
  236. // "%g", .01 -> "1e-2"
  237. // "%p", (void*)&value -> "0x7ffdeb6ad2a4"
  238. //
  239. // int n = 0;
  240. // TString s = y_absl::StrFormat(
  241. // "%s%d%n", "hello", 123, y_absl::FormatCountCapture(&n));
  242. // EXPECT_EQ(8, n);
  243. //
  244. // NOTE: the `v` specifier (for "value") is a type specifier not present in the
  245. // POSIX specification. %v will format values according to their deduced type.
  246. // `v` uses `d` for signed integer values, `u` for unsigned integer values, `g`
  247. // for floating point values, and formats boolean values as "true"/"false"
  248. // (instead of 1 or 0 for booleans formatted using d). `const char*` is not
  249. // supported; please use `TString` and `string_view`. `char` is also not
  250. // supported due to ambiguity of the type. This specifier does not support
  251. // modifiers.
  252. //
  253. // The `FormatSpec` intrinsically supports all of these fundamental C++ types:
  254. //
  255. // * Characters: `char`, `signed char`, `unsigned char`, `wchar_t`
  256. // * Integers: `int`, `short`, `unsigned short`, `unsigned`, `long`,
  257. // `unsigned long`, `long long`, `unsigned long long`
  258. // * Enums: printed as their underlying integral value
  259. // * Floating-point: `float`, `double`, `long double`
  260. //
  261. // However, in the `str_format` library, a format conversion specifies a broader
  262. // C++ conceptual category instead of an exact type. For example, `%s` binds to
  263. // any string-like argument, so `TString`, `std::wstring`,
  264. // `y_absl::string_view`, `const char*`, and `const wchar_t*` are all accepted.
  265. // Likewise, `%d` accepts any integer-like argument, etc.
  266. template <typename... Args>
  267. using FormatSpec = str_format_internal::FormatSpecTemplate<
  268. str_format_internal::ArgumentToConv<Args>()...>;
  269. // ParsedFormat
  270. //
  271. // A `ParsedFormat` is a class template representing a preparsed `FormatSpec`,
  272. // with template arguments specifying the conversion characters used within the
  273. // format string. Such characters must be valid format type specifiers, and
  274. // these type specifiers are checked at compile-time.
  275. //
  276. // Instances of `ParsedFormat` can be created, copied, and reused to speed up
  277. // formatting loops. A `ParsedFormat` may either be constructed statically, or
  278. // dynamically through its `New()` factory function, which only constructs a
  279. // runtime object if the format is valid at that time.
  280. //
  281. // Example:
  282. //
  283. // // Verified at compile time.
  284. // y_absl::ParsedFormat<'s', 'd'> format_string("Welcome to %s, Number %d!");
  285. // y_absl::StrFormat(format_string, "TheVillage", 6);
  286. //
  287. // // Verified at runtime.
  288. // auto format_runtime = y_absl::ParsedFormat<'d'>::New(format_string);
  289. // if (format_runtime) {
  290. // value = y_absl::StrFormat(*format_runtime, i);
  291. // } else {
  292. // ... error case ...
  293. // }
  294. #if defined(__cpp_nontype_template_parameter_auto)
  295. // If C++17 is available, an 'extended' format is also allowed that can specify
  296. // multiple conversion characters per format argument, using a combination of
  297. // `y_absl::FormatConversionCharSet` enum values (logically a set union)
  298. // via the `|` operator. (Single character-based arguments are still accepted,
  299. // but cannot be combined). Some common conversions also have predefined enum
  300. // values, such as `y_absl::FormatConversionCharSet::kIntegral`.
  301. //
  302. // Example:
  303. // // Extended format supports multiple conversion characters per argument,
  304. // // specified via a combination of `FormatConversionCharSet` enums.
  305. // using MyFormat = y_absl::ParsedFormat<y_absl::FormatConversionCharSet::d |
  306. // y_absl::FormatConversionCharSet::x>;
  307. // MyFormat GetFormat(bool use_hex) {
  308. // if (use_hex) return MyFormat("foo %x bar");
  309. // return MyFormat("foo %d bar");
  310. // }
  311. // // `format` can be used with any value that supports 'd' and 'x',
  312. // // like `int`.
  313. // auto format = GetFormat(use_hex);
  314. // value = StringF(format, i);
  315. template <auto... Conv>
  316. using ParsedFormat = y_absl::str_format_internal::ExtendedParsedFormat<
  317. y_absl::str_format_internal::ToFormatConversionCharSet(Conv)...>;
  318. #else
  319. template <char... Conv>
  320. using ParsedFormat = str_format_internal::ExtendedParsedFormat<
  321. y_absl::str_format_internal::ToFormatConversionCharSet(Conv)...>;
  322. #endif // defined(__cpp_nontype_template_parameter_auto)
  323. // StrFormat()
  324. //
  325. // Returns a `string` given a `printf()`-style format string and zero or more
  326. // additional arguments. Use it as you would `sprintf()`. `StrFormat()` is the
  327. // primary formatting function within the `str_format` library, and should be
  328. // used in most cases where you need type-safe conversion of types into
  329. // formatted strings.
  330. //
  331. // The format string generally consists of ordinary character data along with
  332. // one or more format conversion specifiers (denoted by the `%` character).
  333. // Ordinary character data is returned unchanged into the result string, while
  334. // each conversion specification performs a type substitution from
  335. // `StrFormat()`'s other arguments. See the comments for `FormatSpec` for full
  336. // information on the makeup of this format string.
  337. //
  338. // Example:
  339. //
  340. // TString s = y_absl::StrFormat(
  341. // "Welcome to %s, Number %d!", "The Village", 6);
  342. // EXPECT_EQ("Welcome to The Village, Number 6!", s);
  343. //
  344. // Returns an empty string in case of error.
  345. template <typename... Args>
  346. Y_ABSL_MUST_USE_RESULT TString StrFormat(const FormatSpec<Args...>& format,
  347. const Args&... args) {
  348. return str_format_internal::FormatPack(
  349. str_format_internal::UntypedFormatSpecImpl::Extract(format),
  350. {str_format_internal::FormatArgImpl(args)...});
  351. }
  352. // StrAppendFormat()
  353. //
  354. // Appends to a `dst` string given a format string, and zero or more additional
  355. // arguments, returning `*dst` as a convenience for chaining purposes. Appends
  356. // nothing in case of error (but possibly alters its capacity).
  357. //
  358. // Example:
  359. //
  360. // TString orig("For example PI is approximately ");
  361. // std::cout << StrAppendFormat(&orig, "%12.6f", 3.14);
  362. template <typename... Args>
  363. TString& StrAppendFormat(y_absl::Nonnull<TString*> dst,
  364. const FormatSpec<Args...>& format,
  365. const Args&... args) {
  366. return str_format_internal::AppendPack(
  367. dst, str_format_internal::UntypedFormatSpecImpl::Extract(format),
  368. {str_format_internal::FormatArgImpl(args)...});
  369. }
  370. // StreamFormat()
  371. //
  372. // Writes to an output stream given a format string and zero or more arguments,
  373. // generally in a manner that is more efficient than streaming the result of
  374. // `y_absl::StrFormat()`. The returned object must be streamed before the full
  375. // expression ends.
  376. //
  377. // Example:
  378. //
  379. // std::cout << StreamFormat("%12.6f", 3.14);
  380. template <typename... Args>
  381. Y_ABSL_MUST_USE_RESULT str_format_internal::Streamable StreamFormat(
  382. const FormatSpec<Args...>& format, const Args&... args) {
  383. return str_format_internal::Streamable(
  384. str_format_internal::UntypedFormatSpecImpl::Extract(format),
  385. {str_format_internal::FormatArgImpl(args)...});
  386. }
  387. // PrintF()
  388. //
  389. // Writes to stdout given a format string and zero or more arguments. This
  390. // function is functionally equivalent to `std::printf()` (and type-safe);
  391. // prefer `y_absl::PrintF()` over `std::printf()`.
  392. //
  393. // Example:
  394. //
  395. // std::string_view s = "Ulaanbaatar";
  396. // y_absl::PrintF("The capital of Mongolia is %s", s);
  397. //
  398. // Outputs: "The capital of Mongolia is Ulaanbaatar"
  399. //
  400. template <typename... Args>
  401. int PrintF(const FormatSpec<Args...>& format, const Args&... args) {
  402. return str_format_internal::FprintF(
  403. stdout, str_format_internal::UntypedFormatSpecImpl::Extract(format),
  404. {str_format_internal::FormatArgImpl(args)...});
  405. }
  406. // FPrintF()
  407. //
  408. // Writes to a file given a format string and zero or more arguments. This
  409. // function is functionally equivalent to `std::fprintf()` (and type-safe);
  410. // prefer `y_absl::FPrintF()` over `std::fprintf()`.
  411. //
  412. // Example:
  413. //
  414. // std::string_view s = "Ulaanbaatar";
  415. // y_absl::FPrintF(stdout, "The capital of Mongolia is %s", s);
  416. //
  417. // Outputs: "The capital of Mongolia is Ulaanbaatar"
  418. //
  419. template <typename... Args>
  420. int FPrintF(y_absl::Nonnull<std::FILE*> output, const FormatSpec<Args...>& format,
  421. const Args&... args) {
  422. return str_format_internal::FprintF(
  423. output, str_format_internal::UntypedFormatSpecImpl::Extract(format),
  424. {str_format_internal::FormatArgImpl(args)...});
  425. }
  426. // SNPrintF()
  427. //
  428. // Writes to a sized buffer given a format string and zero or more arguments.
  429. // This function is functionally equivalent to `std::snprintf()` (and
  430. // type-safe); prefer `y_absl::SNPrintF()` over `std::snprintf()`.
  431. //
  432. // In particular, a successful call to `y_absl::SNPrintF()` writes at most `size`
  433. // bytes of the formatted output to `output`, including a NUL-terminator, and
  434. // returns the number of bytes that would have been written if truncation did
  435. // not occur. In the event of an error, a negative value is returned and `errno`
  436. // is set.
  437. //
  438. // Example:
  439. //
  440. // std::string_view s = "Ulaanbaatar";
  441. // char output[128];
  442. // y_absl::SNPrintF(output, sizeof(output),
  443. // "The capital of Mongolia is %s", s);
  444. //
  445. // Post-condition: output == "The capital of Mongolia is Ulaanbaatar"
  446. //
  447. template <typename... Args>
  448. int SNPrintF(y_absl::Nonnull<char*> output, std::size_t size,
  449. const FormatSpec<Args...>& format, const Args&... args) {
  450. return str_format_internal::SnprintF(
  451. output, size, str_format_internal::UntypedFormatSpecImpl::Extract(format),
  452. {str_format_internal::FormatArgImpl(args)...});
  453. }
  454. // -----------------------------------------------------------------------------
  455. // Custom Output Formatting Functions
  456. // -----------------------------------------------------------------------------
  457. // FormatRawSink
  458. //
  459. // FormatRawSink is a type erased wrapper around arbitrary sink objects
  460. // specifically used as an argument to `Format()`.
  461. //
  462. // All the object has to do define an overload of `AbslFormatFlush()` for the
  463. // sink, usually by adding a ADL-based free function in the same namespace as
  464. // the sink:
  465. //
  466. // void AbslFormatFlush(MySink* dest, y_absl::string_view part);
  467. //
  468. // where `dest` is the pointer passed to `y_absl::Format()`. The function should
  469. // append `part` to `dest`.
  470. //
  471. // FormatRawSink does not own the passed sink object. The passed object must
  472. // outlive the FormatRawSink.
  473. class FormatRawSink {
  474. public:
  475. // Implicitly convert from any type that provides the hook function as
  476. // described above.
  477. template <typename T,
  478. typename = typename std::enable_if<std::is_constructible<
  479. str_format_internal::FormatRawSinkImpl, T*>::value>::type>
  480. FormatRawSink(y_absl::Nonnull<T*> raw) // NOLINT
  481. : sink_(raw) {}
  482. private:
  483. friend str_format_internal::FormatRawSinkImpl;
  484. str_format_internal::FormatRawSinkImpl sink_;
  485. };
  486. // Format()
  487. //
  488. // Writes a formatted string to an arbitrary sink object (implementing the
  489. // `y_absl::FormatRawSink` interface), using a format string and zero or more
  490. // additional arguments.
  491. //
  492. // By default, `TString`, `std::ostream`, and `y_absl::Cord` are supported as
  493. // destination objects. If a `TString` is used the formatted string is
  494. // appended to it.
  495. //
  496. // `y_absl::Format()` is a generic version of `y_absl::StrAppendFormat()`, for
  497. // custom sinks. The format string, like format strings for `StrFormat()`, is
  498. // checked at compile-time.
  499. //
  500. // On failure, this function returns `false` and the state of the sink is
  501. // unspecified.
  502. template <typename... Args>
  503. bool Format(FormatRawSink raw_sink, const FormatSpec<Args...>& format,
  504. const Args&... args) {
  505. return str_format_internal::FormatUntyped(
  506. str_format_internal::FormatRawSinkImpl::Extract(raw_sink),
  507. str_format_internal::UntypedFormatSpecImpl::Extract(format),
  508. {str_format_internal::FormatArgImpl(args)...});
  509. }
  510. // FormatArg
  511. //
  512. // A type-erased handle to a format argument specifically used as an argument to
  513. // `FormatUntyped()`. You may construct `FormatArg` by passing
  514. // reference-to-const of any printable type. `FormatArg` is both copyable and
  515. // assignable. The source data must outlive the `FormatArg` instance. See
  516. // example below.
  517. //
  518. using FormatArg = str_format_internal::FormatArgImpl;
  519. // FormatUntyped()
  520. //
  521. // Writes a formatted string to an arbitrary sink object (implementing the
  522. // `y_absl::FormatRawSink` interface), using an `UntypedFormatSpec` and zero or
  523. // more additional arguments.
  524. //
  525. // This function acts as the most generic formatting function in the
  526. // `str_format` library. The caller provides a raw sink, an unchecked format
  527. // string, and (usually) a runtime specified list of arguments; no compile-time
  528. // checking of formatting is performed within this function. As a result, a
  529. // caller should check the return value to verify that no error occurred.
  530. // On failure, this function returns `false` and the state of the sink is
  531. // unspecified.
  532. //
  533. // The arguments are provided in an `y_absl::Span<const y_absl::FormatArg>`.
  534. // Each `y_absl::FormatArg` object binds to a single argument and keeps a
  535. // reference to it. The values used to create the `FormatArg` objects must
  536. // outlive this function call.
  537. //
  538. // Example:
  539. //
  540. // std::optional<TString> FormatDynamic(
  541. // const TString& in_format,
  542. // const vector<TString>& in_args) {
  543. // TString out;
  544. // std::vector<y_absl::FormatArg> args;
  545. // for (const auto& v : in_args) {
  546. // // It is important that 'v' is a reference to the objects in in_args.
  547. // // The values we pass to FormatArg must outlive the call to
  548. // // FormatUntyped.
  549. // args.emplace_back(v);
  550. // }
  551. // y_absl::UntypedFormatSpec format(in_format);
  552. // if (!y_absl::FormatUntyped(&out, format, args)) {
  553. // return std::nullopt;
  554. // }
  555. // return std::move(out);
  556. // }
  557. //
  558. Y_ABSL_MUST_USE_RESULT inline bool FormatUntyped(
  559. FormatRawSink raw_sink, const UntypedFormatSpec& format,
  560. y_absl::Span<const FormatArg> args) {
  561. return str_format_internal::FormatUntyped(
  562. str_format_internal::FormatRawSinkImpl::Extract(raw_sink),
  563. str_format_internal::UntypedFormatSpecImpl::Extract(format), args);
  564. }
  565. //------------------------------------------------------------------------------
  566. // StrFormat Extensions
  567. //------------------------------------------------------------------------------
  568. //
  569. // AbslStringify()
  570. //
  571. // A simpler customization API for formatting user-defined types using
  572. // y_absl::StrFormat(). The API relies on detecting an overload in the
  573. // user-defined type's namespace of a free (non-member) `AbslStringify()`
  574. // function as a friend definition with the following signature:
  575. //
  576. // template <typename Sink>
  577. // void AbslStringify(Sink& sink, const X& value);
  578. //
  579. // An `AbslStringify()` overload for a type should only be declared in the same
  580. // file and namespace as said type.
  581. //
  582. // Note that unlike with AbslFormatConvert(), AbslStringify() does not allow
  583. // customization of allowed conversion characters. AbslStringify() uses `%v` as
  584. // the underlying conversion specififer. Additionally, AbslStringify() supports
  585. // use with y_absl::StrCat while AbslFormatConvert() does not.
  586. //
  587. // Example:
  588. //
  589. // struct Point {
  590. // // To add formatting support to `Point`, we simply need to add a free
  591. // // (non-member) function `AbslStringify()`. This method prints in the
  592. // // request format using the underlying `%v` specifier. You can add such a
  593. // // free function using a friend declaration within the body of the class.
  594. // // The sink parameter is a templated type to avoid requiring dependencies.
  595. // template <typename Sink>
  596. // friend void AbslStringify(Sink& sink, const Point& p) {
  597. // y_absl::Format(&sink, "(%v, %v)", p.x, p.y);
  598. // }
  599. //
  600. // int x;
  601. // int y;
  602. // };
  603. //
  604. // AbslFormatConvert()
  605. //
  606. // The StrFormat library provides a customization API for formatting
  607. // user-defined types using y_absl::StrFormat(). The API relies on detecting an
  608. // overload in the user-defined type's namespace of a free (non-member)
  609. // `AbslFormatConvert()` function, usually as a friend definition with the
  610. // following signature:
  611. //
  612. // y_absl::FormatConvertResult<...> AbslFormatConvert(
  613. // const X& value,
  614. // const y_absl::FormatConversionSpec& spec,
  615. // y_absl::FormatSink *sink);
  616. //
  617. // An `AbslFormatConvert()` overload for a type should only be declared in the
  618. // same file and namespace as said type.
  619. //
  620. // The abstractions within this definition include:
  621. //
  622. // * An `y_absl::FormatConversionSpec` to specify the fields to pull from a
  623. // user-defined type's format string
  624. // * An `y_absl::FormatSink` to hold the converted string data during the
  625. // conversion process.
  626. // * An `y_absl::FormatConvertResult` to hold the status of the returned
  627. // formatting operation
  628. //
  629. // The return type encodes all the conversion characters that your
  630. // AbslFormatConvert() routine accepts. The return value should be {true}.
  631. // A return value of {false} will result in `StrFormat()` returning
  632. // an empty string. This result will be propagated to the result of
  633. // `FormatUntyped`.
  634. //
  635. // Example:
  636. //
  637. // struct Point {
  638. // // To add formatting support to `Point`, we simply need to add a free
  639. // // (non-member) function `AbslFormatConvert()`. This method interprets
  640. // // `spec` to print in the request format. The allowed conversion characters
  641. // // can be restricted via the type of the result, in this example
  642. // // string and integral formatting are allowed (but not, for instance
  643. // // floating point characters like "%f"). You can add such a free function
  644. // // using a friend declaration within the body of the class:
  645. // friend y_absl::FormatConvertResult<y_absl::FormatConversionCharSet::kString |
  646. // y_absl::FormatConversionCharSet::kIntegral>
  647. // AbslFormatConvert(const Point& p, const y_absl::FormatConversionSpec& spec,
  648. // y_absl::FormatSink* s) {
  649. // if (spec.conversion_char() == y_absl::FormatConversionChar::s) {
  650. // y_absl::Format(s, "x=%vy=%v", p.x, p.y);
  651. // } else {
  652. // y_absl::Format(s, "%v,%v", p.x, p.y);
  653. // }
  654. // return {true};
  655. // }
  656. //
  657. // int x;
  658. // int y;
  659. // };
  660. // clang-format off
  661. // FormatConversionChar
  662. //
  663. // Specifies the formatting character provided in the format string
  664. // passed to `StrFormat()`.
  665. enum class FormatConversionChar : uint8_t {
  666. c, s, // text
  667. d, i, o, u, x, X, // int
  668. f, F, e, E, g, G, a, A, // float
  669. n, p, v // misc
  670. };
  671. // clang-format on
  672. // FormatConversionSpec
  673. //
  674. // Specifies modifications to the conversion of the format string, through use
  675. // of one or more format flags in the source format string.
  676. class FormatConversionSpec {
  677. public:
  678. // FormatConversionSpec::is_basic()
  679. //
  680. // Indicates that width and precision are not specified, and no additional
  681. // flags are set for this conversion character in the format string.
  682. bool is_basic() const { return impl_.is_basic(); }
  683. // FormatConversionSpec::has_left_flag()
  684. //
  685. // Indicates whether the result should be left justified for this conversion
  686. // character in the format string. This flag is set through use of a '-'
  687. // character in the format string. E.g. "%-s"
  688. bool has_left_flag() const { return impl_.has_left_flag(); }
  689. // FormatConversionSpec::has_show_pos_flag()
  690. //
  691. // Indicates whether a sign column is prepended to the result for this
  692. // conversion character in the format string, even if the result is positive.
  693. // This flag is set through use of a '+' character in the format string.
  694. // E.g. "%+d"
  695. bool has_show_pos_flag() const { return impl_.has_show_pos_flag(); }
  696. // FormatConversionSpec::has_sign_col_flag()
  697. //
  698. // Indicates whether a mandatory sign column is added to the result for this
  699. // conversion character. This flag is set through use of a space character
  700. // (' ') in the format string. E.g. "% i"
  701. bool has_sign_col_flag() const { return impl_.has_sign_col_flag(); }
  702. // FormatConversionSpec::has_alt_flag()
  703. //
  704. // Indicates whether an "alternate" format is applied to the result for this
  705. // conversion character. Alternative forms depend on the type of conversion
  706. // character, and unallowed alternatives are undefined. This flag is set
  707. // through use of a '#' character in the format string. E.g. "%#h"
  708. bool has_alt_flag() const { return impl_.has_alt_flag(); }
  709. // FormatConversionSpec::has_zero_flag()
  710. //
  711. // Indicates whether zeroes should be prepended to the result for this
  712. // conversion character instead of spaces. This flag is set through use of the
  713. // '0' character in the format string. E.g. "%0f"
  714. bool has_zero_flag() const { return impl_.has_zero_flag(); }
  715. // FormatConversionSpec::conversion_char()
  716. //
  717. // Returns the underlying conversion character.
  718. FormatConversionChar conversion_char() const {
  719. return impl_.conversion_char();
  720. }
  721. // FormatConversionSpec::width()
  722. //
  723. // Returns the specified width (indicated through use of a non-zero integer
  724. // value or '*' character) of the conversion character. If width is
  725. // unspecified, it returns a negative value.
  726. int width() const { return impl_.width(); }
  727. // FormatConversionSpec::precision()
  728. //
  729. // Returns the specified precision (through use of the '.' character followed
  730. // by a non-zero integer value or '*' character) of the conversion character.
  731. // If precision is unspecified, it returns a negative value.
  732. int precision() const { return impl_.precision(); }
  733. private:
  734. explicit FormatConversionSpec(
  735. str_format_internal::FormatConversionSpecImpl impl)
  736. : impl_(impl) {}
  737. friend str_format_internal::FormatConversionSpecImpl;
  738. y_absl::str_format_internal::FormatConversionSpecImpl impl_;
  739. };
  740. // Type safe OR operator for FormatConversionCharSet to allow accepting multiple
  741. // conversion chars in custom format converters.
  742. constexpr FormatConversionCharSet operator|(FormatConversionCharSet a,
  743. FormatConversionCharSet b) {
  744. return static_cast<FormatConversionCharSet>(static_cast<uint64_t>(a) |
  745. static_cast<uint64_t>(b));
  746. }
  747. // FormatConversionCharSet
  748. //
  749. // Specifies the _accepted_ conversion types as a template parameter to
  750. // FormatConvertResult for custom implementations of `AbslFormatConvert`.
  751. // Note the helper predefined alias definitions (kIntegral, etc.) below.
  752. enum class FormatConversionCharSet : uint64_t {
  753. // text
  754. c = str_format_internal::FormatConversionCharToConvInt('c'),
  755. s = str_format_internal::FormatConversionCharToConvInt('s'),
  756. // integer
  757. d = str_format_internal::FormatConversionCharToConvInt('d'),
  758. i = str_format_internal::FormatConversionCharToConvInt('i'),
  759. o = str_format_internal::FormatConversionCharToConvInt('o'),
  760. u = str_format_internal::FormatConversionCharToConvInt('u'),
  761. x = str_format_internal::FormatConversionCharToConvInt('x'),
  762. X = str_format_internal::FormatConversionCharToConvInt('X'),
  763. // Float
  764. f = str_format_internal::FormatConversionCharToConvInt('f'),
  765. F = str_format_internal::FormatConversionCharToConvInt('F'),
  766. e = str_format_internal::FormatConversionCharToConvInt('e'),
  767. E = str_format_internal::FormatConversionCharToConvInt('E'),
  768. g = str_format_internal::FormatConversionCharToConvInt('g'),
  769. G = str_format_internal::FormatConversionCharToConvInt('G'),
  770. a = str_format_internal::FormatConversionCharToConvInt('a'),
  771. A = str_format_internal::FormatConversionCharToConvInt('A'),
  772. // misc
  773. n = str_format_internal::FormatConversionCharToConvInt('n'),
  774. p = str_format_internal::FormatConversionCharToConvInt('p'),
  775. v = str_format_internal::FormatConversionCharToConvInt('v'),
  776. // Used for width/precision '*' specification.
  777. kStar = static_cast<uint64_t>(
  778. y_absl::str_format_internal::FormatConversionCharSetInternal::kStar),
  779. // Some predefined values:
  780. kIntegral = d | i | u | o | x | X,
  781. kFloating = a | e | f | g | A | E | F | G,
  782. kNumeric = kIntegral | kFloating,
  783. kString = s,
  784. kPointer = p,
  785. };
  786. // FormatSink
  787. //
  788. // A format sink is a generic abstraction to which conversions may write their
  789. // formatted string data. `y_absl::FormatConvert()` uses this sink to write its
  790. // formatted string.
  791. //
  792. class FormatSink {
  793. public:
  794. // FormatSink::Append()
  795. //
  796. // Appends `count` copies of `ch` to the format sink.
  797. void Append(size_t count, char ch) { sink_->Append(count, ch); }
  798. // Overload of FormatSink::Append() for appending the characters of a string
  799. // view to a format sink.
  800. void Append(string_view v) { sink_->Append(v); }
  801. // FormatSink::PutPaddedString()
  802. //
  803. // Appends `precision` number of bytes of `v` to the format sink. If this is
  804. // less than `width`, spaces will be appended first (if `left` is false), or
  805. // after (if `left` is true) to ensure the total amount appended is
  806. // at least `width`.
  807. bool PutPaddedString(string_view v, int width, int precision, bool left) {
  808. return sink_->PutPaddedString(v, width, precision, left);
  809. }
  810. // Support `y_absl::Format(&sink, format, args...)`.
  811. friend void AbslFormatFlush(y_absl::Nonnull<FormatSink*> sink,
  812. y_absl::string_view v) {
  813. sink->Append(v);
  814. }
  815. private:
  816. friend str_format_internal::FormatSinkImpl;
  817. explicit FormatSink(y_absl::Nonnull<str_format_internal::FormatSinkImpl*> s)
  818. : sink_(s) {}
  819. y_absl::Nonnull<str_format_internal::FormatSinkImpl*> sink_;
  820. };
  821. // FormatConvertResult
  822. //
  823. // Indicates whether a call to AbslFormatConvert() was successful.
  824. // This return type informs the StrFormat extension framework (through
  825. // ADL but using the return type) of what conversion characters are supported.
  826. // It is strongly discouraged to return {false}, as this will result in an
  827. // empty string in StrFormat.
  828. template <FormatConversionCharSet C>
  829. struct FormatConvertResult {
  830. bool value;
  831. };
  832. Y_ABSL_NAMESPACE_END
  833. } // namespace y_absl
  834. #endif // Y_ABSL_STRINGS_STR_FORMAT_H_