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