• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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. 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 `RawSinkFormat` interface. (See
61 //     `str_format_sink.h` for more information.)
62 //
63 //   * A `FormatUntyped()` function that is similar to `Format()` except it is
64 //     loosely typed. `FormatUntyped()` is not a template and does not perform
65 //     any compile-time checking of the format string; instead, it returns a
66 //     boolean from a runtime check.
67 //
68 // In addition, the `str_format` library provides extension points for
69 // augmenting formatting to new types. These extensions are fully documented
70 // within the `str_format_extension.h` header file.
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.
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 //
217 // Implementation-defined behavior:
218 //   * A null pointer provided to "%s" or "%p" is output as "(nil)".
219 //   * A non-null pointer provided to "%p" is output in hex as if by %#x or
220 //     %#lx.
221 //
222 // NOTE: `o`, `x\X` and `u` will convert signed values to their unsigned
223 // counterpart before formatting.
224 //
225 // Examples:
226 //     "%c", 'a'                -> "a"
227 //     "%c", 32                 -> " "
228 //     "%s", "C"                -> "C"
229 //     "%s", std::string("C++") -> "C++"
230 //     "%d", -10                -> "-10"
231 //     "%o", 10                 -> "12"
232 //     "%x", 16                 -> "10"
233 //     "%f", 123456789          -> "123456789.000000"
234 //     "%e", .01                -> "1.00000e-2"
235 //     "%a", -3.0               -> "-0x1.8p+1"
236 //     "%g", .01                -> "1e-2"
237 //     "%p", (void*)&value      -> "0x7ffdeb6ad2a4"
238 //
239 //     int n = 0;
240 //     std::string s = absl::StrFormat(
241 //         "%s%d%n", "hello", 123, absl::FormatCountCapture(&n));
242 //     EXPECT_EQ(8, n);
243 //
244 // The `FormatSpec` intrinsically supports all of these fundamental C++ types:
245 //
246 // *   Characters: `char`, `signed char`, `unsigned char`
247 // *   Integers: `int`, `short`, `unsigned short`, `unsigned`, `long`,
248 //         `unsigned long`, `long long`, `unsigned long long`
249 // *   Floating-point: `float`, `double`, `long double`
250 //
251 // However, in the `str_format` library, a format conversion specifies a broader
252 // C++ conceptual category instead of an exact type. For example, `%s` binds to
253 // any string-like argument, so `std::string`, `absl::string_view`, and
254 // `const char*` are all accepted. Likewise, `%d` accepts any integer-like
255 // argument, etc.
256 
257 template <typename... Args>
258 using FormatSpec =
259     typename str_format_internal::FormatSpecDeductionBarrier<Args...>::type;
260 
261 // ParsedFormat
262 //
263 // A `ParsedFormat` is a class template representing a preparsed `FormatSpec`,
264 // with template arguments specifying the conversion characters used within the
265 // format string. Such characters must be valid format type specifiers, and
266 // these type specifiers are checked at compile-time.
267 //
268 // Instances of `ParsedFormat` can be created, copied, and reused to speed up
269 // formatting loops. A `ParsedFormat` may either be constructed statically, or
270 // dynamically through its `New()` factory function, which only constructs a
271 // runtime object if the format is valid at that time.
272 //
273 // Example:
274 //
275 //   // Verified at compile time.
276 //   absl::ParsedFormat<'s', 'd'> formatString("Welcome to %s, Number %d!");
277 //   absl::StrFormat(formatString, "TheVillage", 6);
278 //
279 //   // Verified at runtime.
280 //   auto format_runtime = absl::ParsedFormat<'d'>::New(format_string);
281 //   if (format_runtime) {
282 //     value = absl::StrFormat(*format_runtime, i);
283 //   } else {
284 //     ... error case ...
285 //   }
286 template <char... Conv>
287 using ParsedFormat = str_format_internal::ExtendedParsedFormat<
288     str_format_internal::ConversionCharToConv(Conv)...>;
289 
290 // StrFormat()
291 //
292 // Returns a `string` given a `printf()`-style format string and zero or more
293 // additional arguments. Use it as you would `sprintf()`. `StrFormat()` is the
294 // primary formatting function within the `str_format` library, and should be
295 // used in most cases where you need type-safe conversion of types into
296 // formatted strings.
297 //
298 // The format string generally consists of ordinary character data along with
299 // one or more format conversion specifiers (denoted by the `%` character).
300 // Ordinary character data is returned unchanged into the result string, while
301 // each conversion specification performs a type substitution from
302 // `StrFormat()`'s other arguments. See the comments for `FormatSpec` for full
303 // information on the makeup of this format string.
304 //
305 // Example:
306 //
307 //   std::string s = absl::StrFormat(
308 //       "Welcome to %s, Number %d!", "The Village", 6);
309 //   EXPECT_EQ("Welcome to The Village, Number 6!", s);
310 //
311 // Returns an empty string in case of error.
312 template <typename... Args>
StrFormat(const FormatSpec<Args...> & format,const Args &...args)313 ABSL_MUST_USE_RESULT std::string StrFormat(const FormatSpec<Args...>& format,
314                                            const Args&... args) {
315   return str_format_internal::FormatPack(
316       str_format_internal::UntypedFormatSpecImpl::Extract(format),
317       {str_format_internal::FormatArgImpl(args)...});
318 }
319 
320 // StrAppendFormat()
321 //
322 // Appends to a `dst` string given a format string, and zero or more additional
323 // arguments, returning `*dst` as a convenience for chaining purposes. Appends
324 // nothing in case of error (but possibly alters its capacity).
325 //
326 // Example:
327 //
328 //   std::string orig("For example PI is approximately ");
329 //   std::cout << StrAppendFormat(&orig, "%12.6f", 3.14);
330 template <typename... Args>
StrAppendFormat(std::string * dst,const FormatSpec<Args...> & format,const Args &...args)331 std::string& StrAppendFormat(std::string* dst,
332                              const FormatSpec<Args...>& format,
333                              const Args&... args) {
334   return str_format_internal::AppendPack(
335       dst, str_format_internal::UntypedFormatSpecImpl::Extract(format),
336       {str_format_internal::FormatArgImpl(args)...});
337 }
338 
339 // StreamFormat()
340 //
341 // Writes to an output stream given a format string and zero or more arguments,
342 // generally in a manner that is more efficient than streaming the result of
343 // `absl:: StrFormat()`. The returned object must be streamed before the full
344 // expression ends.
345 //
346 // Example:
347 //
348 //   std::cout << StreamFormat("%12.6f", 3.14);
349 template <typename... Args>
StreamFormat(const FormatSpec<Args...> & format,const Args &...args)350 ABSL_MUST_USE_RESULT str_format_internal::Streamable StreamFormat(
351     const FormatSpec<Args...>& format, const Args&... args) {
352   return str_format_internal::Streamable(
353       str_format_internal::UntypedFormatSpecImpl::Extract(format),
354       {str_format_internal::FormatArgImpl(args)...});
355 }
356 
357 // PrintF()
358 //
359 // Writes to stdout given a format string and zero or more arguments. This
360 // function is functionally equivalent to `std::printf()` (and type-safe);
361 // prefer `absl::PrintF()` over `std::printf()`.
362 //
363 // Example:
364 //
365 //   std::string_view s = "Ulaanbaatar";
366 //   absl::PrintF("The capital of Mongolia is %s", s);
367 //
368 //   Outputs: "The capital of Mongolia is Ulaanbaatar"
369 //
370 template <typename... Args>
PrintF(const FormatSpec<Args...> & format,const Args &...args)371 int PrintF(const FormatSpec<Args...>& format, const Args&... args) {
372   return str_format_internal::FprintF(
373       stdout, str_format_internal::UntypedFormatSpecImpl::Extract(format),
374       {str_format_internal::FormatArgImpl(args)...});
375 }
376 
377 // FPrintF()
378 //
379 // Writes to a file given a format string and zero or more arguments. This
380 // function is functionally equivalent to `std::fprintf()` (and type-safe);
381 // prefer `absl::FPrintF()` over `std::fprintf()`.
382 //
383 // Example:
384 //
385 //   std::string_view s = "Ulaanbaatar";
386 //   absl::FPrintF(stdout, "The capital of Mongolia is %s", s);
387 //
388 //   Outputs: "The capital of Mongolia is Ulaanbaatar"
389 //
390 template <typename... Args>
FPrintF(std::FILE * output,const FormatSpec<Args...> & format,const Args &...args)391 int FPrintF(std::FILE* output, const FormatSpec<Args...>& format,
392             const Args&... args) {
393   return str_format_internal::FprintF(
394       output, str_format_internal::UntypedFormatSpecImpl::Extract(format),
395       {str_format_internal::FormatArgImpl(args)...});
396 }
397 
398 // SNPrintF()
399 //
400 // Writes to a sized buffer given a format string and zero or more arguments.
401 // This function is functionally equivalent to `std::snprintf()` (and
402 // type-safe); prefer `absl::SNPrintF()` over `std::snprintf()`.
403 //
404 // In particular, a successful call to `absl::SNPrintF()` writes at most `size`
405 // bytes of the formatted output to `output`, including a NUL-terminator, and
406 // returns the number of bytes that would have been written if truncation did
407 // not occur. In the event of an error, a negative value is returned and `errno`
408 // is set.
409 //
410 // Example:
411 //
412 //   std::string_view s = "Ulaanbaatar";
413 //   char output[128];
414 //   absl::SNPrintF(output, sizeof(output),
415 //                  "The capital of Mongolia is %s", s);
416 //
417 //   Post-condition: output == "The capital of Mongolia is Ulaanbaatar"
418 //
419 template <typename... Args>
SNPrintF(char * output,std::size_t size,const FormatSpec<Args...> & format,const Args &...args)420 int SNPrintF(char* output, std::size_t size, const FormatSpec<Args...>& format,
421              const Args&... args) {
422   return str_format_internal::SnprintF(
423       output, size, str_format_internal::UntypedFormatSpecImpl::Extract(format),
424       {str_format_internal::FormatArgImpl(args)...});
425 }
426 
427 // -----------------------------------------------------------------------------
428 // Custom Output Formatting Functions
429 // -----------------------------------------------------------------------------
430 
431 // FormatRawSink
432 //
433 // FormatRawSink is a type erased wrapper around arbitrary sink objects
434 // specifically used as an argument to `Format()`.
435 // FormatRawSink does not own the passed sink object. The passed object must
436 // outlive the FormatRawSink.
437 class FormatRawSink {
438  public:
439   // Implicitly convert from any type that provides the hook function as
440   // described above.
441   template <typename T,
442             typename = typename std::enable_if<std::is_constructible<
443                 str_format_internal::FormatRawSinkImpl, T*>::value>::type>
FormatRawSink(T * raw)444   FormatRawSink(T* raw)  // NOLINT
445       : sink_(raw) {}
446 
447  private:
448   friend str_format_internal::FormatRawSinkImpl;
449   str_format_internal::FormatRawSinkImpl sink_;
450 };
451 
452 // Format()
453 //
454 // Writes a formatted string to an arbitrary sink object (implementing the
455 // `absl::FormatRawSink` interface), using a format string and zero or more
456 // additional arguments.
457 //
458 // By default, `std::string` and `std::ostream` are supported as destination
459 // objects. If a `std::string` is used the formatted string is appended to it.
460 //
461 // `absl::Format()` is a generic version of `absl::StrFormat(), for custom
462 // sinks. The format string, like format strings for `StrFormat()`, is checked
463 // at compile-time.
464 //
465 // On failure, this function returns `false` and the state of the sink is
466 // unspecified.
467 template <typename... Args>
Format(FormatRawSink raw_sink,const FormatSpec<Args...> & format,const Args &...args)468 bool Format(FormatRawSink raw_sink, const FormatSpec<Args...>& format,
469             const Args&... args) {
470   return str_format_internal::FormatUntyped(
471       str_format_internal::FormatRawSinkImpl::Extract(raw_sink),
472       str_format_internal::UntypedFormatSpecImpl::Extract(format),
473       {str_format_internal::FormatArgImpl(args)...});
474 }
475 
476 // FormatArg
477 //
478 // A type-erased handle to a format argument specifically used as an argument to
479 // `FormatUntyped()`. You may construct `FormatArg` by passing
480 // reference-to-const of any printable type. `FormatArg` is both copyable and
481 // assignable. The source data must outlive the `FormatArg` instance. See
482 // example below.
483 //
484 using FormatArg = str_format_internal::FormatArgImpl;
485 
486 // FormatUntyped()
487 //
488 // Writes a formatted string to an arbitrary sink object (implementing the
489 // `absl::FormatRawSink` interface), using an `UntypedFormatSpec` and zero or
490 // more additional arguments.
491 //
492 // This function acts as the most generic formatting function in the
493 // `str_format` library. The caller provides a raw sink, an unchecked format
494 // string, and (usually) a runtime specified list of arguments; no compile-time
495 // checking of formatting is performed within this function. As a result, a
496 // caller should check the return value to verify that no error occurred.
497 // On failure, this function returns `false` and the state of the sink is
498 // unspecified.
499 //
500 // The arguments are provided in an `absl::Span<const absl::FormatArg>`.
501 // Each `absl::FormatArg` object binds to a single argument and keeps a
502 // reference to it. The values used to create the `FormatArg` objects must
503 // outlive this function call. (See `str_format_arg.h` for information on
504 // the `FormatArg` class.)_
505 //
506 // Example:
507 //
508 //   std::optional<std::string> FormatDynamic(
509 //       const std::string& in_format,
510 //       const vector<std::string>& in_args) {
511 //     std::string out;
512 //     std::vector<absl::FormatArg> args;
513 //     for (const auto& v : in_args) {
514 //       // It is important that 'v' is a reference to the objects in in_args.
515 //       // The values we pass to FormatArg must outlive the call to
516 //       // FormatUntyped.
517 //       args.emplace_back(v);
518 //     }
519 //     absl::UntypedFormatSpec format(in_format);
520 //     if (!absl::FormatUntyped(&out, format, args)) {
521 //       return std::nullopt;
522 //     }
523 //     return std::move(out);
524 //   }
525 //
FormatUntyped(FormatRawSink raw_sink,const UntypedFormatSpec & format,absl::Span<const FormatArg> args)526 ABSL_MUST_USE_RESULT inline bool FormatUntyped(
527     FormatRawSink raw_sink, const UntypedFormatSpec& format,
528     absl::Span<const FormatArg> args) {
529   return str_format_internal::FormatUntyped(
530       str_format_internal::FormatRawSinkImpl::Extract(raw_sink),
531       str_format_internal::UntypedFormatSpecImpl::Extract(format), args);
532 }
533 
534 ABSL_NAMESPACE_END
535 }  // namespace absl
536 
537 #endif  // ABSL_STRINGS_STR_FORMAT_H_
538