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