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