str_format.h
Go to the documentation of this file.
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, the `str_format` uses a "format string" to
23 // perform argument substitutions based on types.
24 //
25 // Example:
26 //
27 // std::string s = absl::StrFormat(
28 // "%s %s You have $%d!", "Hello", name, dollars);
29 //
30 // The library consists of the following basic utilities:
31 //
32 // * `absl::StrFormat()`, a type-safe replacement for `std::sprintf()`, to
33 // write a format string to a `string` value.
34 // * `absl::StrAppendFormat()` to append a format string to a `string`
35 // * `absl::StreamFormat()` to more efficiently write a format string to a
36 // stream, such as`std::cout`.
37 // * `absl::PrintF()`, `absl::FPrintF()` and `absl::SNPrintF()` as
38 // replacements for `std::printf()`, `std::fprintf()` and `std::snprintf()`.
39 //
40 // Note: a version of `std::sprintf()` is not supported as it is
41 // generally unsafe due to buffer overflows.
42 //
43 // Additionally, you can provide a format string (and its associated arguments)
44 // using one of the following abstractions:
45 //
46 // * A `FormatSpec` class template fully encapsulates a format string and its
47 // type arguments and is usually provided to `str_format` functions as a
48 // variadic argument of type `FormatSpec<Arg...>`. The `FormatSpec<Args...>`
49 // template is evaluated at compile-time, providing type safety.
50 // * A `ParsedFormat` instance, which encapsulates a specific, pre-compiled
51 // format string for a specific set of type(s), and which can be passed
52 // between API boundaries. (The `FormatSpec` type should not be used
53 // directly except as an argument type for wrapper functions.)
54 //
55 // The `str_format` library provides the ability to output its format strings to
56 // arbitrary sink types:
57 //
58 // * A generic `Format()` function to write outputs to arbitrary sink types,
59 // which must implement a `RawSinkFormat` interface. (See
60 // `str_format_sink.h` for more information.)
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. These extensions are fully documented
69 // within the `str_format_extension.h` header file.
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 
84 // UntypedFormatSpec
85 //
86 // A type-erased class that can be used directly within untyped API entry
87 // points. An `UntypedFormatSpec` is specifically used as an argument to
88 // `FormatUntyped()`.
89 //
90 // Example:
91 //
92 // absl::UntypedFormatSpec format("%d");
93 // std::string out;
94 // CHECK(absl::FormatUntyped(&out, format, {absl::FormatArg(1)}));
96  public:
97  UntypedFormatSpec() = delete;
98  UntypedFormatSpec(const UntypedFormatSpec&) = delete;
100 
101  explicit UntypedFormatSpec(string_view s) : spec_(s) {}
102 
103  protected:
105  : spec_(pc) {}
106 
107  private:
110 };
111 
112 // FormatStreamed()
113 //
114 // Takes a streamable argument and returns an object that can print it
115 // with '%s'. Allows printing of types that have an `operator<<` but no
116 // intrinsic type support within `StrFormat()` itself.
117 //
118 // Example:
119 //
120 // absl::StrFormat("%s", absl::FormatStreamed(obj));
121 template <typename T>
124 }
125 
126 // FormatCountCapture
127 //
128 // This class provides a way to safely wrap `StrFormat()` captures of `%n`
129 // conversions, which denote the number of characters written by a formatting
130 // operation to this point, into an integer value.
131 //
132 // This wrapper is designed to allow safe usage of `%n` within `StrFormat(); in
133 // the `printf()` family of functions, `%n` is not safe to use, as the `int *`
134 // buffer can be used to capture arbitrary data.
135 //
136 // Example:
137 //
138 // int n = 0;
139 // std::string s = absl::StrFormat("%s%d%n", "hello", 123,
140 // absl::FormatCountCapture(&n));
141 // EXPECT_EQ(8, n);
143  public:
144  explicit FormatCountCapture(int* p) : p_(p) {}
145 
146  private:
147  // FormatCountCaptureHelper is used to define FormatConvertImpl() for this
148  // class.
150  // Unused() is here because of the false positive from -Wunused-private-field
151  // p_ is used in the templated function of the friend FormatCountCaptureHelper
152  // class.
153  int* Unused() { return p_; }
154  int* p_;
155 };
156 
157 // FormatSpec
158 //
159 // The `FormatSpec` type defines the makeup of a format string within the
160 // `str_format` library. It is a variadic class template that is evaluated at
161 // compile-time, according to the format string and arguments that are passed to
162 // it.
163 //
164 // You should not need to manipulate this type directly. You should only name it
165 // if you are writing wrapper functions which accept format arguments that will
166 // be provided unmodified to functions in this library. Such a wrapper function
167 // might be a class method that provides format arguments and/or internally uses
168 // the result of formatting.
169 //
170 // For a `FormatSpec` to be valid at compile-time, it must be provided as
171 // either:
172 //
173 // * A `constexpr` literal or `absl::string_view`, which is how it most often
174 // used.
175 // * A `ParsedFormat` instantiation, which ensures the format string is
176 // valid before use. (See below.)
177 //
178 // Example:
179 //
180 // // Provided as a string literal.
181 // absl::StrFormat("Welcome to %s, Number %d!", "The Village", 6);
182 //
183 // // Provided as a constexpr absl::string_view.
184 // constexpr absl::string_view formatString = "Welcome to %s, Number %d!";
185 // absl::StrFormat(formatString, "The Village", 6);
186 //
187 // // Provided as a pre-compiled ParsedFormat object.
188 // // Note that this example is useful only for illustration purposes.
189 // absl::ParsedFormat<'s', 'd'> formatString("Welcome to %s, Number %d!");
190 // absl::StrFormat(formatString, "TheVillage", 6);
191 //
192 // A format string generally follows the POSIX syntax as used within the POSIX
193 // `printf` specification.
194 //
195 // (See http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html.)
196 //
197 // In specific, the `FormatSpec` supports the following type specifiers:
198 // * `c` for characters
199 // * `s` for strings
200 // * `d` or `i` for integers
201 // * `o` for unsigned integer conversions into octal
202 // * `x` or `X` for unsigned integer conversions into hex
203 // * `u` for unsigned integers
204 // * `f` or `F` for floating point values into decimal notation
205 // * `e` or `E` for floating point values into exponential notation
206 // * `a` or `A` for floating point values into hex exponential notation
207 // * `g` or `G` for floating point values into decimal or exponential
208 // notation based on their precision
209 // * `p` for pointer address values
210 // * `n` for the special case of writing out the number of characters
211 // written to this point. The resulting value must be captured within an
212 // `absl::FormatCountCapture` type.
213 //
214 // NOTE: `o`, `x\X` and `u` will convert signed values to their unsigned
215 // counterpart before formatting.
216 //
217 // Examples:
218 // "%c", 'a' -> "a"
219 // "%c", 32 -> " "
220 // "%s", "C" -> "C"
221 // "%s", std::string("C++") -> "C++"
222 // "%d", -10 -> "-10"
223 // "%o", 10 -> "12"
224 // "%x", 16 -> "10"
225 // "%f", 123456789 -> "123456789.000000"
226 // "%e", .01 -> "1.00000e-2"
227 // "%a", -3.0 -> "-0x1.8p+1"
228 // "%g", .01 -> "1e-2"
229 // "%p", *int -> "0x7ffdeb6ad2a4"
230 //
231 // int n = 0;
232 // std::string s = absl::StrFormat(
233 // "%s%d%n", "hello", 123, absl::FormatCountCapture(&n));
234 // EXPECT_EQ(8, n);
235 //
236 // The `FormatSpec` intrinsically supports all of these fundamental C++ types:
237 //
238 // * Characters: `char`, `signed char`, `unsigned char`
239 // * Integers: `int`, `short`, `unsigned short`, `unsigned`, `long`,
240 // `unsigned long`, `long long`, `unsigned long long`
241 // * Floating-point: `float`, `double`, `long double`
242 //
243 // However, in the `str_format` library, a format conversion specifies a broader
244 // C++ conceptual category instead of an exact type. For example, `%s` binds to
245 // any string-like argument, so `std::string`, `absl::string_view`, and
246 // `const char*` are all accepted. Likewise, `%d` accepts any integer-like
247 // argument, etc.
248 
249 template <typename... Args>
250 using FormatSpec =
252 
253 // ParsedFormat
254 //
255 // A `ParsedFormat` is a class template representing a preparsed `FormatSpec`,
256 // with template arguments specifying the conversion characters used within the
257 // format string. Such characters must be valid format type specifiers, and
258 // these type specifiers are checked at compile-time.
259 //
260 // Instances of `ParsedFormat` can be created, copied, and reused to speed up
261 // formatting loops. A `ParsedFormat` may either be constructed statically, or
262 // dynamically through its `New()` factory function, which only constructs a
263 // runtime object if the format is valid at that time.
264 //
265 // Example:
266 //
267 // // Verified at compile time.
268 // absl::ParsedFormat<'s', 'd'> formatString("Welcome to %s, Number %d!");
269 // absl::StrFormat(formatString, "TheVillage", 6);
270 //
271 // // Verified at runtime.
272 // auto format_runtime = absl::ParsedFormat<'d'>::New(format_string);
273 // if (format_runtime) {
274 // value = absl::StrFormat(*format_runtime, i);
275 // } else {
276 // ... error case ...
277 // }
278 template <char... Conv>
281 
282 // StrFormat()
283 //
284 // Returns a `string` given a `printf()`-style format string and zero or more
285 // additional arguments. Use it as you would `sprintf()`. `StrFormat()` is the
286 // primary formatting function within the `str_format` library, and should be
287 // used in most cases where you need type-safe conversion of types into
288 // formatted strings.
289 //
290 // The format string generally consists of ordinary character data along with
291 // one or more format conversion specifiers (denoted by the `%` character).
292 // Ordinary character data is returned unchanged into the result string, while
293 // each conversion specification performs a type substitution from
294 // `StrFormat()`'s other arguments. See the comments for `FormatSpec` for full
295 // information on the makeup of this format string.
296 //
297 // Example:
298 //
299 // std::string s = absl::StrFormat(
300 // "Welcome to %s, Number %d!", "The Village", 6);
301 // EXPECT_EQ("Welcome to The Village, Number 6!", s);
302 //
303 // Returns an empty string in case of error.
304 template <typename... Args>
306  const Args&... args) {
310 }
311 
312 // StrAppendFormat()
313 //
314 // Appends to a `dst` string given a format string, and zero or more additional
315 // arguments, returning `*dst` as a convenience for chaining purposes. Appends
316 // nothing in case of error (but possibly alters its capacity).
317 //
318 // Example:
319 //
320 // std::string orig("For example PI is approximately ");
321 // std::cout << StrAppendFormat(&orig, "%12.6f", 3.14);
322 template <typename... Args>
323 std::string& StrAppendFormat(std::string* dst,
325  const Args&... args) {
329 }
330 
331 // StreamFormat()
332 //
333 // Writes to an output stream given a format string and zero or more arguments,
334 // generally in a manner that is more efficient than streaming the result of
335 // `absl:: StrFormat()`. The returned object must be streamed before the full
336 // expression ends.
337 //
338 // Example:
339 //
340 // std::cout << StreamFormat("%12.6f", 3.14);
341 template <typename... Args>
343  const FormatSpec<Args...>& format, const Args&... args) {
347 }
348 
349 // PrintF()
350 //
351 // Writes to stdout given a format string and zero or more arguments. This
352 // function is functionally equivalent to `std::printf()` (and type-safe);
353 // prefer `absl::PrintF()` over `std::printf()`.
354 //
355 // Example:
356 //
357 // std::string_view s = "Ulaanbaatar";
358 // absl::PrintF("The capital of Mongolia is %s", s);
359 //
360 // Outputs: "The capital of Mongolia is Ulaanbaatar"
361 //
362 template <typename... Args>
363 int PrintF(const FormatSpec<Args...>& format, const Args&... args) {
367 }
368 
369 // FPrintF()
370 //
371 // Writes to a file given a format string and zero or more arguments. This
372 // function is functionally equivalent to `std::fprintf()` (and type-safe);
373 // prefer `absl::FPrintF()` over `std::fprintf()`.
374 //
375 // Example:
376 //
377 // std::string_view s = "Ulaanbaatar";
378 // absl::FPrintF(stdout, "The capital of Mongolia is %s", s);
379 //
380 // Outputs: "The capital of Mongolia is Ulaanbaatar"
381 //
382 template <typename... Args>
383 int FPrintF(std::FILE* output, const FormatSpec<Args...>& format,
384  const Args&... args) {
388 }
389 
390 // SNPrintF()
391 //
392 // Writes to a sized buffer given a format string and zero or more arguments.
393 // This function is functionally equivalent to `std::snprintf()` (and
394 // type-safe); prefer `absl::SNPrintF()` over `std::snprintf()`.
395 //
396 // Example:
397 //
398 // std::string_view s = "Ulaanbaatar";
399 // char output[128];
400 // absl::SNPrintF(output, sizeof(output),
401 // "The capital of Mongolia is %s", s);
402 //
403 // Post-condition: output == "The capital of Mongolia is Ulaanbaatar"
404 //
405 template <typename... Args>
406 int SNPrintF(char* output, std::size_t size, const FormatSpec<Args...>& format,
407  const Args&... args) {
411 }
412 
413 // -----------------------------------------------------------------------------
414 // Custom Output Formatting Functions
415 // -----------------------------------------------------------------------------
416 
417 // FormatRawSink
418 //
419 // FormatRawSink is a type erased wrapper around arbitrary sink objects
420 // specifically used as an argument to `Format()`.
421 // FormatRawSink does not own the passed sink object. The passed object must
422 // outlive the FormatRawSink.
424  public:
425  // Implicitly convert from any type that provides the hook function as
426  // described above.
427  template <typename T,
428  typename = typename std::enable_if<std::is_constructible<
430  FormatRawSink(T* raw) // NOLINT
431  : sink_(raw) {}
432 
433  private:
434  friend str_format_internal::FormatRawSinkImpl;
435  str_format_internal::FormatRawSinkImpl sink_;
436 };
437 
438 // Format()
439 //
440 // Writes a formatted string to an arbitrary sink object (implementing the
441 // `absl::FormatRawSink` interface), using a format string and zero or more
442 // additional arguments.
443 //
444 // By default, `std::string` and `std::ostream` are supported as destination
445 // objects.
446 //
447 // `absl::Format()` is a generic version of `absl::StrFormat(), for custom
448 // sinks. The format string, like format strings for `StrFormat()`, is checked
449 // at compile-time.
450 //
451 // On failure, this function returns `false` and the state of the sink is
452 // unspecified.
453 template <typename... Args>
455  const Args&... args) {
460 }
461 
462 // FormatArg
463 //
464 // A type-erased handle to a format argument specifically used as an argument to
465 // `FormatUntyped()`. You may construct `FormatArg` by passing
466 // reference-to-const of any printable type. `FormatArg` is both copyable and
467 // assignable. The source data must outlive the `FormatArg` instance. See
468 // example below.
469 //
471 
472 // FormatUntyped()
473 //
474 // Writes a formatted string to an arbitrary sink object (implementing the
475 // `absl::FormatRawSink` interface), using an `UntypedFormatSpec` and zero or
476 // more additional arguments.
477 //
478 // This function acts as the most generic formatting function in the
479 // `str_format` library. The caller provides a raw sink, an unchecked format
480 // string, and (usually) a runtime specified list of arguments; no compile-time
481 // checking of formatting is performed within this function. As a result, a
482 // caller should check the return value to verify that no error occurred.
483 // On failure, this function returns `false` and the state of the sink is
484 // unspecified.
485 //
486 // The arguments are provided in an `absl::Span<const absl::FormatArg>`.
487 // Each `absl::FormatArg` object binds to a single argument and keeps a
488 // reference to it. The values used to create the `FormatArg` objects must
489 // outlive this function call. (See `str_format_arg.h` for information on
490 // the `FormatArg` class.)_
491 //
492 // Example:
493 //
494 // std::optional<std::string> FormatDynamic(
495 // const std::string& in_format,
496 // const vector<std::string>& in_args) {
497 // std::string out;
498 // std::vector<absl::FormatArg> args;
499 // for (const auto& v : in_args) {
500 // // It is important that 'v' is a reference to the objects in in_args.
501 // // The values we pass to FormatArg must outlive the call to
502 // // FormatUntyped.
503 // args.emplace_back(v);
504 // }
505 // absl::UntypedFormatSpec format(in_format);
506 // if (!absl::FormatUntyped(&out, format, args)) {
507 // return std::nullopt;
508 // }
509 // return std::move(out);
510 // }
511 //
513  FormatRawSink raw_sink, const UntypedFormatSpec& format,
518 }
519 
520 } // namespace absl
521 
522 #endif // ABSL_STRINGS_STR_FORMAT_H_
int v
Definition: variant_test.cc:81
str_format_internal::StreamedWrapper< T > FormatStreamed(const T &v)
Definition: str_format.h:122
int FprintF(std::FILE *output, const UntypedFormatSpecImpl format, absl::Span< const FormatArgImpl > args)
Definition: bind.cc:199
ABSL_MUST_USE_RESULT str_format_internal::Streamable StreamFormat(const FormatSpec< Args... > &format, const Args &...args)
Definition: str_format.h:342
FormatSinkImpl * sink_
Definition: bind.cc:129
str_format_internal::FormatRawSinkImpl sink_
Definition: str_format.h:435
std::string & StrAppendFormat(std::string *dst, const FormatSpec< Args... > &format, const Args &...args)
Definition: str_format.h:323
static FormatRawSinkImpl Extract(T s)
Definition: extension.h:46
ABSL_MUST_USE_RESULT bool FormatUntyped(FormatRawSink raw_sink, const UntypedFormatSpec &format, absl::Span< const FormatArg > args)
Definition: str_format.h:512
Definition: algorithm.h:29
ABSL_MUST_USE_RESULT std::string StrFormat(const FormatSpec< Args... > &format, const Args &...args)
Definition: str_format.h:305
size_t value
int SnprintF(char *output, size_t size, const UntypedFormatSpecImpl format, absl::Span< const FormatArgImpl > args)
Definition: bind.cc:217
UntypedFormatSpec & operator=(const UntypedFormatSpec &)=delete
#define ABSL_MUST_USE_RESULT
Definition: attributes.h:449
std::string format(const std::string &, const time_point< seconds > &, const femtoseconds &, const time_zone &)
str_format_internal::UntypedFormatSpecImpl spec_
Definition: str_format.h:109
int FPrintF(std::FILE *output, const FormatSpec< Args... > &format, const Args &...args)
Definition: str_format.h:383
static const UntypedFormatSpecImpl & Extract(const T &s)
Definition: bind.h:54
uintptr_t size
bool FormatUntyped(FormatRawSinkImpl raw_sink, const UntypedFormatSpecImpl format, absl::Span< const FormatArgImpl > args)
Definition: bind.cc:177
constexpr Conv ConversionCharToConv(char c)
Definition: extension.h:376
int PrintF(const FormatSpec< Args... > &format, const Args &...args)
Definition: str_format.h:363
UntypedFormatSpec(const str_format_internal::ParsedFormatBase *pc)
Definition: str_format.h:104
std::string & AppendPack(std::string *out, const UntypedFormatSpecImpl format, absl::Span< const FormatArgImpl > args)
Definition: bind.cc:190
std::string FormatPack(const UntypedFormatSpecImpl format, absl::Span< const FormatArgImpl > args)
Definition: bind.h:167
UntypedFormatSpec(string_view s)
Definition: str_format.h:101
typename str_format_internal::FormatSpecDeductionBarrier< Args... >::type FormatSpec
Definition: str_format.h:251
bool Format(FormatRawSink raw_sink, const FormatSpec< Args... > &format, const Args &...args)
Definition: str_format.h:454
std::unique_ptr< unsigned char[]> p_
int SNPrintF(char *output, std::size_t size, const FormatSpec< Args... > &format, const Args &...args)
Definition: str_format.h:406


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:19:58