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