2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// Copyright 2018 The Abseil Authors.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
2019-03-08 16:27:53 +01:00
|
|
|
// https://www.apache.org/licenses/LICENSE-2.0
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
//
|
|
|
|
// -----------------------------------------------------------------------------
|
|
|
|
// File: str_format.h
|
|
|
|
// -----------------------------------------------------------------------------
|
|
|
|
//
|
|
|
|
// The `str_format` library is a typesafe replacement for the family of
|
2018-08-21 20:31:02 +02:00
|
|
|
// `printf()` string formatting routines within the `<cstdio>` standard library
|
2020-06-17 15:53:10 +02:00
|
|
|
// header. Like the `printf` family, `str_format` uses a "format string" to
|
2019-06-13 18:14:42 +02:00
|
|
|
// perform argument substitutions based on types. See the `FormatSpec` section
|
|
|
|
// below for format string documentation.
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
2019-03-06 20:36:55 +01:00
|
|
|
// std::string s = absl::StrFormat(
|
|
|
|
// "%s %s You have $%d!", "Hello", name, dollars);
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// The library consists of the following basic utilities:
|
|
|
|
//
|
|
|
|
// * `absl::StrFormat()`, a type-safe replacement for `std::sprintf()`, to
|
2018-08-21 20:31:02 +02:00
|
|
|
// write a format string to a `string` value.
|
|
|
|
// * `absl::StrAppendFormat()` to append a format string to a `string`
|
|
|
|
// * `absl::StreamFormat()` to more efficiently write a format string to a
|
2018-06-21 21:55:12 +02:00
|
|
|
// stream, such as`std::cout`.
|
|
|
|
// * `absl::PrintF()`, `absl::FPrintF()` and `absl::SNPrintF()` as
|
|
|
|
// replacements for `std::printf()`, `std::fprintf()` and `std::snprintf()`.
|
|
|
|
//
|
|
|
|
// Note: a version of `std::sprintf()` is not supported as it is
|
|
|
|
// generally unsafe due to buffer overflows.
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// Additionally, you can provide a format string (and its associated arguments)
|
2018-06-21 21:55:12 +02:00
|
|
|
// using one of the following abstractions:
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// * A `FormatSpec` class template fully encapsulates a format string and its
|
2018-06-21 21:55:12 +02:00
|
|
|
// type arguments and is usually provided to `str_format` functions as a
|
|
|
|
// variadic argument of type `FormatSpec<Arg...>`. The `FormatSpec<Args...>`
|
|
|
|
// template is evaluated at compile-time, providing type safety.
|
|
|
|
// * A `ParsedFormat` instance, which encapsulates a specific, pre-compiled
|
2018-08-21 20:31:02 +02:00
|
|
|
// format string for a specific set of type(s), and which can be passed
|
2018-06-21 21:55:12 +02:00
|
|
|
// between API boundaries. (The `FormatSpec` type should not be used
|
2019-05-10 21:38:49 +02:00
|
|
|
// directly except as an argument type for wrapper functions.)
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// The `str_format` library provides the ability to output its format strings to
|
|
|
|
// arbitrary sink types:
|
|
|
|
//
|
|
|
|
// * A generic `Format()` function to write outputs to arbitrary sink types,
|
2020-04-17 17:13:06 +02:00
|
|
|
// which must implement a `FormatRawSink` interface.
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// * A `FormatUntyped()` function that is similar to `Format()` except it is
|
|
|
|
// loosely typed. `FormatUntyped()` is not a template and does not perform
|
2018-08-21 20:31:02 +02:00
|
|
|
// any compile-time checking of the format string; instead, it returns a
|
2018-06-21 21:55:12 +02:00
|
|
|
// boolean from a runtime check.
|
2020-11-21 14:43:54 +01:00
|
|
|
//
|
|
|
|
// In addition, the `str_format` library provides extension points for
|
|
|
|
// augmenting formatting to new types. See "StrFormat Extensions" below.
|
2019-06-13 18:14:42 +02:00
|
|
|
|
2018-06-21 21:55:12 +02:00
|
|
|
#ifndef ABSL_STRINGS_STR_FORMAT_H_
|
|
|
|
#define ABSL_STRINGS_STR_FORMAT_H_
|
|
|
|
|
|
|
|
#include <cstdio>
|
|
|
|
#include <string>
|
|
|
|
|
|
|
|
#include "absl/strings/internal/str_format/arg.h" // IWYU pragma: export
|
|
|
|
#include "absl/strings/internal/str_format/bind.h" // IWYU pragma: export
|
|
|
|
#include "absl/strings/internal/str_format/checker.h" // IWYU pragma: export
|
|
|
|
#include "absl/strings/internal/str_format/extension.h" // IWYU pragma: export
|
|
|
|
#include "absl/strings/internal/str_format/parser.h" // IWYU pragma: export
|
|
|
|
|
|
|
|
namespace absl {
|
2019-12-12 19:36:03 +01:00
|
|
|
ABSL_NAMESPACE_BEGIN
|
2018-06-21 21:55:12 +02:00
|
|
|
|
|
|
|
// UntypedFormatSpec
|
|
|
|
//
|
|
|
|
// A type-erased class that can be used directly within untyped API entry
|
|
|
|
// points. An `UntypedFormatSpec` is specifically used as an argument to
|
|
|
|
// `FormatUntyped()`.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// absl::UntypedFormatSpec format("%d");
|
2019-03-06 20:36:55 +01:00
|
|
|
// std::string out;
|
2018-06-21 21:55:12 +02:00
|
|
|
// CHECK(absl::FormatUntyped(&out, format, {absl::FormatArg(1)}));
|
|
|
|
class UntypedFormatSpec {
|
|
|
|
public:
|
|
|
|
UntypedFormatSpec() = delete;
|
|
|
|
UntypedFormatSpec(const UntypedFormatSpec&) = delete;
|
|
|
|
UntypedFormatSpec& operator=(const UntypedFormatSpec&) = delete;
|
|
|
|
|
|
|
|
explicit UntypedFormatSpec(string_view s) : spec_(s) {}
|
|
|
|
|
|
|
|
protected:
|
|
|
|
explicit UntypedFormatSpec(const str_format_internal::ParsedFormatBase* pc)
|
|
|
|
: spec_(pc) {}
|
|
|
|
|
|
|
|
private:
|
|
|
|
friend str_format_internal::UntypedFormatSpecImpl;
|
|
|
|
str_format_internal::UntypedFormatSpecImpl spec_;
|
|
|
|
};
|
|
|
|
|
|
|
|
// FormatStreamed()
|
|
|
|
//
|
|
|
|
// Takes a streamable argument and returns an object that can print it
|
|
|
|
// with '%s'. Allows printing of types that have an `operator<<` but no
|
|
|
|
// intrinsic type support within `StrFormat()` itself.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// absl::StrFormat("%s", absl::FormatStreamed(obj));
|
|
|
|
template <typename T>
|
|
|
|
str_format_internal::StreamedWrapper<T> FormatStreamed(const T& v) {
|
|
|
|
return str_format_internal::StreamedWrapper<T>(v);
|
|
|
|
}
|
|
|
|
|
|
|
|
// FormatCountCapture
|
|
|
|
//
|
|
|
|
// This class provides a way to safely wrap `StrFormat()` captures of `%n`
|
|
|
|
// conversions, which denote the number of characters written by a formatting
|
|
|
|
// operation to this point, into an integer value.
|
|
|
|
//
|
|
|
|
// This wrapper is designed to allow safe usage of `%n` within `StrFormat(); in
|
|
|
|
// the `printf()` family of functions, `%n` is not safe to use, as the `int *`
|
|
|
|
// buffer can be used to capture arbitrary data.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// int n = 0;
|
2019-03-06 20:36:55 +01:00
|
|
|
// std::string s = absl::StrFormat("%s%d%n", "hello", 123,
|
|
|
|
// absl::FormatCountCapture(&n));
|
2018-06-21 21:55:12 +02:00
|
|
|
// EXPECT_EQ(8, n);
|
|
|
|
class FormatCountCapture {
|
|
|
|
public:
|
|
|
|
explicit FormatCountCapture(int* p) : p_(p) {}
|
|
|
|
|
|
|
|
private:
|
|
|
|
// FormatCountCaptureHelper is used to define FormatConvertImpl() for this
|
|
|
|
// class.
|
|
|
|
friend struct str_format_internal::FormatCountCaptureHelper;
|
|
|
|
// Unused() is here because of the false positive from -Wunused-private-field
|
|
|
|
// p_ is used in the templated function of the friend FormatCountCaptureHelper
|
|
|
|
// class.
|
|
|
|
int* Unused() { return p_; }
|
|
|
|
int* p_;
|
|
|
|
};
|
|
|
|
|
|
|
|
// FormatSpec
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// The `FormatSpec` type defines the makeup of a format string within the
|
2019-05-10 21:38:49 +02:00
|
|
|
// `str_format` library. It is a variadic class template that is evaluated at
|
|
|
|
// compile-time, according to the format string and arguments that are passed to
|
|
|
|
// it.
|
|
|
|
//
|
|
|
|
// You should not need to manipulate this type directly. You should only name it
|
|
|
|
// if you are writing wrapper functions which accept format arguments that will
|
|
|
|
// be provided unmodified to functions in this library. Such a wrapper function
|
|
|
|
// might be a class method that provides format arguments and/or internally uses
|
|
|
|
// the result of formatting.
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// For a `FormatSpec` to be valid at compile-time, it must be provided as
|
|
|
|
// either:
|
|
|
|
//
|
|
|
|
// * A `constexpr` literal or `absl::string_view`, which is how it most often
|
|
|
|
// used.
|
2018-08-21 20:31:02 +02:00
|
|
|
// * A `ParsedFormat` instantiation, which ensures the format string is
|
2018-06-21 21:55:12 +02:00
|
|
|
// valid before use. (See below.)
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// // Provided as a string literal.
|
2018-06-21 21:55:12 +02:00
|
|
|
// absl::StrFormat("Welcome to %s, Number %d!", "The Village", 6);
|
|
|
|
//
|
|
|
|
// // Provided as a constexpr absl::string_view.
|
|
|
|
// constexpr absl::string_view formatString = "Welcome to %s, Number %d!";
|
|
|
|
// absl::StrFormat(formatString, "The Village", 6);
|
|
|
|
//
|
|
|
|
// // Provided as a pre-compiled ParsedFormat object.
|
|
|
|
// // Note that this example is useful only for illustration purposes.
|
|
|
|
// absl::ParsedFormat<'s', 'd'> formatString("Welcome to %s, Number %d!");
|
|
|
|
// absl::StrFormat(formatString, "TheVillage", 6);
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// A format string generally follows the POSIX syntax as used within the POSIX
|
2018-06-21 21:55:12 +02:00
|
|
|
// `printf` specification.
|
|
|
|
//
|
2019-01-31 05:33:55 +01:00
|
|
|
// (See http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html.)
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// In specific, the `FormatSpec` supports the following type specifiers:
|
|
|
|
// * `c` for characters
|
|
|
|
// * `s` for strings
|
|
|
|
// * `d` or `i` for integers
|
|
|
|
// * `o` for unsigned integer conversions into octal
|
|
|
|
// * `x` or `X` for unsigned integer conversions into hex
|
|
|
|
// * `u` for unsigned integers
|
|
|
|
// * `f` or `F` for floating point values into decimal notation
|
|
|
|
// * `e` or `E` for floating point values into exponential notation
|
|
|
|
// * `a` or `A` for floating point values into hex exponential notation
|
|
|
|
// * `g` or `G` for floating point values into decimal or exponential
|
|
|
|
// notation based on their precision
|
|
|
|
// * `p` for pointer address values
|
|
|
|
// * `n` for the special case of writing out the number of characters
|
|
|
|
// written to this point. The resulting value must be captured within an
|
|
|
|
// `absl::FormatCountCapture` type.
|
|
|
|
//
|
2019-06-13 18:14:42 +02:00
|
|
|
// Implementation-defined behavior:
|
|
|
|
// * A null pointer provided to "%s" or "%p" is output as "(nil)".
|
|
|
|
// * A non-null pointer provided to "%p" is output in hex as if by %#x or
|
|
|
|
// %#lx.
|
|
|
|
//
|
2018-06-21 21:55:12 +02:00
|
|
|
// NOTE: `o`, `x\X` and `u` will convert signed values to their unsigned
|
|
|
|
// counterpart before formatting.
|
|
|
|
//
|
|
|
|
// Examples:
|
|
|
|
// "%c", 'a' -> "a"
|
|
|
|
// "%c", 32 -> " "
|
|
|
|
// "%s", "C" -> "C"
|
|
|
|
// "%s", std::string("C++") -> "C++"
|
|
|
|
// "%d", -10 -> "-10"
|
|
|
|
// "%o", 10 -> "12"
|
|
|
|
// "%x", 16 -> "10"
|
|
|
|
// "%f", 123456789 -> "123456789.000000"
|
|
|
|
// "%e", .01 -> "1.00000e-2"
|
|
|
|
// "%a", -3.0 -> "-0x1.8p+1"
|
|
|
|
// "%g", .01 -> "1e-2"
|
2019-06-13 18:14:42 +02:00
|
|
|
// "%p", (void*)&value -> "0x7ffdeb6ad2a4"
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// int n = 0;
|
2019-03-06 20:36:55 +01:00
|
|
|
// std::string s = absl::StrFormat(
|
2018-06-21 21:55:12 +02:00
|
|
|
// "%s%d%n", "hello", 123, absl::FormatCountCapture(&n));
|
|
|
|
// EXPECT_EQ(8, n);
|
|
|
|
//
|
|
|
|
// The `FormatSpec` intrinsically supports all of these fundamental C++ types:
|
|
|
|
//
|
|
|
|
// * Characters: `char`, `signed char`, `unsigned char`
|
|
|
|
// * Integers: `int`, `short`, `unsigned short`, `unsigned`, `long`,
|
|
|
|
// `unsigned long`, `long long`, `unsigned long long`
|
|
|
|
// * Floating-point: `float`, `double`, `long double`
|
|
|
|
//
|
|
|
|
// However, in the `str_format` library, a format conversion specifies a broader
|
|
|
|
// C++ conceptual category instead of an exact type. For example, `%s` binds to
|
2018-08-21 20:31:02 +02:00
|
|
|
// any string-like argument, so `std::string`, `absl::string_view`, and
|
2018-06-21 21:55:12 +02:00
|
|
|
// `const char*` are all accepted. Likewise, `%d` accepts any integer-like
|
|
|
|
// argument, etc.
|
|
|
|
|
|
|
|
template <typename... Args>
|
2020-04-24 15:12:31 +02:00
|
|
|
using FormatSpec = str_format_internal::FormatSpecTemplate<
|
|
|
|
str_format_internal::ArgumentToConv<Args>()...>;
|
2018-06-21 21:55:12 +02:00
|
|
|
|
|
|
|
// ParsedFormat
|
|
|
|
//
|
|
|
|
// A `ParsedFormat` is a class template representing a preparsed `FormatSpec`,
|
|
|
|
// with template arguments specifying the conversion characters used within the
|
2018-08-21 20:31:02 +02:00
|
|
|
// format string. Such characters must be valid format type specifiers, and
|
2018-06-21 21:55:12 +02:00
|
|
|
// these type specifiers are checked at compile-time.
|
|
|
|
//
|
|
|
|
// Instances of `ParsedFormat` can be created, copied, and reused to speed up
|
|
|
|
// formatting loops. A `ParsedFormat` may either be constructed statically, or
|
|
|
|
// dynamically through its `New()` factory function, which only constructs a
|
|
|
|
// runtime object if the format is valid at that time.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// // Verified at compile time.
|
|
|
|
// absl::ParsedFormat<'s', 'd'> formatString("Welcome to %s, Number %d!");
|
|
|
|
// absl::StrFormat(formatString, "TheVillage", 6);
|
|
|
|
//
|
|
|
|
// // Verified at runtime.
|
|
|
|
// auto format_runtime = absl::ParsedFormat<'d'>::New(format_string);
|
|
|
|
// if (format_runtime) {
|
|
|
|
// value = absl::StrFormat(*format_runtime, i);
|
|
|
|
// } else {
|
|
|
|
// ... error case ...
|
|
|
|
// }
|
2020-11-21 14:43:54 +01:00
|
|
|
|
|
|
|
#if defined(__cpp_nontype_template_parameter_auto)
|
|
|
|
// If C++17 is available, an 'extended' format is also allowed that can specify
|
|
|
|
// multiple conversion characters per format argument, using a combination of
|
|
|
|
// `absl::FormatConversionCharSet` enum values (logically a set union)
|
|
|
|
// via the `|` operator. (Single character-based arguments are still accepted,
|
|
|
|
// but cannot be combined). Some common conversions also have predefined enum
|
|
|
|
// values, such as `absl::FormatConversionCharSet::kIntegral`.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
// // Extended format supports multiple conversion characters per argument,
|
|
|
|
// // specified via a combination of `FormatConversionCharSet` enums.
|
|
|
|
// using MyFormat = absl::ParsedFormat<absl::FormatConversionCharSet::d |
|
|
|
|
// absl::FormatConversionCharSet::x>;
|
|
|
|
// MyFormat GetFormat(bool use_hex) {
|
|
|
|
// if (use_hex) return MyFormat("foo %x bar");
|
|
|
|
// return MyFormat("foo %d bar");
|
|
|
|
// }
|
|
|
|
// // `format` can be used with any value that supports 'd' and 'x',
|
|
|
|
// // like `int`.
|
|
|
|
// auto format = GetFormat(use_hex);
|
|
|
|
// value = StringF(format, i);
|
|
|
|
template <auto... Conv>
|
|
|
|
using ParsedFormat = absl::str_format_internal::ExtendedParsedFormat<
|
|
|
|
absl::str_format_internal::ToFormatConversionCharSet(Conv)...>;
|
|
|
|
#else
|
2018-06-21 21:55:12 +02:00
|
|
|
template <char... Conv>
|
|
|
|
using ParsedFormat = str_format_internal::ExtendedParsedFormat<
|
2020-03-16 17:06:23 +01:00
|
|
|
absl::str_format_internal::ToFormatConversionCharSet(Conv)...>;
|
2020-11-21 14:43:54 +01:00
|
|
|
#endif // defined(__cpp_nontype_template_parameter_auto)
|
2018-06-21 21:55:12 +02:00
|
|
|
|
|
|
|
// StrFormat()
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// Returns a `string` given a `printf()`-style format string and zero or more
|
2018-06-21 21:55:12 +02:00
|
|
|
// additional arguments. Use it as you would `sprintf()`. `StrFormat()` is the
|
|
|
|
// primary formatting function within the `str_format` library, and should be
|
|
|
|
// used in most cases where you need type-safe conversion of types into
|
|
|
|
// formatted strings.
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// The format string generally consists of ordinary character data along with
|
2018-06-21 21:55:12 +02:00
|
|
|
// one or more format conversion specifiers (denoted by the `%` character).
|
2018-08-21 20:31:02 +02:00
|
|
|
// Ordinary character data is returned unchanged into the result string, while
|
2018-06-21 21:55:12 +02:00
|
|
|
// each conversion specification performs a type substitution from
|
|
|
|
// `StrFormat()`'s other arguments. See the comments for `FormatSpec` for full
|
2018-08-21 20:31:02 +02:00
|
|
|
// information on the makeup of this format string.
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
2019-03-06 20:36:55 +01:00
|
|
|
// std::string s = absl::StrFormat(
|
2018-06-21 21:55:12 +02:00
|
|
|
// "Welcome to %s, Number %d!", "The Village", 6);
|
|
|
|
// EXPECT_EQ("Welcome to The Village, Number 6!", s);
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// Returns an empty string in case of error.
|
2018-06-21 21:55:12 +02:00
|
|
|
template <typename... Args>
|
|
|
|
ABSL_MUST_USE_RESULT std::string StrFormat(const FormatSpec<Args...>& format,
|
2019-03-06 20:36:55 +01:00
|
|
|
const Args&... args) {
|
2018-06-21 21:55:12 +02:00
|
|
|
return str_format_internal::FormatPack(
|
|
|
|
str_format_internal::UntypedFormatSpecImpl::Extract(format),
|
|
|
|
{str_format_internal::FormatArgImpl(args)...});
|
|
|
|
}
|
|
|
|
|
|
|
|
// StrAppendFormat()
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// Appends to a `dst` string given a format string, and zero or more additional
|
2018-06-21 21:55:12 +02:00
|
|
|
// arguments, returning `*dst` as a convenience for chaining purposes. Appends
|
|
|
|
// nothing in case of error (but possibly alters its capacity).
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
2019-03-06 20:36:55 +01:00
|
|
|
// std::string orig("For example PI is approximately ");
|
2018-06-21 21:55:12 +02:00
|
|
|
// std::cout << StrAppendFormat(&orig, "%12.6f", 3.14);
|
|
|
|
template <typename... Args>
|
2019-03-06 20:36:55 +01:00
|
|
|
std::string& StrAppendFormat(std::string* dst,
|
|
|
|
const FormatSpec<Args...>& format,
|
|
|
|
const Args&... args) {
|
2018-06-21 21:55:12 +02:00
|
|
|
return str_format_internal::AppendPack(
|
|
|
|
dst, str_format_internal::UntypedFormatSpecImpl::Extract(format),
|
|
|
|
{str_format_internal::FormatArgImpl(args)...});
|
|
|
|
}
|
|
|
|
|
|
|
|
// StreamFormat()
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// Writes to an output stream given a format string and zero or more arguments,
|
2018-06-21 21:55:12 +02:00
|
|
|
// generally in a manner that is more efficient than streaming the result of
|
|
|
|
// `absl:: StrFormat()`. The returned object must be streamed before the full
|
|
|
|
// expression ends.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// std::cout << StreamFormat("%12.6f", 3.14);
|
|
|
|
template <typename... Args>
|
|
|
|
ABSL_MUST_USE_RESULT str_format_internal::Streamable StreamFormat(
|
|
|
|
const FormatSpec<Args...>& format, const Args&... args) {
|
|
|
|
return str_format_internal::Streamable(
|
|
|
|
str_format_internal::UntypedFormatSpecImpl::Extract(format),
|
|
|
|
{str_format_internal::FormatArgImpl(args)...});
|
|
|
|
}
|
|
|
|
|
|
|
|
// PrintF()
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// Writes to stdout given a format string and zero or more arguments. This
|
2018-06-25 18:18:19 +02:00
|
|
|
// function is functionally equivalent to `std::printf()` (and type-safe);
|
|
|
|
// prefer `absl::PrintF()` over `std::printf()`.
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// std::string_view s = "Ulaanbaatar";
|
2018-06-25 18:18:19 +02:00
|
|
|
// absl::PrintF("The capital of Mongolia is %s", s);
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// Outputs: "The capital of Mongolia is Ulaanbaatar"
|
|
|
|
//
|
|
|
|
template <typename... Args>
|
|
|
|
int PrintF(const FormatSpec<Args...>& format, const Args&... args) {
|
|
|
|
return str_format_internal::FprintF(
|
|
|
|
stdout, str_format_internal::UntypedFormatSpecImpl::Extract(format),
|
|
|
|
{str_format_internal::FormatArgImpl(args)...});
|
|
|
|
}
|
|
|
|
|
|
|
|
// FPrintF()
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// Writes to a file given a format string and zero or more arguments. This
|
2018-06-25 18:18:19 +02:00
|
|
|
// function is functionally equivalent to `std::fprintf()` (and type-safe);
|
2018-06-21 21:55:12 +02:00
|
|
|
// prefer `absl::FPrintF()` over `std::fprintf()`.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// std::string_view s = "Ulaanbaatar";
|
2018-08-10 20:15:46 +02:00
|
|
|
// absl::FPrintF(stdout, "The capital of Mongolia is %s", s);
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// Outputs: "The capital of Mongolia is Ulaanbaatar"
|
|
|
|
//
|
|
|
|
template <typename... Args>
|
|
|
|
int FPrintF(std::FILE* output, const FormatSpec<Args...>& format,
|
|
|
|
const Args&... args) {
|
|
|
|
return str_format_internal::FprintF(
|
|
|
|
output, str_format_internal::UntypedFormatSpecImpl::Extract(format),
|
|
|
|
{str_format_internal::FormatArgImpl(args)...});
|
|
|
|
}
|
|
|
|
|
|
|
|
// SNPrintF()
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// Writes to a sized buffer given a format string and zero or more arguments.
|
2018-06-25 18:18:19 +02:00
|
|
|
// This function is functionally equivalent to `std::snprintf()` (and
|
|
|
|
// type-safe); prefer `absl::SNPrintF()` over `std::snprintf()`.
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
Export of internal Abseil changes
--
2f49cb9009386bc67bf54a2908c8720b749c8b7f by Greg Falcon <gfalcon@google.com>:
docs: fix typo
Import of https://github.com/abseil/abseil-cpp/pull/397
PiperOrigin-RevId: 277504420
--
f2bed362c1c12d3fa9c22d11f2b918668e8c37b7 by Abseil Team <absl-team@google.com>:
Avoid our is_[copy/move]_assignable workarounds in MSVC 19.20 and on, since that release introduces a regression that breaks our workaround. We should ideally use the std forms in more cases, but branching when our workarounds fail is simpler to maintain.
PiperOrigin-RevId: 277502334
--
e33de894ffd49848b9e088f59acc9743d1661948 by Derek Mauro <dmauro@google.com>:
Update rules_cc version. The mirror.bazel.build URL does not exist
(cache expiration?)
PiperOrigin-RevId: 277498394
--
b23757b0747c64634d2d701433782c969effef19 by Abseil Team <absl-team@google.com>:
Fix https://github.com/abseil/abseil-cpp/issues/394.
PiperOrigin-RevId: 277491405
--
54c75b8b29813531c52d67cf0ba7063baae4a4f3 by Abseil Team <absl-team@google.com>:
Fix comment typos: waker => waiter.
PiperOrigin-RevId: 277376952
--
874eeaa3b3af808fc88b6355245f643674f5e36e by Abseil Team <absl-team@google.com>:
Don't use atomic ops on waiter and wakeup counts in CONDVAR waiter mode.
Just guard the waiter and wakeup counts with the mutex. This eliminates the
race.
Also fix a typo in the error message for pthread_cond_timedwait.
PiperOrigin-RevId: 277366017
--
ce8c9a63109214519b5a7eaecef2c663c4d566df by Greg Falcon <gfalcon@google.com>:
Implement the config options for our four main C++ forward compatibility types.
These options control whether the names `any`, `optional`, `string_view`, and `variant` in namespace `absl` are aliases to the corresponding C++17 types in namespace `std`. By default, we continue to auto-detect the configuration of the compiler being run.
These options are not intended to be modified on the command line (as -D flags, say). Instead, the options.h file can be modified by distributors of Abseil (e.g., binary packagers, maintainers of local copies of Abseil, etc.)
Changing options will change Abseil in an ODR sense. Any program must only link in a single version of Abseil. Linking libraries that use Abseil configured with different options is an error: there is no ABI compatibility guarantee when linking different configurations, even if the Abseil versions used are otherwise exactly identical.
PiperOrigin-RevId: 277364298
--
5ed3ad42ae43a05862070f92f9ffd07f5c1f2b81 by Chris Kennelly <ckennelly@google.com>:
Suppress -Wimplicit-int-float-conversion.
On recent builds of Clang, this is an error/warning.
PiperOrigin-RevId: 277346168
--
9b9b0055243c705189bb27d912e6d45a7789cdee by Eric Fiselier <ericwf@google.com>:
Allow building Abseil as a shared library with CMake.
By default CMake's `add_library` creates the target as a static
library. However, users can override the default using the builtin
CMake option -DBUILD_SHARED_LIBS=ON.
This changes Abseil's CMake to respect this configuration option
by removing the explicit `STATIC` in our usages of `add_library`.
PiperOrigin-RevId: 277337753
--
63a8b7b8ede3a9d851916929d6b8537f4f2508ca by Abseil Team <absl-team@google.com>:
Improve AlphaNum Hex performance by using absl::numbers_internal::FastHexToBufferZeroPad16.
PiperOrigin-RevId: 277318108
--
dd047f7e92032682d94b27732df0e4d0670e24a4 by CJ Johnson <johnsoncj@google.com>:
Internal change
PiperOrigin-RevId: 277316913
--
d19ee7074929fed08973cc5b40a844573ce1e0a6 by Abseil Team <absl-team@google.com>:
Handle invoking [[nodiscard]] functions correctly in our tests.
PiperOrigin-RevId: 277301500
--
5373f3737894ba9b8481e95e5f58c7957c00d26a by Chris Kennelly <ckennelly@google.com>:
For internal reasons, loosen visibility restrictions of `//absl/base:malloc_internal`.
As an internal-namespace interface, this module remains unsupported. We
reserve the right to change, delete, or re-restrict visibility to this target
at any time.
PiperOrigin-RevId: 277118689
--
44e4f6655e05393a375d09b3625c192b1fde5909 by Abseil Team <absl-team@google.com>:
Fix error in example civil day comment.
PiperOrigin-RevId: 277103315
--
7657392b4ce48469106f11cdb952a0bc76a28df3 by Abseil Team <absl-team@google.com>:
Internal change
PiperOrigin-RevId: 277056076
--
c75bda76f40b01fa249b75b5a70c1f5907e56c76 by Abseil Team <absl-team@google.com>:
Suppress lifetime constant-initialization tests when building with MSVC versions > 19.0.
These are broken due to non-compliant initialization order in these versions:
https://developercommunity.visualstudio.com/content/problem/336946/class-with-constexpr-constructor-not-using-static.html
We don't know when Microsoft will fix this bug.
PiperOrigin-RevId: 277049770
--
16c3b9bf2a1796efa57f97b00bcd6227fbccca1f by Matt Calabrese <calabrese@google.com>:
Avoid our is_[copy/move]_assignable workarounds in MSVC 19.20 and on, since that release introduces a regression that breaks our workaround. We should ideally use the std forms in more cases, but branching when our workarounds fail is simpler to maintain.
PiperOrigin-RevId: 277048670
--
e91003fa3ee6026d9b80624a23fc144fa5d74810 by Chris Kennelly <ckennelly@google.com>:
Fix -Wimplicit-int-float-conversion warning in latest clang
PiperOrigin-RevId: 276771618
--
53087ca6603e86ad815f3dd9ab795cc0f79792c1 by Andy Soffer <asoffer@google.com>:
Add documentation on absl::SNPrintF.
PiperOrigin-RevId: 276694032
--
a9426af8cbd4c3a8f9053e7446c821852e41ff61 by Jorg Brown <jorg@google.com>:
Stop including kern/OSByteOrder.h in order to support __APPLE__
Apple compiles with clang now anyway, and clang has support for the
built-in compiler swap functions that are much faster than any function call to
the OS.
PiperOrigin-RevId: 276625231
--
df974be5aa5b4dc1b09c356cb8816edfc7867e63 by Jorg Brown <jorg@google.com>:
Fix the build for Android x86-64 builds, where __SSE4_2__ is defined but
_bswap64 is not.
PiperOrigin-RevId: 276542642
--
d99dc092b3a5ad17643005e55f3b3cb6b9187ccc by Jorg Brown <jorg@google.com>:
Remove a byteswap from the non-SSE path of FastHexToBufferZeroPad16
Remove the need for including absl/base/internal/endian.h from the SSE case
(since if we have the Intel SSE intrinsics, then clearly we also have the
Intel Byte-Swap intrinsics.)
PiperOrigin-RevId: 276532608
--
d67b106dc930d8558810ae3983613bb2ab1e0d36 by Abseil Team <absl-team@google.com>:
Use explicit static_cast<double> for int64_t to double conversion
This uses an explicit static_cast<double>() in the int64_t to double comparisons in duration.cc's SafeAddRepHi. This satisfies clang's -Wimplicit-int-to-float-conversion warning (with https://reviews.llvm.org/D64666). This may also make it easier for humans to realize that the comparison is happening between two floating point double precision values. It should have no impact on the behavior or generated code.
Tested:
No behavior change
PiperOrigin-RevId: 276529211
GitOrigin-RevId: 2f49cb9009386bc67bf54a2908c8720b749c8b7f
Change-Id: I71e0781893ce219960b8290d54b20532779cb0ff
2019-10-30 16:00:44 +01:00
|
|
|
// In particular, a successful call to `absl::SNPrintF()` writes at most `size`
|
2019-12-18 20:46:26 +01:00
|
|
|
// bytes of the formatted output to `output`, including a NUL-terminator, and
|
Export of internal Abseil changes
--
2f49cb9009386bc67bf54a2908c8720b749c8b7f by Greg Falcon <gfalcon@google.com>:
docs: fix typo
Import of https://github.com/abseil/abseil-cpp/pull/397
PiperOrigin-RevId: 277504420
--
f2bed362c1c12d3fa9c22d11f2b918668e8c37b7 by Abseil Team <absl-team@google.com>:
Avoid our is_[copy/move]_assignable workarounds in MSVC 19.20 and on, since that release introduces a regression that breaks our workaround. We should ideally use the std forms in more cases, but branching when our workarounds fail is simpler to maintain.
PiperOrigin-RevId: 277502334
--
e33de894ffd49848b9e088f59acc9743d1661948 by Derek Mauro <dmauro@google.com>:
Update rules_cc version. The mirror.bazel.build URL does not exist
(cache expiration?)
PiperOrigin-RevId: 277498394
--
b23757b0747c64634d2d701433782c969effef19 by Abseil Team <absl-team@google.com>:
Fix https://github.com/abseil/abseil-cpp/issues/394.
PiperOrigin-RevId: 277491405
--
54c75b8b29813531c52d67cf0ba7063baae4a4f3 by Abseil Team <absl-team@google.com>:
Fix comment typos: waker => waiter.
PiperOrigin-RevId: 277376952
--
874eeaa3b3af808fc88b6355245f643674f5e36e by Abseil Team <absl-team@google.com>:
Don't use atomic ops on waiter and wakeup counts in CONDVAR waiter mode.
Just guard the waiter and wakeup counts with the mutex. This eliminates the
race.
Also fix a typo in the error message for pthread_cond_timedwait.
PiperOrigin-RevId: 277366017
--
ce8c9a63109214519b5a7eaecef2c663c4d566df by Greg Falcon <gfalcon@google.com>:
Implement the config options for our four main C++ forward compatibility types.
These options control whether the names `any`, `optional`, `string_view`, and `variant` in namespace `absl` are aliases to the corresponding C++17 types in namespace `std`. By default, we continue to auto-detect the configuration of the compiler being run.
These options are not intended to be modified on the command line (as -D flags, say). Instead, the options.h file can be modified by distributors of Abseil (e.g., binary packagers, maintainers of local copies of Abseil, etc.)
Changing options will change Abseil in an ODR sense. Any program must only link in a single version of Abseil. Linking libraries that use Abseil configured with different options is an error: there is no ABI compatibility guarantee when linking different configurations, even if the Abseil versions used are otherwise exactly identical.
PiperOrigin-RevId: 277364298
--
5ed3ad42ae43a05862070f92f9ffd07f5c1f2b81 by Chris Kennelly <ckennelly@google.com>:
Suppress -Wimplicit-int-float-conversion.
On recent builds of Clang, this is an error/warning.
PiperOrigin-RevId: 277346168
--
9b9b0055243c705189bb27d912e6d45a7789cdee by Eric Fiselier <ericwf@google.com>:
Allow building Abseil as a shared library with CMake.
By default CMake's `add_library` creates the target as a static
library. However, users can override the default using the builtin
CMake option -DBUILD_SHARED_LIBS=ON.
This changes Abseil's CMake to respect this configuration option
by removing the explicit `STATIC` in our usages of `add_library`.
PiperOrigin-RevId: 277337753
--
63a8b7b8ede3a9d851916929d6b8537f4f2508ca by Abseil Team <absl-team@google.com>:
Improve AlphaNum Hex performance by using absl::numbers_internal::FastHexToBufferZeroPad16.
PiperOrigin-RevId: 277318108
--
dd047f7e92032682d94b27732df0e4d0670e24a4 by CJ Johnson <johnsoncj@google.com>:
Internal change
PiperOrigin-RevId: 277316913
--
d19ee7074929fed08973cc5b40a844573ce1e0a6 by Abseil Team <absl-team@google.com>:
Handle invoking [[nodiscard]] functions correctly in our tests.
PiperOrigin-RevId: 277301500
--
5373f3737894ba9b8481e95e5f58c7957c00d26a by Chris Kennelly <ckennelly@google.com>:
For internal reasons, loosen visibility restrictions of `//absl/base:malloc_internal`.
As an internal-namespace interface, this module remains unsupported. We
reserve the right to change, delete, or re-restrict visibility to this target
at any time.
PiperOrigin-RevId: 277118689
--
44e4f6655e05393a375d09b3625c192b1fde5909 by Abseil Team <absl-team@google.com>:
Fix error in example civil day comment.
PiperOrigin-RevId: 277103315
--
7657392b4ce48469106f11cdb952a0bc76a28df3 by Abseil Team <absl-team@google.com>:
Internal change
PiperOrigin-RevId: 277056076
--
c75bda76f40b01fa249b75b5a70c1f5907e56c76 by Abseil Team <absl-team@google.com>:
Suppress lifetime constant-initialization tests when building with MSVC versions > 19.0.
These are broken due to non-compliant initialization order in these versions:
https://developercommunity.visualstudio.com/content/problem/336946/class-with-constexpr-constructor-not-using-static.html
We don't know when Microsoft will fix this bug.
PiperOrigin-RevId: 277049770
--
16c3b9bf2a1796efa57f97b00bcd6227fbccca1f by Matt Calabrese <calabrese@google.com>:
Avoid our is_[copy/move]_assignable workarounds in MSVC 19.20 and on, since that release introduces a regression that breaks our workaround. We should ideally use the std forms in more cases, but branching when our workarounds fail is simpler to maintain.
PiperOrigin-RevId: 277048670
--
e91003fa3ee6026d9b80624a23fc144fa5d74810 by Chris Kennelly <ckennelly@google.com>:
Fix -Wimplicit-int-float-conversion warning in latest clang
PiperOrigin-RevId: 276771618
--
53087ca6603e86ad815f3dd9ab795cc0f79792c1 by Andy Soffer <asoffer@google.com>:
Add documentation on absl::SNPrintF.
PiperOrigin-RevId: 276694032
--
a9426af8cbd4c3a8f9053e7446c821852e41ff61 by Jorg Brown <jorg@google.com>:
Stop including kern/OSByteOrder.h in order to support __APPLE__
Apple compiles with clang now anyway, and clang has support for the
built-in compiler swap functions that are much faster than any function call to
the OS.
PiperOrigin-RevId: 276625231
--
df974be5aa5b4dc1b09c356cb8816edfc7867e63 by Jorg Brown <jorg@google.com>:
Fix the build for Android x86-64 builds, where __SSE4_2__ is defined but
_bswap64 is not.
PiperOrigin-RevId: 276542642
--
d99dc092b3a5ad17643005e55f3b3cb6b9187ccc by Jorg Brown <jorg@google.com>:
Remove a byteswap from the non-SSE path of FastHexToBufferZeroPad16
Remove the need for including absl/base/internal/endian.h from the SSE case
(since if we have the Intel SSE intrinsics, then clearly we also have the
Intel Byte-Swap intrinsics.)
PiperOrigin-RevId: 276532608
--
d67b106dc930d8558810ae3983613bb2ab1e0d36 by Abseil Team <absl-team@google.com>:
Use explicit static_cast<double> for int64_t to double conversion
This uses an explicit static_cast<double>() in the int64_t to double comparisons in duration.cc's SafeAddRepHi. This satisfies clang's -Wimplicit-int-to-float-conversion warning (with https://reviews.llvm.org/D64666). This may also make it easier for humans to realize that the comparison is happening between two floating point double precision values. It should have no impact on the behavior or generated code.
Tested:
No behavior change
PiperOrigin-RevId: 276529211
GitOrigin-RevId: 2f49cb9009386bc67bf54a2908c8720b749c8b7f
Change-Id: I71e0781893ce219960b8290d54b20532779cb0ff
2019-10-30 16:00:44 +01:00
|
|
|
// returns the number of bytes that would have been written if truncation did
|
|
|
|
// not occur. In the event of an error, a negative value is returned and `errno`
|
|
|
|
// is set.
|
|
|
|
//
|
2018-06-21 21:55:12 +02:00
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// std::string_view s = "Ulaanbaatar";
|
2018-06-25 18:18:19 +02:00
|
|
|
// char output[128];
|
|
|
|
// absl::SNPrintF(output, sizeof(output),
|
|
|
|
// "The capital of Mongolia is %s", s);
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
2018-06-25 18:18:19 +02:00
|
|
|
// Post-condition: output == "The capital of Mongolia is Ulaanbaatar"
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
template <typename... Args>
|
|
|
|
int SNPrintF(char* output, std::size_t size, const FormatSpec<Args...>& format,
|
|
|
|
const Args&... args) {
|
|
|
|
return str_format_internal::SnprintF(
|
|
|
|
output, size, str_format_internal::UntypedFormatSpecImpl::Extract(format),
|
|
|
|
{str_format_internal::FormatArgImpl(args)...});
|
|
|
|
}
|
|
|
|
|
|
|
|
// -----------------------------------------------------------------------------
|
|
|
|
// Custom Output Formatting Functions
|
|
|
|
// -----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
// FormatRawSink
|
|
|
|
//
|
|
|
|
// FormatRawSink is a type erased wrapper around arbitrary sink objects
|
|
|
|
// specifically used as an argument to `Format()`.
|
2020-04-17 17:13:06 +02:00
|
|
|
//
|
|
|
|
// All the object has to do define an overload of `AbslFormatFlush()` for the
|
|
|
|
// sink, usually by adding a ADL-based free function in the same namespace as
|
|
|
|
// the sink:
|
|
|
|
//
|
|
|
|
// void AbslFormatFlush(MySink* dest, absl::string_view part);
|
|
|
|
//
|
|
|
|
// where `dest` is the pointer passed to `absl::Format()`. The function should
|
|
|
|
// append `part` to `dest`.
|
|
|
|
//
|
2018-06-21 21:55:12 +02:00
|
|
|
// FormatRawSink does not own the passed sink object. The passed object must
|
|
|
|
// outlive the FormatRawSink.
|
|
|
|
class FormatRawSink {
|
|
|
|
public:
|
|
|
|
// Implicitly convert from any type that provides the hook function as
|
|
|
|
// described above.
|
|
|
|
template <typename T,
|
|
|
|
typename = typename std::enable_if<std::is_constructible<
|
|
|
|
str_format_internal::FormatRawSinkImpl, T*>::value>::type>
|
|
|
|
FormatRawSink(T* raw) // NOLINT
|
|
|
|
: sink_(raw) {}
|
|
|
|
|
|
|
|
private:
|
|
|
|
friend str_format_internal::FormatRawSinkImpl;
|
|
|
|
str_format_internal::FormatRawSinkImpl sink_;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Format()
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// Writes a formatted string to an arbitrary sink object (implementing the
|
|
|
|
// `absl::FormatRawSink` interface), using a format string and zero or more
|
2018-06-21 21:55:12 +02:00
|
|
|
// additional arguments.
|
|
|
|
//
|
2020-04-17 17:13:06 +02:00
|
|
|
// By default, `std::string`, `std::ostream`, and `absl::Cord` are supported as
|
|
|
|
// destination objects. If a `std::string` is used the formatted string is
|
|
|
|
// appended to it.
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
2020-04-17 17:13:06 +02:00
|
|
|
// `absl::Format()` is a generic version of `absl::StrAppendFormat()`, for
|
|
|
|
// custom sinks. The format string, like format strings for `StrFormat()`, is
|
|
|
|
// checked at compile-time.
|
2018-06-21 21:55:12 +02:00
|
|
|
//
|
|
|
|
// On failure, this function returns `false` and the state of the sink is
|
|
|
|
// unspecified.
|
|
|
|
template <typename... Args>
|
|
|
|
bool Format(FormatRawSink raw_sink, const FormatSpec<Args...>& format,
|
|
|
|
const Args&... args) {
|
|
|
|
return str_format_internal::FormatUntyped(
|
|
|
|
str_format_internal::FormatRawSinkImpl::Extract(raw_sink),
|
|
|
|
str_format_internal::UntypedFormatSpecImpl::Extract(format),
|
|
|
|
{str_format_internal::FormatArgImpl(args)...});
|
|
|
|
}
|
|
|
|
|
|
|
|
// FormatArg
|
|
|
|
//
|
|
|
|
// A type-erased handle to a format argument specifically used as an argument to
|
|
|
|
// `FormatUntyped()`. You may construct `FormatArg` by passing
|
|
|
|
// reference-to-const of any printable type. `FormatArg` is both copyable and
|
|
|
|
// assignable. The source data must outlive the `FormatArg` instance. See
|
|
|
|
// example below.
|
|
|
|
//
|
|
|
|
using FormatArg = str_format_internal::FormatArgImpl;
|
|
|
|
|
|
|
|
// FormatUntyped()
|
|
|
|
//
|
2018-08-21 20:31:02 +02:00
|
|
|
// Writes a formatted string to an arbitrary sink object (implementing the
|
2018-06-21 21:55:12 +02:00
|
|
|
// `absl::FormatRawSink` interface), using an `UntypedFormatSpec` and zero or
|
|
|
|
// more additional arguments.
|
|
|
|
//
|
|
|
|
// This function acts as the most generic formatting function in the
|
|
|
|
// `str_format` library. The caller provides a raw sink, an unchecked format
|
2018-08-21 20:31:02 +02:00
|
|
|
// string, and (usually) a runtime specified list of arguments; no compile-time
|
2018-06-21 21:55:12 +02:00
|
|
|
// checking of formatting is performed within this function. As a result, a
|
|
|
|
// caller should check the return value to verify that no error occurred.
|
|
|
|
// On failure, this function returns `false` and the state of the sink is
|
|
|
|
// unspecified.
|
|
|
|
//
|
|
|
|
// The arguments are provided in an `absl::Span<const absl::FormatArg>`.
|
|
|
|
// Each `absl::FormatArg` object binds to a single argument and keeps a
|
|
|
|
// reference to it. The values used to create the `FormatArg` objects must
|
|
|
|
// outlive this function call. (See `str_format_arg.h` for information on
|
|
|
|
// the `FormatArg` class.)_
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
2019-03-06 20:36:55 +01:00
|
|
|
// std::optional<std::string> FormatDynamic(
|
|
|
|
// const std::string& in_format,
|
|
|
|
// const vector<std::string>& in_args) {
|
|
|
|
// std::string out;
|
2018-06-21 21:55:12 +02:00
|
|
|
// std::vector<absl::FormatArg> args;
|
|
|
|
// for (const auto& v : in_args) {
|
|
|
|
// // It is important that 'v' is a reference to the objects in in_args.
|
|
|
|
// // The values we pass to FormatArg must outlive the call to
|
|
|
|
// // FormatUntyped.
|
|
|
|
// args.emplace_back(v);
|
|
|
|
// }
|
|
|
|
// absl::UntypedFormatSpec format(in_format);
|
|
|
|
// if (!absl::FormatUntyped(&out, format, args)) {
|
|
|
|
// return std::nullopt;
|
|
|
|
// }
|
|
|
|
// return std::move(out);
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
ABSL_MUST_USE_RESULT inline bool FormatUntyped(
|
|
|
|
FormatRawSink raw_sink, const UntypedFormatSpec& format,
|
|
|
|
absl::Span<const FormatArg> args) {
|
|
|
|
return str_format_internal::FormatUntyped(
|
|
|
|
str_format_internal::FormatRawSinkImpl::Extract(raw_sink),
|
|
|
|
str_format_internal::UntypedFormatSpecImpl::Extract(format), args);
|
|
|
|
}
|
|
|
|
|
2020-11-21 14:43:54 +01:00
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
// StrFormat Extensions
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
//
|
|
|
|
// AbslFormatConvert()
|
|
|
|
//
|
|
|
|
// The StrFormat library provides a customization API for formatting
|
|
|
|
// user-defined types using absl::StrFormat(). The API relies on detecting an
|
|
|
|
// overload in the user-defined type's namespace of a free (non-member)
|
|
|
|
// `AbslFormatConvert()` function, usually as a friend definition with the
|
|
|
|
// following signature:
|
|
|
|
//
|
|
|
|
// absl::FormatConvertResult<...> AbslFormatConvert(
|
|
|
|
// const X& value,
|
|
|
|
// const absl::FormatConversionSpec& spec,
|
|
|
|
// absl::FormatSink *sink);
|
|
|
|
//
|
|
|
|
// An `AbslFormatConvert()` overload for a type should only be declared in the
|
|
|
|
// same file and namespace as said type.
|
|
|
|
//
|
|
|
|
// The abstractions within this definition include:
|
|
|
|
//
|
|
|
|
// * An `absl::FormatConversionSpec` to specify the fields to pull from a
|
|
|
|
// user-defined type's format string
|
|
|
|
// * An `absl::FormatSink` to hold the converted string data during the
|
|
|
|
// conversion process.
|
|
|
|
// * An `absl::FormatConvertResult` to hold the status of the returned
|
|
|
|
// formatting operation
|
|
|
|
//
|
|
|
|
// The return type encodes all the conversion characters that your
|
|
|
|
// AbslFormatConvert() routine accepts. The return value should be {true}.
|
|
|
|
// A return value of {false} will result in `StrFormat()` returning
|
|
|
|
// an empty string. This result will be propagated to the result of
|
|
|
|
// `FormatUntyped`.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
|
|
|
// struct Point {
|
|
|
|
// // To add formatting support to `Point`, we simply need to add a free
|
|
|
|
// // (non-member) function `AbslFormatConvert()`. This method interprets
|
|
|
|
// // `spec` to print in the request format. The allowed conversion characters
|
|
|
|
// // can be restricted via the type of the result, in this example
|
|
|
|
// // string and integral formatting are allowed (but not, for instance
|
|
|
|
// // floating point characters like "%f"). You can add such a free function
|
|
|
|
// // using a friend declaration within the body of the class:
|
|
|
|
// friend absl::FormatConvertResult<absl::FormatConversionCharSet::kString |
|
|
|
|
// absl::FormatConversionCharSet::kIntegral>
|
|
|
|
// AbslFormatConvert(const Point& p, const absl::FormatConversionSpec& spec,
|
|
|
|
// absl::FormatSink* s) {
|
|
|
|
// if (spec.conversion_char() == absl::FormatConversionChar::s) {
|
|
|
|
// s->Append(absl::StrCat("x=", p.x, " y=", p.y));
|
|
|
|
// } else {
|
|
|
|
// s->Append(absl::StrCat(p.x, ",", p.y));
|
|
|
|
// }
|
|
|
|
// return {true};
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// int x;
|
|
|
|
// int y;
|
|
|
|
// };
|
|
|
|
|
|
|
|
// clang-format off
|
|
|
|
|
|
|
|
// FormatConversionChar
|
|
|
|
//
|
|
|
|
// Specifies the formatting character provided in the format string
|
|
|
|
// passed to `StrFormat()`.
|
|
|
|
enum class FormatConversionChar : uint8_t {
|
|
|
|
c, s, // text
|
|
|
|
d, i, o, u, x, X, // int
|
|
|
|
f, F, e, E, g, G, a, A, // float
|
|
|
|
n, p // misc
|
|
|
|
};
|
|
|
|
// clang-format on
|
|
|
|
|
|
|
|
// FormatConversionSpec
|
|
|
|
//
|
|
|
|
// Specifies modifications to the conversion of the format string, through use
|
|
|
|
// of one or more format flags in the source format string.
|
|
|
|
class FormatConversionSpec {
|
|
|
|
public:
|
|
|
|
// FormatConversionSpec::is_basic()
|
|
|
|
//
|
|
|
|
// Indicates that width and precision are not specified, and no additional
|
|
|
|
// flags are set for this conversion character in the format string.
|
|
|
|
bool is_basic() const { return impl_.is_basic(); }
|
|
|
|
|
|
|
|
// FormatConversionSpec::has_left_flag()
|
|
|
|
//
|
|
|
|
// Indicates whether the result should be left justified for this conversion
|
|
|
|
// character in the format string. This flag is set through use of a '-'
|
|
|
|
// character in the format string. E.g. "%-s"
|
|
|
|
bool has_left_flag() const { return impl_.has_left_flag(); }
|
|
|
|
|
|
|
|
// FormatConversionSpec::has_show_pos_flag()
|
|
|
|
//
|
|
|
|
// Indicates whether a sign column is prepended to the result for this
|
|
|
|
// conversion character in the format string, even if the result is positive.
|
|
|
|
// This flag is set through use of a '+' character in the format string.
|
|
|
|
// E.g. "%+d"
|
|
|
|
bool has_show_pos_flag() const { return impl_.has_show_pos_flag(); }
|
|
|
|
|
|
|
|
// FormatConversionSpec::has_sign_col_flag()
|
|
|
|
//
|
|
|
|
// Indicates whether a mandatory sign column is added to the result for this
|
|
|
|
// conversion character. This flag is set through use of a space character
|
|
|
|
// (' ') in the format string. E.g. "% i"
|
|
|
|
bool has_sign_col_flag() const { return impl_.has_sign_col_flag(); }
|
|
|
|
|
|
|
|
// FormatConversionSpec::has_alt_flag()
|
|
|
|
//
|
|
|
|
// Indicates whether an "alternate" format is applied to the result for this
|
|
|
|
// conversion character. Alternative forms depend on the type of conversion
|
|
|
|
// character, and unallowed alternatives are undefined. This flag is set
|
|
|
|
// through use of a '#' character in the format string. E.g. "%#h"
|
|
|
|
bool has_alt_flag() const { return impl_.has_alt_flag(); }
|
|
|
|
|
|
|
|
// FormatConversionSpec::has_zero_flag()
|
|
|
|
//
|
|
|
|
// Indicates whether zeroes should be prepended to the result for this
|
|
|
|
// conversion character instead of spaces. This flag is set through use of the
|
|
|
|
// '0' character in the format string. E.g. "%0f"
|
|
|
|
bool has_zero_flag() const { return impl_.has_zero_flag(); }
|
|
|
|
|
|
|
|
// FormatConversionSpec::conversion_char()
|
|
|
|
//
|
|
|
|
// Returns the underlying conversion character.
|
|
|
|
FormatConversionChar conversion_char() const {
|
|
|
|
return impl_.conversion_char();
|
|
|
|
}
|
|
|
|
|
|
|
|
// FormatConversionSpec::width()
|
|
|
|
//
|
|
|
|
// Returns the specified width (indicated through use of a non-zero integer
|
|
|
|
// value or '*' character) of the conversion character. If width is
|
|
|
|
// unspecified, it returns a negative value.
|
|
|
|
int width() const { return impl_.width(); }
|
|
|
|
|
|
|
|
// FormatConversionSpec::precision()
|
|
|
|
//
|
|
|
|
// Returns the specified precision (through use of the '.' character followed
|
|
|
|
// by a non-zero integer value or '*' character) of the conversion character.
|
|
|
|
// If precision is unspecified, it returns a negative value.
|
|
|
|
int precision() const { return impl_.precision(); }
|
|
|
|
|
|
|
|
private:
|
|
|
|
explicit FormatConversionSpec(
|
|
|
|
str_format_internal::FormatConversionSpecImpl impl)
|
|
|
|
: impl_(impl) {}
|
|
|
|
|
|
|
|
friend str_format_internal::FormatConversionSpecImpl;
|
|
|
|
|
|
|
|
absl::str_format_internal::FormatConversionSpecImpl impl_;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Type safe OR operator for FormatConversionCharSet to allow accepting multiple
|
|
|
|
// conversion chars in custom format converters.
|
|
|
|
constexpr FormatConversionCharSet operator|(FormatConversionCharSet a,
|
|
|
|
FormatConversionCharSet b) {
|
|
|
|
return static_cast<FormatConversionCharSet>(static_cast<uint64_t>(a) |
|
|
|
|
static_cast<uint64_t>(b));
|
|
|
|
}
|
|
|
|
|
|
|
|
// FormatConversionCharSet
|
|
|
|
//
|
|
|
|
// Specifies the _accepted_ conversion types as a template parameter to
|
|
|
|
// FormatConvertResult for custom implementations of `AbslFormatConvert`.
|
|
|
|
// Note the helper predefined alias definitions (kIntegral, etc.) below.
|
|
|
|
enum class FormatConversionCharSet : uint64_t {
|
|
|
|
// text
|
|
|
|
c = str_format_internal::FormatConversionCharToConvInt('c'),
|
|
|
|
s = str_format_internal::FormatConversionCharToConvInt('s'),
|
|
|
|
// integer
|
|
|
|
d = str_format_internal::FormatConversionCharToConvInt('d'),
|
|
|
|
i = str_format_internal::FormatConversionCharToConvInt('i'),
|
|
|
|
o = str_format_internal::FormatConversionCharToConvInt('o'),
|
|
|
|
u = str_format_internal::FormatConversionCharToConvInt('u'),
|
|
|
|
x = str_format_internal::FormatConversionCharToConvInt('x'),
|
|
|
|
X = str_format_internal::FormatConversionCharToConvInt('X'),
|
|
|
|
// Float
|
|
|
|
f = str_format_internal::FormatConversionCharToConvInt('f'),
|
|
|
|
F = str_format_internal::FormatConversionCharToConvInt('F'),
|
|
|
|
e = str_format_internal::FormatConversionCharToConvInt('e'),
|
|
|
|
E = str_format_internal::FormatConversionCharToConvInt('E'),
|
|
|
|
g = str_format_internal::FormatConversionCharToConvInt('g'),
|
|
|
|
G = str_format_internal::FormatConversionCharToConvInt('G'),
|
|
|
|
a = str_format_internal::FormatConversionCharToConvInt('a'),
|
|
|
|
A = str_format_internal::FormatConversionCharToConvInt('A'),
|
|
|
|
// misc
|
|
|
|
n = str_format_internal::FormatConversionCharToConvInt('n'),
|
|
|
|
p = str_format_internal::FormatConversionCharToConvInt('p'),
|
|
|
|
|
|
|
|
// Used for width/precision '*' specification.
|
|
|
|
kStar = static_cast<uint64_t>(
|
|
|
|
absl::str_format_internal::FormatConversionCharSetInternal::kStar),
|
|
|
|
// Some predefined values:
|
|
|
|
kIntegral = d | i | u | o | x | X,
|
|
|
|
kFloating = a | e | f | g | A | E | F | G,
|
|
|
|
kNumeric = kIntegral | kFloating,
|
|
|
|
kString = s,
|
|
|
|
kPointer = p,
|
|
|
|
};
|
|
|
|
|
|
|
|
// FormatSink
|
|
|
|
//
|
|
|
|
// An abstraction to which conversions write their string data.
|
|
|
|
//
|
|
|
|
class FormatSink {
|
|
|
|
public:
|
|
|
|
// Appends `count` copies of `ch`.
|
|
|
|
void Append(size_t count, char ch) { sink_->Append(count, ch); }
|
|
|
|
|
|
|
|
void Append(string_view v) { sink_->Append(v); }
|
|
|
|
|
|
|
|
// Appends the first `precision` bytes of `v`. If this is less than
|
|
|
|
// `width`, spaces will be appended first (if `left` is false), or
|
|
|
|
// after (if `left` is true) to ensure the total amount appended is
|
|
|
|
// at least `width`.
|
|
|
|
bool PutPaddedString(string_view v, int width, int precision, bool left) {
|
|
|
|
return sink_->PutPaddedString(v, width, precision, left);
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
friend str_format_internal::FormatSinkImpl;
|
|
|
|
explicit FormatSink(str_format_internal::FormatSinkImpl* s) : sink_(s) {}
|
|
|
|
str_format_internal::FormatSinkImpl* sink_;
|
|
|
|
};
|
|
|
|
|
|
|
|
// FormatConvertResult
|
|
|
|
//
|
|
|
|
// Indicates whether a call to AbslFormatConvert() was successful.
|
|
|
|
// This return type informs the StrFormat extension framework (through
|
|
|
|
// ADL but using the return type) of what conversion characters are supported.
|
|
|
|
// It is strongly discouraged to return {false}, as this will result in an
|
|
|
|
// empty string in StrFormat.
|
|
|
|
template <FormatConversionCharSet C>
|
|
|
|
struct FormatConvertResult {
|
|
|
|
bool value;
|
|
|
|
};
|
|
|
|
|
2019-12-12 19:36:03 +01:00
|
|
|
ABSL_NAMESPACE_END
|
2018-06-21 21:55:12 +02:00
|
|
|
} // namespace absl
|
2019-03-19 19:14:01 +01:00
|
|
|
|
2018-06-21 21:55:12 +02:00
|
|
|
#endif // ABSL_STRINGS_STR_FORMAT_H_
|