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