str_format.h 32 KB

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