str_format.h
Go to the documentation of this file.
00001 //
00002 // Copyright 2018 The Abseil Authors.
00003 //
00004 // Licensed under the Apache License, Version 2.0 (the "License");
00005 // you may not use this file except in compliance with the License.
00006 // You may obtain a copy of the License at
00007 //
00008 //      https://www.apache.org/licenses/LICENSE-2.0
00009 //
00010 // Unless required by applicable law or agreed to in writing, software
00011 // distributed under the License is distributed on an "AS IS" BASIS,
00012 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013 // See the License for the specific language governing permissions and
00014 // limitations under the License.
00015 //
00016 // -----------------------------------------------------------------------------
00017 // File: str_format.h
00018 // -----------------------------------------------------------------------------
00019 //
00020 // The `str_format` library is a typesafe replacement for the family of
00021 // `printf()` string formatting routines within the `<cstdio>` standard library
00022 // header. Like the `printf` family, the `str_format` uses a "format string" to
00023 // perform argument substitutions based on types.
00024 //
00025 // Example:
00026 //
00027 //   std::string s = absl::StrFormat(
00028 //                      "%s %s You have $%d!", "Hello", name, dollars);
00029 //
00030 // The library consists of the following basic utilities:
00031 //
00032 //   * `absl::StrFormat()`, a type-safe replacement for `std::sprintf()`, to
00033 //     write a format string to a `string` value.
00034 //   * `absl::StrAppendFormat()` to append a format string to a `string`
00035 //   * `absl::StreamFormat()` to more efficiently write a format string to a
00036 //     stream, such as`std::cout`.
00037 //   * `absl::PrintF()`, `absl::FPrintF()` and `absl::SNPrintF()` as
00038 //     replacements for `std::printf()`, `std::fprintf()` and `std::snprintf()`.
00039 //
00040 //     Note: a version of `std::sprintf()` is not supported as it is
00041 //     generally unsafe due to buffer overflows.
00042 //
00043 // Additionally, you can provide a format string (and its associated arguments)
00044 // using one of the following abstractions:
00045 //
00046 //   * A `FormatSpec` class template fully encapsulates a format string and its
00047 //     type arguments and is usually provided to `str_format` functions as a
00048 //     variadic argument of type `FormatSpec<Arg...>`. The `FormatSpec<Args...>`
00049 //     template is evaluated at compile-time, providing type safety.
00050 //   * A `ParsedFormat` instance, which encapsulates a specific, pre-compiled
00051 //     format string for a specific set of type(s), and which can be passed
00052 //     between API boundaries. (The `FormatSpec` type should not be used
00053 //     directly except as an argument type for wrapper functions.)
00054 //
00055 // The `str_format` library provides the ability to output its format strings to
00056 // arbitrary sink types:
00057 //
00058 //   * A generic `Format()` function to write outputs to arbitrary sink types,
00059 //     which must implement a `RawSinkFormat` interface. (See
00060 //     `str_format_sink.h` for more information.)
00061 //
00062 //   * A `FormatUntyped()` function that is similar to `Format()` except it is
00063 //     loosely typed. `FormatUntyped()` is not a template and does not perform
00064 //     any compile-time checking of the format string; instead, it returns a
00065 //     boolean from a runtime check.
00066 //
00067 // In addition, the `str_format` library provides extension points for
00068 // augmenting formatting to new types. These extensions are fully documented
00069 // within the `str_format_extension.h` header file.
00070 #ifndef ABSL_STRINGS_STR_FORMAT_H_
00071 #define ABSL_STRINGS_STR_FORMAT_H_
00072 
00073 #include <cstdio>
00074 #include <string>
00075 
00076 #include "absl/strings/internal/str_format/arg.h"  // IWYU pragma: export
00077 #include "absl/strings/internal/str_format/bind.h"  // IWYU pragma: export
00078 #include "absl/strings/internal/str_format/checker.h"  // IWYU pragma: export
00079 #include "absl/strings/internal/str_format/extension.h"  // IWYU pragma: export
00080 #include "absl/strings/internal/str_format/parser.h"  // IWYU pragma: export
00081 
00082 namespace absl {
00083 
00084 // UntypedFormatSpec
00085 //
00086 // A type-erased class that can be used directly within untyped API entry
00087 // points. An `UntypedFormatSpec` is specifically used as an argument to
00088 // `FormatUntyped()`.
00089 //
00090 // Example:
00091 //
00092 //   absl::UntypedFormatSpec format("%d");
00093 //   std::string out;
00094 //   CHECK(absl::FormatUntyped(&out, format, {absl::FormatArg(1)}));
00095 class UntypedFormatSpec {
00096  public:
00097   UntypedFormatSpec() = delete;
00098   UntypedFormatSpec(const UntypedFormatSpec&) = delete;
00099   UntypedFormatSpec& operator=(const UntypedFormatSpec&) = delete;
00100 
00101   explicit UntypedFormatSpec(string_view s) : spec_(s) {}
00102 
00103  protected:
00104   explicit UntypedFormatSpec(const str_format_internal::ParsedFormatBase* pc)
00105       : spec_(pc) {}
00106 
00107  private:
00108   friend str_format_internal::UntypedFormatSpecImpl;
00109   str_format_internal::UntypedFormatSpecImpl spec_;
00110 };
00111 
00112 // FormatStreamed()
00113 //
00114 // Takes a streamable argument and returns an object that can print it
00115 // with '%s'. Allows printing of types that have an `operator<<` but no
00116 // intrinsic type support within `StrFormat()` itself.
00117 //
00118 // Example:
00119 //
00120 //   absl::StrFormat("%s", absl::FormatStreamed(obj));
00121 template <typename T>
00122 str_format_internal::StreamedWrapper<T> FormatStreamed(const T& v) {
00123   return str_format_internal::StreamedWrapper<T>(v);
00124 }
00125 
00126 // FormatCountCapture
00127 //
00128 // This class provides a way to safely wrap `StrFormat()` captures of `%n`
00129 // conversions, which denote the number of characters written by a formatting
00130 // operation to this point, into an integer value.
00131 //
00132 // This wrapper is designed to allow safe usage of `%n` within `StrFormat(); in
00133 // the `printf()` family of functions, `%n` is not safe to use, as the `int *`
00134 // buffer can be used to capture arbitrary data.
00135 //
00136 // Example:
00137 //
00138 //   int n = 0;
00139 //   std::string s = absl::StrFormat("%s%d%n", "hello", 123,
00140 //                       absl::FormatCountCapture(&n));
00141 //   EXPECT_EQ(8, n);
00142 class FormatCountCapture {
00143  public:
00144   explicit FormatCountCapture(int* p) : p_(p) {}
00145 
00146  private:
00147   // FormatCountCaptureHelper is used to define FormatConvertImpl() for this
00148   // class.
00149   friend struct str_format_internal::FormatCountCaptureHelper;
00150   // Unused() is here because of the false positive from -Wunused-private-field
00151   // p_ is used in the templated function of the friend FormatCountCaptureHelper
00152   // class.
00153   int* Unused() { return p_; }
00154   int* p_;
00155 };
00156 
00157 // FormatSpec
00158 //
00159 // The `FormatSpec` type defines the makeup of a format string within the
00160 // `str_format` library. It is a variadic class template that is evaluated at
00161 // compile-time, according to the format string and arguments that are passed to
00162 // it.
00163 //
00164 // You should not need to manipulate this type directly. You should only name it
00165 // if you are writing wrapper functions which accept format arguments that will
00166 // be provided unmodified to functions in this library. Such a wrapper function
00167 // might be a class method that provides format arguments and/or internally uses
00168 // the result of formatting.
00169 //
00170 // For a `FormatSpec` to be valid at compile-time, it must be provided as
00171 // either:
00172 //
00173 // * A `constexpr` literal or `absl::string_view`, which is how it most often
00174 //   used.
00175 // * A `ParsedFormat` instantiation, which ensures the format string is
00176 //   valid before use. (See below.)
00177 //
00178 // Example:
00179 //
00180 //   // Provided as a string literal.
00181 //   absl::StrFormat("Welcome to %s, Number %d!", "The Village", 6);
00182 //
00183 //   // Provided as a constexpr absl::string_view.
00184 //   constexpr absl::string_view formatString = "Welcome to %s, Number %d!";
00185 //   absl::StrFormat(formatString, "The Village", 6);
00186 //
00187 //   // Provided as a pre-compiled ParsedFormat object.
00188 //   // Note that this example is useful only for illustration purposes.
00189 //   absl::ParsedFormat<'s', 'd'> formatString("Welcome to %s, Number %d!");
00190 //   absl::StrFormat(formatString, "TheVillage", 6);
00191 //
00192 // A format string generally follows the POSIX syntax as used within the POSIX
00193 // `printf` specification.
00194 //
00195 // (See http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html.)
00196 //
00197 // In specific, the `FormatSpec` supports the following type specifiers:
00198 //   * `c` for characters
00199 //   * `s` for strings
00200 //   * `d` or `i` for integers
00201 //   * `o` for unsigned integer conversions into octal
00202 //   * `x` or `X` for unsigned integer conversions into hex
00203 //   * `u` for unsigned integers
00204 //   * `f` or `F` for floating point values into decimal notation
00205 //   * `e` or `E` for floating point values into exponential notation
00206 //   * `a` or `A` for floating point values into hex exponential notation
00207 //   * `g` or `G` for floating point values into decimal or exponential
00208 //     notation based on their precision
00209 //   * `p` for pointer address values
00210 //   * `n` for the special case of writing out the number of characters
00211 //     written to this point. The resulting value must be captured within an
00212 //     `absl::FormatCountCapture` type.
00213 //
00214 // NOTE: `o`, `x\X` and `u` will convert signed values to their unsigned
00215 // counterpart before formatting.
00216 //
00217 // Examples:
00218 //     "%c", 'a'                -> "a"
00219 //     "%c", 32                 -> " "
00220 //     "%s", "C"                -> "C"
00221 //     "%s", std::string("C++") -> "C++"
00222 //     "%d", -10                -> "-10"
00223 //     "%o", 10                 -> "12"
00224 //     "%x", 16                 -> "10"
00225 //     "%f", 123456789          -> "123456789.000000"
00226 //     "%e", .01                -> "1.00000e-2"
00227 //     "%a", -3.0               -> "-0x1.8p+1"
00228 //     "%g", .01                -> "1e-2"
00229 //     "%p", *int               -> "0x7ffdeb6ad2a4"
00230 //
00231 //     int n = 0;
00232 //     std::string s = absl::StrFormat(
00233 //         "%s%d%n", "hello", 123, absl::FormatCountCapture(&n));
00234 //     EXPECT_EQ(8, n);
00235 //
00236 // The `FormatSpec` intrinsically supports all of these fundamental C++ types:
00237 //
00238 // *   Characters: `char`, `signed char`, `unsigned char`
00239 // *   Integers: `int`, `short`, `unsigned short`, `unsigned`, `long`,
00240 //         `unsigned long`, `long long`, `unsigned long long`
00241 // *   Floating-point: `float`, `double`, `long double`
00242 //
00243 // However, in the `str_format` library, a format conversion specifies a broader
00244 // C++ conceptual category instead of an exact type. For example, `%s` binds to
00245 // any string-like argument, so `std::string`, `absl::string_view`, and
00246 // `const char*` are all accepted. Likewise, `%d` accepts any integer-like
00247 // argument, etc.
00248 
00249 template <typename... Args>
00250 using FormatSpec =
00251     typename str_format_internal::FormatSpecDeductionBarrier<Args...>::type;
00252 
00253 // ParsedFormat
00254 //
00255 // A `ParsedFormat` is a class template representing a preparsed `FormatSpec`,
00256 // with template arguments specifying the conversion characters used within the
00257 // format string. Such characters must be valid format type specifiers, and
00258 // these type specifiers are checked at compile-time.
00259 //
00260 // Instances of `ParsedFormat` can be created, copied, and reused to speed up
00261 // formatting loops. A `ParsedFormat` may either be constructed statically, or
00262 // dynamically through its `New()` factory function, which only constructs a
00263 // runtime object if the format is valid at that time.
00264 //
00265 // Example:
00266 //
00267 //   // Verified at compile time.
00268 //   absl::ParsedFormat<'s', 'd'> formatString("Welcome to %s, Number %d!");
00269 //   absl::StrFormat(formatString, "TheVillage", 6);
00270 //
00271 //   // Verified at runtime.
00272 //   auto format_runtime = absl::ParsedFormat<'d'>::New(format_string);
00273 //   if (format_runtime) {
00274 //     value = absl::StrFormat(*format_runtime, i);
00275 //   } else {
00276 //     ... error case ...
00277 //   }
00278 template <char... Conv>
00279 using ParsedFormat = str_format_internal::ExtendedParsedFormat<
00280     str_format_internal::ConversionCharToConv(Conv)...>;
00281 
00282 // StrFormat()
00283 //
00284 // Returns a `string` given a `printf()`-style format string and zero or more
00285 // additional arguments. Use it as you would `sprintf()`. `StrFormat()` is the
00286 // primary formatting function within the `str_format` library, and should be
00287 // used in most cases where you need type-safe conversion of types into
00288 // formatted strings.
00289 //
00290 // The format string generally consists of ordinary character data along with
00291 // one or more format conversion specifiers (denoted by the `%` character).
00292 // Ordinary character data is returned unchanged into the result string, while
00293 // each conversion specification performs a type substitution from
00294 // `StrFormat()`'s other arguments. See the comments for `FormatSpec` for full
00295 // information on the makeup of this format string.
00296 //
00297 // Example:
00298 //
00299 //   std::string s = absl::StrFormat(
00300 //       "Welcome to %s, Number %d!", "The Village", 6);
00301 //   EXPECT_EQ("Welcome to The Village, Number 6!", s);
00302 //
00303 // Returns an empty string in case of error.
00304 template <typename... Args>
00305 ABSL_MUST_USE_RESULT std::string StrFormat(const FormatSpec<Args...>& format,
00306                                            const Args&... args) {
00307   return str_format_internal::FormatPack(
00308       str_format_internal::UntypedFormatSpecImpl::Extract(format),
00309       {str_format_internal::FormatArgImpl(args)...});
00310 }
00311 
00312 // StrAppendFormat()
00313 //
00314 // Appends to a `dst` string given a format string, and zero or more additional
00315 // arguments, returning `*dst` as a convenience for chaining purposes. Appends
00316 // nothing in case of error (but possibly alters its capacity).
00317 //
00318 // Example:
00319 //
00320 //   std::string orig("For example PI is approximately ");
00321 //   std::cout << StrAppendFormat(&orig, "%12.6f", 3.14);
00322 template <typename... Args>
00323 std::string& StrAppendFormat(std::string* dst,
00324                              const FormatSpec<Args...>& format,
00325                              const Args&... args) {
00326   return str_format_internal::AppendPack(
00327       dst, str_format_internal::UntypedFormatSpecImpl::Extract(format),
00328       {str_format_internal::FormatArgImpl(args)...});
00329 }
00330 
00331 // StreamFormat()
00332 //
00333 // Writes to an output stream given a format string and zero or more arguments,
00334 // generally in a manner that is more efficient than streaming the result of
00335 // `absl:: StrFormat()`. The returned object must be streamed before the full
00336 // expression ends.
00337 //
00338 // Example:
00339 //
00340 //   std::cout << StreamFormat("%12.6f", 3.14);
00341 template <typename... Args>
00342 ABSL_MUST_USE_RESULT str_format_internal::Streamable StreamFormat(
00343     const FormatSpec<Args...>& format, const Args&... args) {
00344   return str_format_internal::Streamable(
00345       str_format_internal::UntypedFormatSpecImpl::Extract(format),
00346       {str_format_internal::FormatArgImpl(args)...});
00347 }
00348 
00349 // PrintF()
00350 //
00351 // Writes to stdout given a format string and zero or more arguments. This
00352 // function is functionally equivalent to `std::printf()` (and type-safe);
00353 // prefer `absl::PrintF()` over `std::printf()`.
00354 //
00355 // Example:
00356 //
00357 //   std::string_view s = "Ulaanbaatar";
00358 //   absl::PrintF("The capital of Mongolia is %s", s);
00359 //
00360 //   Outputs: "The capital of Mongolia is Ulaanbaatar"
00361 //
00362 template <typename... Args>
00363 int PrintF(const FormatSpec<Args...>& format, const Args&... args) {
00364   return str_format_internal::FprintF(
00365       stdout, str_format_internal::UntypedFormatSpecImpl::Extract(format),
00366       {str_format_internal::FormatArgImpl(args)...});
00367 }
00368 
00369 // FPrintF()
00370 //
00371 // Writes to a file given a format string and zero or more arguments. This
00372 // function is functionally equivalent to `std::fprintf()` (and type-safe);
00373 // prefer `absl::FPrintF()` over `std::fprintf()`.
00374 //
00375 // Example:
00376 //
00377 //   std::string_view s = "Ulaanbaatar";
00378 //   absl::FPrintF(stdout, "The capital of Mongolia is %s", s);
00379 //
00380 //   Outputs: "The capital of Mongolia is Ulaanbaatar"
00381 //
00382 template <typename... Args>
00383 int FPrintF(std::FILE* output, const FormatSpec<Args...>& format,
00384             const Args&... args) {
00385   return str_format_internal::FprintF(
00386       output, str_format_internal::UntypedFormatSpecImpl::Extract(format),
00387       {str_format_internal::FormatArgImpl(args)...});
00388 }
00389 
00390 // SNPrintF()
00391 //
00392 // Writes to a sized buffer given a format string and zero or more arguments.
00393 // This function is functionally equivalent to `std::snprintf()` (and
00394 // type-safe); prefer `absl::SNPrintF()` over `std::snprintf()`.
00395 //
00396 // Example:
00397 //
00398 //   std::string_view s = "Ulaanbaatar";
00399 //   char output[128];
00400 //   absl::SNPrintF(output, sizeof(output),
00401 //                  "The capital of Mongolia is %s", s);
00402 //
00403 //   Post-condition: output == "The capital of Mongolia is Ulaanbaatar"
00404 //
00405 template <typename... Args>
00406 int SNPrintF(char* output, std::size_t size, const FormatSpec<Args...>& format,
00407              const Args&... args) {
00408   return str_format_internal::SnprintF(
00409       output, size, str_format_internal::UntypedFormatSpecImpl::Extract(format),
00410       {str_format_internal::FormatArgImpl(args)...});
00411 }
00412 
00413 // -----------------------------------------------------------------------------
00414 // Custom Output Formatting Functions
00415 // -----------------------------------------------------------------------------
00416 
00417 // FormatRawSink
00418 //
00419 // FormatRawSink is a type erased wrapper around arbitrary sink objects
00420 // specifically used as an argument to `Format()`.
00421 // FormatRawSink does not own the passed sink object. The passed object must
00422 // outlive the FormatRawSink.
00423 class FormatRawSink {
00424  public:
00425   // Implicitly convert from any type that provides the hook function as
00426   // described above.
00427   template <typename T,
00428             typename = typename std::enable_if<std::is_constructible<
00429                 str_format_internal::FormatRawSinkImpl, T*>::value>::type>
00430   FormatRawSink(T* raw)  // NOLINT
00431       : sink_(raw) {}
00432 
00433  private:
00434   friend str_format_internal::FormatRawSinkImpl;
00435   str_format_internal::FormatRawSinkImpl sink_;
00436 };
00437 
00438 // Format()
00439 //
00440 // Writes a formatted string to an arbitrary sink object (implementing the
00441 // `absl::FormatRawSink` interface), using a format string and zero or more
00442 // additional arguments.
00443 //
00444 // By default, `std::string` and `std::ostream` are supported as destination
00445 // objects.
00446 //
00447 // `absl::Format()` is a generic version of `absl::StrFormat(), for custom
00448 // sinks. The format string, like format strings for `StrFormat()`, is checked
00449 // at compile-time.
00450 //
00451 // On failure, this function returns `false` and the state of the sink is
00452 // unspecified.
00453 template <typename... Args>
00454 bool Format(FormatRawSink raw_sink, const FormatSpec<Args...>& format,
00455             const Args&... args) {
00456   return str_format_internal::FormatUntyped(
00457       str_format_internal::FormatRawSinkImpl::Extract(raw_sink),
00458       str_format_internal::UntypedFormatSpecImpl::Extract(format),
00459       {str_format_internal::FormatArgImpl(args)...});
00460 }
00461 
00462 // FormatArg
00463 //
00464 // A type-erased handle to a format argument specifically used as an argument to
00465 // `FormatUntyped()`. You may construct `FormatArg` by passing
00466 // reference-to-const of any printable type. `FormatArg` is both copyable and
00467 // assignable. The source data must outlive the `FormatArg` instance. See
00468 // example below.
00469 //
00470 using FormatArg = str_format_internal::FormatArgImpl;
00471 
00472 // FormatUntyped()
00473 //
00474 // Writes a formatted string to an arbitrary sink object (implementing the
00475 // `absl::FormatRawSink` interface), using an `UntypedFormatSpec` and zero or
00476 // more additional arguments.
00477 //
00478 // This function acts as the most generic formatting function in the
00479 // `str_format` library. The caller provides a raw sink, an unchecked format
00480 // string, and (usually) a runtime specified list of arguments; no compile-time
00481 // checking of formatting is performed within this function. As a result, a
00482 // caller should check the return value to verify that no error occurred.
00483 // On failure, this function returns `false` and the state of the sink is
00484 // unspecified.
00485 //
00486 // The arguments are provided in an `absl::Span<const absl::FormatArg>`.
00487 // Each `absl::FormatArg` object binds to a single argument and keeps a
00488 // reference to it. The values used to create the `FormatArg` objects must
00489 // outlive this function call. (See `str_format_arg.h` for information on
00490 // the `FormatArg` class.)_
00491 //
00492 // Example:
00493 //
00494 //   std::optional<std::string> FormatDynamic(
00495 //       const std::string& in_format,
00496 //       const vector<std::string>& in_args) {
00497 //     std::string out;
00498 //     std::vector<absl::FormatArg> args;
00499 //     for (const auto& v : in_args) {
00500 //       // It is important that 'v' is a reference to the objects in in_args.
00501 //       // The values we pass to FormatArg must outlive the call to
00502 //       // FormatUntyped.
00503 //       args.emplace_back(v);
00504 //     }
00505 //     absl::UntypedFormatSpec format(in_format);
00506 //     if (!absl::FormatUntyped(&out, format, args)) {
00507 //       return std::nullopt;
00508 //     }
00509 //     return std::move(out);
00510 //   }
00511 //
00512 ABSL_MUST_USE_RESULT inline bool FormatUntyped(
00513     FormatRawSink raw_sink, const UntypedFormatSpec& format,
00514     absl::Span<const FormatArg> args) {
00515   return str_format_internal::FormatUntyped(
00516       str_format_internal::FormatRawSinkImpl::Extract(raw_sink),
00517       str_format_internal::UntypedFormatSpecImpl::Extract(format), args);
00518 }
00519 
00520 }  // namespace absl
00521 
00522 #endif  // ABSL_STRINGS_STR_FORMAT_H_


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