You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

str_format.h 36 kB

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