Include fmt 11.0.2
[openal-soft.git] / fmt-11.0.2 / include / fmt / base.h
blob6276494253dd49b2ed5a238b6ce0430ffea5e5cb
1 // Formatting library for C++ - the base API for char/UTF-8
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
8 #ifndef FMT_BASE_H_
9 #define FMT_BASE_H_
11 #if defined(FMT_IMPORT_STD) && !defined(FMT_MODULE)
12 # define FMT_MODULE
13 #endif
15 #ifndef FMT_MODULE
16 # include <limits.h> // CHAR_BIT
17 # include <stdio.h> // FILE
18 # include <string.h> // strlen
20 // <cstddef> is also included transitively from <type_traits>.
21 # include <cstddef> // std::byte
22 # include <type_traits> // std::enable_if
23 #endif
25 // The fmt library version in the form major * 10000 + minor * 100 + patch.
26 #define FMT_VERSION 110002
28 // Detect compiler versions.
29 #if defined(__clang__) && !defined(__ibmxl__)
30 # define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
31 #else
32 # define FMT_CLANG_VERSION 0
33 #endif
34 #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
35 # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
36 #else
37 # define FMT_GCC_VERSION 0
38 #endif
39 #if defined(__ICL)
40 # define FMT_ICC_VERSION __ICL
41 #elif defined(__INTEL_COMPILER)
42 # define FMT_ICC_VERSION __INTEL_COMPILER
43 #else
44 # define FMT_ICC_VERSION 0
45 #endif
46 #if defined(_MSC_VER)
47 # define FMT_MSC_VERSION _MSC_VER
48 #else
49 # define FMT_MSC_VERSION 0
50 #endif
52 // Detect standard library versions.
53 #ifdef _GLIBCXX_RELEASE
54 # define FMT_GLIBCXX_RELEASE _GLIBCXX_RELEASE
55 #else
56 # define FMT_GLIBCXX_RELEASE 0
57 #endif
58 #ifdef _LIBCPP_VERSION
59 # define FMT_LIBCPP_VERSION _LIBCPP_VERSION
60 #else
61 # define FMT_LIBCPP_VERSION 0
62 #endif
64 #ifdef _MSVC_LANG
65 # define FMT_CPLUSPLUS _MSVC_LANG
66 #else
67 # define FMT_CPLUSPLUS __cplusplus
68 #endif
70 // Detect __has_*.
71 #ifdef __has_feature
72 # define FMT_HAS_FEATURE(x) __has_feature(x)
73 #else
74 # define FMT_HAS_FEATURE(x) 0
75 #endif
76 #ifdef __has_include
77 # define FMT_HAS_INCLUDE(x) __has_include(x)
78 #else
79 # define FMT_HAS_INCLUDE(x) 0
80 #endif
81 #ifdef __has_cpp_attribute
82 # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
83 #else
84 # define FMT_HAS_CPP_ATTRIBUTE(x) 0
85 #endif
87 #define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
88 (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
90 #define FMT_HAS_CPP17_ATTRIBUTE(attribute) \
91 (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))
93 // Detect C++14 relaxed constexpr.
94 #ifdef FMT_USE_CONSTEXPR
95 // Use the provided definition.
96 #elif FMT_GCC_VERSION >= 600 && FMT_CPLUSPLUS >= 201402L
97 // GCC only allows throw in constexpr since version 6:
98 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67371.
99 # define FMT_USE_CONSTEXPR 1
100 #elif FMT_ICC_VERSION
101 # define FMT_USE_CONSTEXPR 0 // https://github.com/fmtlib/fmt/issues/1628
102 #elif FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912
103 # define FMT_USE_CONSTEXPR 1
104 #else
105 # define FMT_USE_CONSTEXPR 0
106 #endif
107 #if FMT_USE_CONSTEXPR
108 # define FMT_CONSTEXPR constexpr
109 #else
110 # define FMT_CONSTEXPR
111 #endif
113 // Detect consteval, C++20 constexpr extensions and std::is_constant_evaluated.
114 #if !defined(__cpp_lib_is_constant_evaluated)
115 # define FMT_USE_CONSTEVAL 0
116 #elif FMT_CPLUSPLUS < 201709L
117 # define FMT_USE_CONSTEVAL 0
118 #elif FMT_GLIBCXX_RELEASE && FMT_GLIBCXX_RELEASE < 10
119 # define FMT_USE_CONSTEVAL 0
120 #elif FMT_LIBCPP_VERSION && FMT_LIBCPP_VERSION < 10000
121 # define FMT_USE_CONSTEVAL 0
122 #elif defined(__apple_build_version__) && __apple_build_version__ < 14000029L
123 # define FMT_USE_CONSTEVAL 0 // consteval is broken in Apple clang < 14.
124 #elif FMT_MSC_VERSION && FMT_MSC_VERSION < 1929
125 # define FMT_USE_CONSTEVAL 0 // consteval is broken in MSVC VS2019 < 16.10.
126 #elif defined(__cpp_consteval)
127 # define FMT_USE_CONSTEVAL 1
128 #elif FMT_GCC_VERSION >= 1002 || FMT_CLANG_VERSION >= 1101
129 # define FMT_USE_CONSTEVAL 1
130 #else
131 # define FMT_USE_CONSTEVAL 0
132 #endif
133 #if FMT_USE_CONSTEVAL
134 # define FMT_CONSTEVAL consteval
135 # define FMT_CONSTEXPR20 constexpr
136 #else
137 # define FMT_CONSTEVAL
138 # define FMT_CONSTEXPR20
139 #endif
141 #if defined(FMT_USE_NONTYPE_TEMPLATE_ARGS)
142 // Use the provided definition.
143 #elif defined(__NVCOMPILER)
144 # define FMT_USE_NONTYPE_TEMPLATE_ARGS 0
145 #elif FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L
146 # define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
147 #elif defined(__cpp_nontype_template_args) && \
148 __cpp_nontype_template_args >= 201911L
149 # define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
150 #elif FMT_CLANG_VERSION >= 1200 && FMT_CPLUSPLUS >= 202002L
151 # define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
152 #else
153 # define FMT_USE_NONTYPE_TEMPLATE_ARGS 0
154 #endif
156 #ifdef FMT_USE_CONCEPTS
157 // Use the provided definition.
158 #elif defined(__cpp_concepts)
159 # define FMT_USE_CONCEPTS 1
160 #else
161 # define FMT_USE_CONCEPTS 0
162 #endif
164 // Check if exceptions are disabled.
165 #ifdef FMT_EXCEPTIONS
166 // Use the provided definition.
167 #elif defined(__GNUC__) && !defined(__EXCEPTIONS)
168 # define FMT_EXCEPTIONS 0
169 #elif FMT_MSC_VERSION && !_HAS_EXCEPTIONS
170 # define FMT_EXCEPTIONS 0
171 #else
172 # define FMT_EXCEPTIONS 1
173 #endif
174 #if FMT_EXCEPTIONS
175 # define FMT_TRY try
176 # define FMT_CATCH(x) catch (x)
177 #else
178 # define FMT_TRY if (true)
179 # define FMT_CATCH(x) if (false)
180 #endif
182 #if FMT_HAS_CPP17_ATTRIBUTE(fallthrough)
183 # define FMT_FALLTHROUGH [[fallthrough]]
184 #elif defined(__clang__)
185 # define FMT_FALLTHROUGH [[clang::fallthrough]]
186 #elif FMT_GCC_VERSION >= 700 && \
187 (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)
188 # define FMT_FALLTHROUGH [[gnu::fallthrough]]
189 #else
190 # define FMT_FALLTHROUGH
191 #endif
193 // Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings.
194 #if FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && !defined(__NVCC__)
195 # define FMT_NORETURN [[noreturn]]
196 #else
197 # define FMT_NORETURN
198 #endif
200 #ifndef FMT_NODISCARD
201 # if FMT_HAS_CPP17_ATTRIBUTE(nodiscard)
202 # define FMT_NODISCARD [[nodiscard]]
203 # else
204 # define FMT_NODISCARD
205 # endif
206 #endif
208 #ifdef FMT_DEPRECATED
209 // Use the provided definition.
210 #elif FMT_HAS_CPP14_ATTRIBUTE(deprecated)
211 # define FMT_DEPRECATED [[deprecated]]
212 #else
213 # define FMT_DEPRECATED /* deprecated */
214 #endif
216 #ifdef FMT_INLINE
217 // Use the provided definition.
218 #elif FMT_GCC_VERSION || FMT_CLANG_VERSION
219 # define FMT_ALWAYS_INLINE inline __attribute__((always_inline))
220 #else
221 # define FMT_ALWAYS_INLINE inline
222 #endif
223 // A version of FMT_INLINE to prevent code bloat in debug mode.
224 #ifdef NDEBUG
225 # define FMT_INLINE FMT_ALWAYS_INLINE
226 #else
227 # define FMT_INLINE inline
228 #endif
230 #if FMT_GCC_VERSION || FMT_CLANG_VERSION
231 # define FMT_VISIBILITY(value) __attribute__((visibility(value)))
232 #else
233 # define FMT_VISIBILITY(value)
234 #endif
236 #ifndef FMT_GCC_PRAGMA
237 // Workaround a _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884
238 // and an nvhpc warning: https://github.com/fmtlib/fmt/pull/2582.
239 # if FMT_GCC_VERSION >= 504 && !defined(__NVCOMPILER)
240 # define FMT_GCC_PRAGMA(arg) _Pragma(arg)
241 # else
242 # define FMT_GCC_PRAGMA(arg)
243 # endif
244 #endif
246 // GCC < 5 requires this-> in decltype.
247 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 500
248 # define FMT_DECLTYPE_THIS this->
249 #else
250 # define FMT_DECLTYPE_THIS
251 #endif
253 #if FMT_MSC_VERSION
254 # define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__))
255 # define FMT_UNCHECKED_ITERATOR(It) \
256 using _Unchecked_type = It // Mark iterator as checked.
257 #else
258 # define FMT_MSC_WARNING(...)
259 # define FMT_UNCHECKED_ITERATOR(It) using unchecked_type = It
260 #endif
262 #ifndef FMT_BEGIN_NAMESPACE
263 # define FMT_BEGIN_NAMESPACE \
264 namespace fmt { \
265 inline namespace v11 {
266 # define FMT_END_NAMESPACE \
269 #endif
271 #ifndef FMT_EXPORT
272 # define FMT_EXPORT
273 # define FMT_BEGIN_EXPORT
274 # define FMT_END_EXPORT
275 #endif
277 #if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
278 # if defined(FMT_LIB_EXPORT)
279 # define FMT_API __declspec(dllexport)
280 # elif defined(FMT_SHARED)
281 # define FMT_API __declspec(dllimport)
282 # endif
283 #elif defined(FMT_LIB_EXPORT) || defined(FMT_SHARED)
284 # define FMT_API FMT_VISIBILITY("default")
285 #endif
286 #ifndef FMT_API
287 # define FMT_API
288 #endif
290 #ifndef FMT_UNICODE
291 # define FMT_UNICODE 1
292 #endif
294 // Check if rtti is available.
295 #ifndef FMT_USE_RTTI
296 // __RTTI is for EDG compilers. _CPPRTTI is for MSVC.
297 # if defined(__GXX_RTTI) || FMT_HAS_FEATURE(cxx_rtti) || defined(_CPPRTTI) || \
298 defined(__INTEL_RTTI__) || defined(__RTTI)
299 # define FMT_USE_RTTI 1
300 # else
301 # define FMT_USE_RTTI 0
302 # endif
303 #endif
305 #define FMT_FWD(...) static_cast<decltype(__VA_ARGS__)&&>(__VA_ARGS__)
307 // Enable minimal optimizations for more compact code in debug mode.
308 FMT_GCC_PRAGMA("GCC push_options")
309 #if !defined(__OPTIMIZE__) && !defined(__CUDACC__)
310 FMT_GCC_PRAGMA("GCC optimize(\"Og\")")
311 #endif
313 FMT_BEGIN_NAMESPACE
315 // Implementations of enable_if_t and other metafunctions for older systems.
316 template <bool B, typename T = void>
317 using enable_if_t = typename std::enable_if<B, T>::type;
318 template <bool B, typename T, typename F>
319 using conditional_t = typename std::conditional<B, T, F>::type;
320 template <bool B> using bool_constant = std::integral_constant<bool, B>;
321 template <typename T>
322 using remove_reference_t = typename std::remove_reference<T>::type;
323 template <typename T>
324 using remove_const_t = typename std::remove_const<T>::type;
325 template <typename T>
326 using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
327 template <typename T> struct type_identity {
328 using type = T;
330 template <typename T> using type_identity_t = typename type_identity<T>::type;
331 template <typename T>
332 using make_unsigned_t = typename std::make_unsigned<T>::type;
333 template <typename T>
334 using underlying_t = typename std::underlying_type<T>::type;
336 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 500
337 // A workaround for gcc 4.8 to make void_t work in a SFINAE context.
338 template <typename...> struct void_t_impl {
339 using type = void;
341 template <typename... T> using void_t = typename void_t_impl<T...>::type;
342 #else
343 template <typename...> using void_t = void;
344 #endif
346 struct monostate {
347 constexpr monostate() {}
350 // An enable_if helper to be used in template parameters which results in much
351 // shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed
352 // to workaround a bug in MSVC 2019 (see #1140 and #1186).
353 #ifdef FMT_DOC
354 # define FMT_ENABLE_IF(...)
355 #else
356 # define FMT_ENABLE_IF(...) fmt::enable_if_t<(__VA_ARGS__), int> = 0
357 #endif
359 // This is defined in base.h instead of format.h to avoid injecting in std.
360 // It is a template to avoid undesirable implicit conversions to std::byte.
361 #ifdef __cpp_lib_byte
362 template <typename T, FMT_ENABLE_IF(std::is_same<T, std::byte>::value)>
363 inline auto format_as(T b) -> unsigned char {
364 return static_cast<unsigned char>(b);
366 #endif
368 namespace detail {
369 // Suppresses "unused variable" warnings with the method described in
370 // https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/.
371 // (void)var does not work on many Intel compilers.
372 template <typename... T> FMT_CONSTEXPR void ignore_unused(const T&...) {}
374 constexpr auto is_constant_evaluated(bool default_value = false) noexcept
375 -> bool {
376 // Workaround for incompatibility between libstdc++ consteval-based
377 // std::is_constant_evaluated() implementation and clang-14:
378 // https://github.com/fmtlib/fmt/issues/3247.
379 #if FMT_CPLUSPLUS >= 202002L && FMT_GLIBCXX_RELEASE >= 12 && \
380 (FMT_CLANG_VERSION >= 1400 && FMT_CLANG_VERSION < 1500)
381 ignore_unused(default_value);
382 return __builtin_is_constant_evaluated();
383 #elif defined(__cpp_lib_is_constant_evaluated)
384 ignore_unused(default_value);
385 return std::is_constant_evaluated();
386 #else
387 return default_value;
388 #endif
391 // Suppresses "conditional expression is constant" warnings.
392 template <typename T> constexpr auto const_check(T value) -> T { return value; }
394 FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
395 const char* message);
397 #if defined(FMT_ASSERT)
398 // Use the provided definition.
399 #elif defined(NDEBUG)
400 // FMT_ASSERT is not empty to avoid -Wempty-body.
401 # define FMT_ASSERT(condition, message) \
402 fmt::detail::ignore_unused((condition), (message))
403 #else
404 # define FMT_ASSERT(condition, message) \
405 ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
406 ? (void)0 \
407 : fmt::detail::assert_fail(__FILE__, __LINE__, (message)))
408 #endif
410 #ifdef FMT_USE_INT128
411 // Do nothing.
412 #elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \
413 !(FMT_CLANG_VERSION && FMT_MSC_VERSION)
414 # define FMT_USE_INT128 1
415 using int128_opt = __int128_t; // An optional native 128-bit integer.
416 using uint128_opt = __uint128_t;
417 template <typename T> inline auto convert_for_visit(T value) -> T {
418 return value;
420 #else
421 # define FMT_USE_INT128 0
422 #endif
423 #if !FMT_USE_INT128
424 enum class int128_opt {};
425 enum class uint128_opt {};
426 // Reduce template instantiations.
427 template <typename T> auto convert_for_visit(T) -> monostate { return {}; }
428 #endif
430 // Casts a nonnegative integer to unsigned.
431 template <typename Int>
432 FMT_CONSTEXPR auto to_unsigned(Int value) -> make_unsigned_t<Int> {
433 FMT_ASSERT(std::is_unsigned<Int>::value || value >= 0, "negative value");
434 return static_cast<make_unsigned_t<Int>>(value);
437 // A heuristic to detect std::string and std::[experimental::]string_view.
438 // It is mainly used to avoid dependency on <[experimental/]string_view>.
439 template <typename T, typename Enable = void>
440 struct is_std_string_like : std::false_type {};
441 template <typename T>
442 struct is_std_string_like<T, void_t<decltype(std::declval<T>().find_first_of(
443 typename T::value_type(), 0))>>
444 : std::is_convertible<decltype(std::declval<T>().data()),
445 const typename T::value_type*> {};
447 // Returns true iff the literal encoding is UTF-8.
448 constexpr auto is_utf8_enabled() -> bool {
449 // Avoid an MSVC sign extension bug: https://github.com/fmtlib/fmt/pull/2297.
450 using uchar = unsigned char;
451 return sizeof("\u00A7") == 3 && uchar("\u00A7"[0]) == 0xC2 &&
452 uchar("\u00A7"[1]) == 0xA7;
454 constexpr auto use_utf8() -> bool {
455 return !FMT_MSC_VERSION || is_utf8_enabled();
458 static_assert(!FMT_UNICODE || use_utf8(),
459 "Unicode support requires compiling with /utf-8");
461 template <typename Char> FMT_CONSTEXPR auto length(const Char* s) -> size_t {
462 size_t len = 0;
463 while (*s++) ++len;
464 return len;
467 template <typename Char>
468 FMT_CONSTEXPR auto compare(const Char* s1, const Char* s2, std::size_t n)
469 -> int {
470 if (!is_constant_evaluated() && sizeof(Char) == 1) return memcmp(s1, s2, n);
471 for (; n != 0; ++s1, ++s2, --n) {
472 if (*s1 < *s2) return -1;
473 if (*s1 > *s2) return 1;
475 return 0;
478 namespace adl {
479 using namespace std;
481 template <typename Container>
482 auto invoke_back_inserter()
483 -> decltype(back_inserter(std::declval<Container&>()));
484 } // namespace adl
486 template <typename It, typename Enable = std::true_type>
487 struct is_back_insert_iterator : std::false_type {};
489 template <typename It>
490 struct is_back_insert_iterator<
491 It, bool_constant<std::is_same<
492 decltype(adl::invoke_back_inserter<typename It::container_type>()),
493 It>::value>> : std::true_type {};
495 // Extracts a reference to the container from *insert_iterator.
496 template <typename OutputIt>
497 inline auto get_container(OutputIt it) -> typename OutputIt::container_type& {
498 struct accessor : OutputIt {
499 accessor(OutputIt base) : OutputIt(base) {}
500 using OutputIt::container;
502 return *accessor(it).container;
504 } // namespace detail
506 // Checks whether T is a container with contiguous storage.
507 template <typename T> struct is_contiguous : std::false_type {};
510 * An implementation of `std::basic_string_view` for pre-C++17. It provides a
511 * subset of the API. `fmt::basic_string_view` is used for format strings even
512 * if `std::basic_string_view` is available to prevent issues when a library is
513 * compiled with a different `-std` option than the client code (which is not
514 * recommended).
516 FMT_EXPORT
517 template <typename Char> class basic_string_view {
518 private:
519 const Char* data_;
520 size_t size_;
522 public:
523 using value_type = Char;
524 using iterator = const Char*;
526 constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {}
528 /// Constructs a string reference object from a C string and a size.
529 constexpr basic_string_view(const Char* s, size_t count) noexcept
530 : data_(s), size_(count) {}
532 constexpr basic_string_view(std::nullptr_t) = delete;
534 /// Constructs a string reference object from a C string.
535 FMT_CONSTEXPR20
536 basic_string_view(const Char* s)
537 : data_(s),
538 size_(detail::const_check(std::is_same<Char, char>::value &&
539 !detail::is_constant_evaluated(false))
540 ? strlen(reinterpret_cast<const char*>(s))
541 : detail::length(s)) {}
543 /// Constructs a string reference from a `std::basic_string` or a
544 /// `std::basic_string_view` object.
545 template <typename S,
546 FMT_ENABLE_IF(detail::is_std_string_like<S>::value&& std::is_same<
547 typename S::value_type, Char>::value)>
548 FMT_CONSTEXPR basic_string_view(const S& s) noexcept
549 : data_(s.data()), size_(s.size()) {}
551 /// Returns a pointer to the string data.
552 constexpr auto data() const noexcept -> const Char* { return data_; }
554 /// Returns the string size.
555 constexpr auto size() const noexcept -> size_t { return size_; }
557 constexpr auto begin() const noexcept -> iterator { return data_; }
558 constexpr auto end() const noexcept -> iterator { return data_ + size_; }
560 constexpr auto operator[](size_t pos) const noexcept -> const Char& {
561 return data_[pos];
564 FMT_CONSTEXPR void remove_prefix(size_t n) noexcept {
565 data_ += n;
566 size_ -= n;
569 FMT_CONSTEXPR auto starts_with(basic_string_view<Char> sv) const noexcept
570 -> bool {
571 return size_ >= sv.size_ && detail::compare(data_, sv.data_, sv.size_) == 0;
573 FMT_CONSTEXPR auto starts_with(Char c) const noexcept -> bool {
574 return size_ >= 1 && *data_ == c;
576 FMT_CONSTEXPR auto starts_with(const Char* s) const -> bool {
577 return starts_with(basic_string_view<Char>(s));
580 // Lexicographically compare this string reference to other.
581 FMT_CONSTEXPR auto compare(basic_string_view other) const -> int {
582 size_t str_size = size_ < other.size_ ? size_ : other.size_;
583 int result = detail::compare(data_, other.data_, str_size);
584 if (result == 0)
585 result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
586 return result;
589 FMT_CONSTEXPR friend auto operator==(basic_string_view lhs,
590 basic_string_view rhs) -> bool {
591 return lhs.compare(rhs) == 0;
593 friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool {
594 return lhs.compare(rhs) != 0;
596 friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool {
597 return lhs.compare(rhs) < 0;
599 friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool {
600 return lhs.compare(rhs) <= 0;
602 friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool {
603 return lhs.compare(rhs) > 0;
605 friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool {
606 return lhs.compare(rhs) >= 0;
610 FMT_EXPORT
611 using string_view = basic_string_view<char>;
613 /// Specifies if `T` is a character type. Can be specialized by users.
614 FMT_EXPORT
615 template <typename T> struct is_char : std::false_type {};
616 template <> struct is_char<char> : std::true_type {};
618 namespace detail {
620 // Constructs fmt::basic_string_view<Char> from types implicitly convertible
621 // to it, deducing Char. Explicitly convertible types such as the ones returned
622 // from FMT_STRING are intentionally excluded.
623 template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
624 constexpr auto to_string_view(const Char* s) -> basic_string_view<Char> {
625 return s;
627 template <typename T, FMT_ENABLE_IF(is_std_string_like<T>::value)>
628 constexpr auto to_string_view(const T& s)
629 -> basic_string_view<typename T::value_type> {
630 return s;
632 template <typename Char>
633 constexpr auto to_string_view(basic_string_view<Char> s)
634 -> basic_string_view<Char> {
635 return s;
638 template <typename T, typename Enable = void>
639 struct has_to_string_view : std::false_type {};
640 // detail:: is intentional since to_string_view is not an extension point.
641 template <typename T>
642 struct has_to_string_view<
643 T, void_t<decltype(detail::to_string_view(std::declval<T>()))>>
644 : std::true_type {};
646 template <typename Char, Char... C> struct string_literal {
647 static constexpr Char value[sizeof...(C)] = {C...};
648 constexpr operator basic_string_view<Char>() const {
649 return {value, sizeof...(C)};
652 #if FMT_CPLUSPLUS < 201703L
653 template <typename Char, Char... C>
654 constexpr Char string_literal<Char, C...>::value[sizeof...(C)];
655 #endif
657 enum class type {
658 none_type,
659 // Integer types should go first,
660 int_type,
661 uint_type,
662 long_long_type,
663 ulong_long_type,
664 int128_type,
665 uint128_type,
666 bool_type,
667 char_type,
668 last_integer_type = char_type,
669 // followed by floating-point types.
670 float_type,
671 double_type,
672 long_double_type,
673 last_numeric_type = long_double_type,
674 cstring_type,
675 string_type,
676 pointer_type,
677 custom_type
680 // Maps core type T to the corresponding type enum constant.
681 template <typename T, typename Char>
682 struct type_constant : std::integral_constant<type, type::custom_type> {};
684 #define FMT_TYPE_CONSTANT(Type, constant) \
685 template <typename Char> \
686 struct type_constant<Type, Char> \
687 : std::integral_constant<type, type::constant> {}
689 FMT_TYPE_CONSTANT(int, int_type);
690 FMT_TYPE_CONSTANT(unsigned, uint_type);
691 FMT_TYPE_CONSTANT(long long, long_long_type);
692 FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
693 FMT_TYPE_CONSTANT(int128_opt, int128_type);
694 FMT_TYPE_CONSTANT(uint128_opt, uint128_type);
695 FMT_TYPE_CONSTANT(bool, bool_type);
696 FMT_TYPE_CONSTANT(Char, char_type);
697 FMT_TYPE_CONSTANT(float, float_type);
698 FMT_TYPE_CONSTANT(double, double_type);
699 FMT_TYPE_CONSTANT(long double, long_double_type);
700 FMT_TYPE_CONSTANT(const Char*, cstring_type);
701 FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
702 FMT_TYPE_CONSTANT(const void*, pointer_type);
704 constexpr auto is_integral_type(type t) -> bool {
705 return t > type::none_type && t <= type::last_integer_type;
707 constexpr auto is_arithmetic_type(type t) -> bool {
708 return t > type::none_type && t <= type::last_numeric_type;
711 constexpr auto set(type rhs) -> int { return 1 << static_cast<int>(rhs); }
712 constexpr auto in(type t, int set) -> bool {
713 return ((set >> static_cast<int>(t)) & 1) != 0;
716 // Bitsets of types.
717 enum {
718 sint_set =
719 set(type::int_type) | set(type::long_long_type) | set(type::int128_type),
720 uint_set = set(type::uint_type) | set(type::ulong_long_type) |
721 set(type::uint128_type),
722 bool_set = set(type::bool_type),
723 char_set = set(type::char_type),
724 float_set = set(type::float_type) | set(type::double_type) |
725 set(type::long_double_type),
726 string_set = set(type::string_type),
727 cstring_set = set(type::cstring_type),
728 pointer_set = set(type::pointer_type)
730 } // namespace detail
732 /// Reports a format error at compile time or, via a `format_error` exception,
733 /// at runtime.
734 // This function is intentionally not constexpr to give a compile-time error.
735 FMT_NORETURN FMT_API void report_error(const char* message);
737 FMT_DEPRECATED FMT_NORETURN inline void throw_format_error(
738 const char* message) {
739 report_error(message);
742 /// String's character (code unit) type.
743 template <typename S,
744 typename V = decltype(detail::to_string_view(std::declval<S>()))>
745 using char_t = typename V::value_type;
748 * Parsing context consisting of a format string range being parsed and an
749 * argument counter for automatic indexing.
750 * You can use the `format_parse_context` type alias for `char` instead.
752 FMT_EXPORT
753 template <typename Char> class basic_format_parse_context {
754 private:
755 basic_string_view<Char> format_str_;
756 int next_arg_id_;
758 FMT_CONSTEXPR void do_check_arg_id(int id);
760 public:
761 using char_type = Char;
762 using iterator = const Char*;
764 explicit constexpr basic_format_parse_context(
765 basic_string_view<Char> format_str, int next_arg_id = 0)
766 : format_str_(format_str), next_arg_id_(next_arg_id) {}
768 /// Returns an iterator to the beginning of the format string range being
769 /// parsed.
770 constexpr auto begin() const noexcept -> iterator {
771 return format_str_.begin();
774 /// Returns an iterator past the end of the format string range being parsed.
775 constexpr auto end() const noexcept -> iterator { return format_str_.end(); }
777 /// Advances the begin iterator to `it`.
778 FMT_CONSTEXPR void advance_to(iterator it) {
779 format_str_.remove_prefix(detail::to_unsigned(it - begin()));
782 /// Reports an error if using the manual argument indexing; otherwise returns
783 /// the next argument index and switches to the automatic indexing.
784 FMT_CONSTEXPR auto next_arg_id() -> int {
785 if (next_arg_id_ < 0) {
786 report_error("cannot switch from manual to automatic argument indexing");
787 return 0;
789 int id = next_arg_id_++;
790 do_check_arg_id(id);
791 return id;
794 /// Reports an error if using the automatic argument indexing; otherwise
795 /// switches to the manual indexing.
796 FMT_CONSTEXPR void check_arg_id(int id) {
797 if (next_arg_id_ > 0) {
798 report_error("cannot switch from automatic to manual argument indexing");
799 return;
801 next_arg_id_ = -1;
802 do_check_arg_id(id);
804 FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {
805 next_arg_id_ = -1;
807 FMT_CONSTEXPR void check_dynamic_spec(int arg_id);
810 FMT_EXPORT
811 using format_parse_context = basic_format_parse_context<char>;
813 namespace detail {
814 // A parse context with extra data used only in compile-time checks.
815 template <typename Char>
816 class compile_parse_context : public basic_format_parse_context<Char> {
817 private:
818 int num_args_;
819 const type* types_;
820 using base = basic_format_parse_context<Char>;
822 public:
823 explicit FMT_CONSTEXPR compile_parse_context(
824 basic_string_view<Char> format_str, int num_args, const type* types,
825 int next_arg_id = 0)
826 : base(format_str, next_arg_id), num_args_(num_args), types_(types) {}
828 constexpr auto num_args() const -> int { return num_args_; }
829 constexpr auto arg_type(int id) const -> type { return types_[id]; }
831 FMT_CONSTEXPR auto next_arg_id() -> int {
832 int id = base::next_arg_id();
833 if (id >= num_args_) report_error("argument not found");
834 return id;
837 FMT_CONSTEXPR void check_arg_id(int id) {
838 base::check_arg_id(id);
839 if (id >= num_args_) report_error("argument not found");
841 using base::check_arg_id;
843 FMT_CONSTEXPR void check_dynamic_spec(int arg_id) {
844 detail::ignore_unused(arg_id);
845 if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id]))
846 report_error("width/precision is not integer");
850 /// A contiguous memory buffer with an optional growing ability. It is an
851 /// internal class and shouldn't be used directly, only via `memory_buffer`.
852 template <typename T> class buffer {
853 private:
854 T* ptr_;
855 size_t size_;
856 size_t capacity_;
858 using grow_fun = void (*)(buffer& buf, size_t capacity);
859 grow_fun grow_;
861 protected:
862 // Don't initialize ptr_ since it is not accessed to save a few cycles.
863 FMT_MSC_WARNING(suppress : 26495)
864 FMT_CONSTEXPR20 buffer(grow_fun grow, size_t sz) noexcept
865 : size_(sz), capacity_(sz), grow_(grow) {}
867 constexpr buffer(grow_fun grow, T* p = nullptr, size_t sz = 0,
868 size_t cap = 0) noexcept
869 : ptr_(p), size_(sz), capacity_(cap), grow_(grow) {}
871 FMT_CONSTEXPR20 ~buffer() = default;
872 buffer(buffer&&) = default;
874 /// Sets the buffer data and capacity.
875 FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept {
876 ptr_ = buf_data;
877 capacity_ = buf_capacity;
880 public:
881 using value_type = T;
882 using const_reference = const T&;
884 buffer(const buffer&) = delete;
885 void operator=(const buffer&) = delete;
887 auto begin() noexcept -> T* { return ptr_; }
888 auto end() noexcept -> T* { return ptr_ + size_; }
890 auto begin() const noexcept -> const T* { return ptr_; }
891 auto end() const noexcept -> const T* { return ptr_ + size_; }
893 /// Returns the size of this buffer.
894 constexpr auto size() const noexcept -> size_t { return size_; }
896 /// Returns the capacity of this buffer.
897 constexpr auto capacity() const noexcept -> size_t { return capacity_; }
899 /// Returns a pointer to the buffer data (not null-terminated).
900 FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; }
901 FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; }
903 /// Clears this buffer.
904 void clear() { size_ = 0; }
906 // Tries resizing the buffer to contain `count` elements. If T is a POD type
907 // the new elements may not be initialized.
908 FMT_CONSTEXPR void try_resize(size_t count) {
909 try_reserve(count);
910 size_ = count <= capacity_ ? count : capacity_;
913 // Tries increasing the buffer capacity to `new_capacity`. It can increase the
914 // capacity by a smaller amount than requested but guarantees there is space
915 // for at least one additional element either by increasing the capacity or by
916 // flushing the buffer if it is full.
917 FMT_CONSTEXPR void try_reserve(size_t new_capacity) {
918 if (new_capacity > capacity_) grow_(*this, new_capacity);
921 FMT_CONSTEXPR void push_back(const T& value) {
922 try_reserve(size_ + 1);
923 ptr_[size_++] = value;
926 /// Appends data to the end of the buffer.
927 template <typename U> void append(const U* begin, const U* end) {
928 while (begin != end) {
929 auto count = to_unsigned(end - begin);
930 try_reserve(size_ + count);
931 auto free_cap = capacity_ - size_;
932 if (free_cap < count) count = free_cap;
933 // A loop is faster than memcpy on small sizes.
934 T* out = ptr_ + size_;
935 for (size_t i = 0; i < count; ++i) out[i] = begin[i];
936 size_ += count;
937 begin += count;
941 template <typename Idx> FMT_CONSTEXPR auto operator[](Idx index) -> T& {
942 return ptr_[index];
944 template <typename Idx>
945 FMT_CONSTEXPR auto operator[](Idx index) const -> const T& {
946 return ptr_[index];
950 struct buffer_traits {
951 explicit buffer_traits(size_t) {}
952 auto count() const -> size_t { return 0; }
953 auto limit(size_t size) -> size_t { return size; }
956 class fixed_buffer_traits {
957 private:
958 size_t count_ = 0;
959 size_t limit_;
961 public:
962 explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}
963 auto count() const -> size_t { return count_; }
964 auto limit(size_t size) -> size_t {
965 size_t n = limit_ > count_ ? limit_ - count_ : 0;
966 count_ += size;
967 return size < n ? size : n;
971 // A buffer that writes to an output iterator when flushed.
972 template <typename OutputIt, typename T, typename Traits = buffer_traits>
973 class iterator_buffer : public Traits, public buffer<T> {
974 private:
975 OutputIt out_;
976 enum { buffer_size = 256 };
977 T data_[buffer_size];
979 static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
980 if (buf.size() == buffer_size) static_cast<iterator_buffer&>(buf).flush();
983 void flush() {
984 auto size = this->size();
985 this->clear();
986 const T* begin = data_;
987 const T* end = begin + this->limit(size);
988 while (begin != end) *out_++ = *begin++;
991 public:
992 explicit iterator_buffer(OutputIt out, size_t n = buffer_size)
993 : Traits(n), buffer<T>(grow, data_, 0, buffer_size), out_(out) {}
994 iterator_buffer(iterator_buffer&& other) noexcept
995 : Traits(other),
996 buffer<T>(grow, data_, 0, buffer_size),
997 out_(other.out_) {}
998 ~iterator_buffer() {
999 // Don't crash if flush fails during unwinding.
1000 FMT_TRY { flush(); }
1001 FMT_CATCH(...) {}
1004 auto out() -> OutputIt {
1005 flush();
1006 return out_;
1008 auto count() const -> size_t { return Traits::count() + this->size(); }
1011 template <typename T>
1012 class iterator_buffer<T*, T, fixed_buffer_traits> : public fixed_buffer_traits,
1013 public buffer<T> {
1014 private:
1015 T* out_;
1016 enum { buffer_size = 256 };
1017 T data_[buffer_size];
1019 static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
1020 if (buf.size() == buf.capacity())
1021 static_cast<iterator_buffer&>(buf).flush();
1024 void flush() {
1025 size_t n = this->limit(this->size());
1026 if (this->data() == out_) {
1027 out_ += n;
1028 this->set(data_, buffer_size);
1030 this->clear();
1033 public:
1034 explicit iterator_buffer(T* out, size_t n = buffer_size)
1035 : fixed_buffer_traits(n), buffer<T>(grow, out, 0, n), out_(out) {}
1036 iterator_buffer(iterator_buffer&& other) noexcept
1037 : fixed_buffer_traits(other),
1038 buffer<T>(static_cast<iterator_buffer&&>(other)),
1039 out_(other.out_) {
1040 if (this->data() != out_) {
1041 this->set(data_, buffer_size);
1042 this->clear();
1045 ~iterator_buffer() { flush(); }
1047 auto out() -> T* {
1048 flush();
1049 return out_;
1051 auto count() const -> size_t {
1052 return fixed_buffer_traits::count() + this->size();
1056 template <typename T> class iterator_buffer<T*, T> : public buffer<T> {
1057 public:
1058 explicit iterator_buffer(T* out, size_t = 0)
1059 : buffer<T>([](buffer<T>&, size_t) {}, out, 0, ~size_t()) {}
1061 auto out() -> T* { return &*this->end(); }
1064 // A buffer that writes to a container with the contiguous storage.
1065 template <typename OutputIt>
1066 class iterator_buffer<
1067 OutputIt,
1068 enable_if_t<detail::is_back_insert_iterator<OutputIt>::value &&
1069 is_contiguous<typename OutputIt::container_type>::value,
1070 typename OutputIt::container_type::value_type>>
1071 : public buffer<typename OutputIt::container_type::value_type> {
1072 private:
1073 using container_type = typename OutputIt::container_type;
1074 using value_type = typename container_type::value_type;
1075 container_type& container_;
1077 static FMT_CONSTEXPR void grow(buffer<value_type>& buf, size_t capacity) {
1078 auto& self = static_cast<iterator_buffer&>(buf);
1079 self.container_.resize(capacity);
1080 self.set(&self.container_[0], capacity);
1083 public:
1084 explicit iterator_buffer(container_type& c)
1085 : buffer<value_type>(grow, c.size()), container_(c) {}
1086 explicit iterator_buffer(OutputIt out, size_t = 0)
1087 : iterator_buffer(get_container(out)) {}
1089 auto out() -> OutputIt { return back_inserter(container_); }
1092 // A buffer that counts the number of code units written discarding the output.
1093 template <typename T = char> class counting_buffer : public buffer<T> {
1094 private:
1095 enum { buffer_size = 256 };
1096 T data_[buffer_size];
1097 size_t count_ = 0;
1099 static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
1100 if (buf.size() != buffer_size) return;
1101 static_cast<counting_buffer&>(buf).count_ += buf.size();
1102 buf.clear();
1105 public:
1106 counting_buffer() : buffer<T>(grow, data_, 0, buffer_size) {}
1108 auto count() -> size_t { return count_ + this->size(); }
1110 } // namespace detail
1112 template <typename Char>
1113 FMT_CONSTEXPR void basic_format_parse_context<Char>::do_check_arg_id(int id) {
1114 // Argument id is only checked at compile-time during parsing because
1115 // formatting has its own validation.
1116 if (detail::is_constant_evaluated() &&
1117 (!FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200)) {
1118 using context = detail::compile_parse_context<Char>;
1119 if (id >= static_cast<context*>(this)->num_args())
1120 report_error("argument not found");
1124 template <typename Char>
1125 FMT_CONSTEXPR void basic_format_parse_context<Char>::check_dynamic_spec(
1126 int arg_id) {
1127 if (detail::is_constant_evaluated() &&
1128 (!FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200)) {
1129 using context = detail::compile_parse_context<Char>;
1130 static_cast<context*>(this)->check_dynamic_spec(arg_id);
1134 FMT_EXPORT template <typename Context> class basic_format_arg;
1135 FMT_EXPORT template <typename Context> class basic_format_args;
1136 FMT_EXPORT template <typename Context> class dynamic_format_arg_store;
1138 // A formatter for objects of type T.
1139 FMT_EXPORT
1140 template <typename T, typename Char = char, typename Enable = void>
1141 struct formatter {
1142 // A deleted default constructor indicates a disabled formatter.
1143 formatter() = delete;
1146 // Specifies if T has an enabled formatter specialization. A type can be
1147 // formattable even if it doesn't have a formatter e.g. via a conversion.
1148 template <typename T, typename Context>
1149 using has_formatter =
1150 std::is_constructible<typename Context::template formatter_type<T>>;
1152 // An output iterator that appends to a buffer. It is used instead of
1153 // back_insert_iterator to reduce symbol sizes and avoid <iterator> dependency.
1154 template <typename T> class basic_appender {
1155 private:
1156 detail::buffer<T>* buffer_;
1158 friend auto get_container(basic_appender app) -> detail::buffer<T>& {
1159 return *app.buffer_;
1162 public:
1163 using iterator_category = int;
1164 using value_type = T;
1165 using difference_type = ptrdiff_t;
1166 using pointer = T*;
1167 using reference = T&;
1168 using container_type = detail::buffer<T>;
1169 FMT_UNCHECKED_ITERATOR(basic_appender);
1171 FMT_CONSTEXPR basic_appender(detail::buffer<T>& buf) : buffer_(&buf) {}
1173 auto operator=(T c) -> basic_appender& {
1174 buffer_->push_back(c);
1175 return *this;
1177 auto operator*() -> basic_appender& { return *this; }
1178 auto operator++() -> basic_appender& { return *this; }
1179 auto operator++(int) -> basic_appender { return *this; }
1182 using appender = basic_appender<char>;
1184 namespace detail {
1185 template <typename T>
1186 struct is_back_insert_iterator<basic_appender<T>> : std::true_type {};
1188 template <typename T, typename Enable = void>
1189 struct locking : std::true_type {};
1190 template <typename T>
1191 struct locking<T, void_t<typename formatter<remove_cvref_t<T>>::nonlocking>>
1192 : std::false_type {};
1194 template <typename T = int> FMT_CONSTEXPR inline auto is_locking() -> bool {
1195 return locking<T>::value;
1197 template <typename T1, typename T2, typename... Tail>
1198 FMT_CONSTEXPR inline auto is_locking() -> bool {
1199 return locking<T1>::value || is_locking<T2, Tail...>();
1202 // An optimized version of std::copy with the output value type (T).
1203 template <typename T, typename InputIt, typename OutputIt,
1204 FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value)>
1205 auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt {
1206 get_container(out).append(begin, end);
1207 return out;
1210 template <typename T, typename InputIt, typename OutputIt,
1211 FMT_ENABLE_IF(!is_back_insert_iterator<OutputIt>::value)>
1212 FMT_CONSTEXPR auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt {
1213 while (begin != end) *out++ = static_cast<T>(*begin++);
1214 return out;
1217 template <typename T, typename V, typename OutputIt>
1218 FMT_CONSTEXPR auto copy(basic_string_view<V> s, OutputIt out) -> OutputIt {
1219 return copy<T>(s.begin(), s.end(), out);
1222 template <typename Context, typename T>
1223 constexpr auto has_const_formatter_impl(T*)
1224 -> decltype(typename Context::template formatter_type<T>().format(
1225 std::declval<const T&>(), std::declval<Context&>()),
1226 true) {
1227 return true;
1229 template <typename Context>
1230 constexpr auto has_const_formatter_impl(...) -> bool {
1231 return false;
1233 template <typename T, typename Context>
1234 constexpr auto has_const_formatter() -> bool {
1235 return has_const_formatter_impl<Context>(static_cast<T*>(nullptr));
1238 template <typename It, typename Enable = std::true_type>
1239 struct is_buffer_appender : std::false_type {};
1240 template <typename It>
1241 struct is_buffer_appender<
1242 It, bool_constant<
1243 is_back_insert_iterator<It>::value &&
1244 std::is_base_of<buffer<typename It::container_type::value_type>,
1245 typename It::container_type>::value>>
1246 : std::true_type {};
1248 // Maps an output iterator to a buffer.
1249 template <typename T, typename OutputIt,
1250 FMT_ENABLE_IF(!is_buffer_appender<OutputIt>::value)>
1251 auto get_buffer(OutputIt out) -> iterator_buffer<OutputIt, T> {
1252 return iterator_buffer<OutputIt, T>(out);
1254 template <typename T, typename OutputIt,
1255 FMT_ENABLE_IF(is_buffer_appender<OutputIt>::value)>
1256 auto get_buffer(OutputIt out) -> buffer<T>& {
1257 return get_container(out);
1260 template <typename Buf, typename OutputIt>
1261 auto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) {
1262 return buf.out();
1264 template <typename T, typename OutputIt>
1265 auto get_iterator(buffer<T>&, OutputIt out) -> OutputIt {
1266 return out;
1269 struct view {};
1271 template <typename Char, typename T> struct named_arg : view {
1272 const Char* name;
1273 const T& value;
1274 named_arg(const Char* n, const T& v) : name(n), value(v) {}
1277 template <typename Char> struct named_arg_info {
1278 const Char* name;
1279 int id;
1282 template <typename T> struct is_named_arg : std::false_type {};
1283 template <typename T> struct is_statically_named_arg : std::false_type {};
1285 template <typename T, typename Char>
1286 struct is_named_arg<named_arg<Char, T>> : std::true_type {};
1288 template <bool B = false> constexpr auto count() -> size_t { return B ? 1 : 0; }
1289 template <bool B1, bool B2, bool... Tail> constexpr auto count() -> size_t {
1290 return (B1 ? 1 : 0) + count<B2, Tail...>();
1293 template <typename... Args> constexpr auto count_named_args() -> size_t {
1294 return count<is_named_arg<Args>::value...>();
1297 template <typename... Args>
1298 constexpr auto count_statically_named_args() -> size_t {
1299 return count<is_statically_named_arg<Args>::value...>();
1302 struct unformattable {};
1303 struct unformattable_char : unformattable {};
1304 struct unformattable_pointer : unformattable {};
1306 template <typename Char> struct string_value {
1307 const Char* data;
1308 size_t size;
1311 template <typename Char> struct named_arg_value {
1312 const named_arg_info<Char>* data;
1313 size_t size;
1316 template <typename Context> struct custom_value {
1317 using parse_context = typename Context::parse_context_type;
1318 void* value;
1319 void (*format)(void* arg, parse_context& parse_ctx, Context& ctx);
1322 // A formatting argument value.
1323 template <typename Context> class value {
1324 public:
1325 using char_type = typename Context::char_type;
1327 union {
1328 monostate no_value;
1329 int int_value;
1330 unsigned uint_value;
1331 long long long_long_value;
1332 unsigned long long ulong_long_value;
1333 int128_opt int128_value;
1334 uint128_opt uint128_value;
1335 bool bool_value;
1336 char_type char_value;
1337 float float_value;
1338 double double_value;
1339 long double long_double_value;
1340 const void* pointer;
1341 string_value<char_type> string;
1342 custom_value<Context> custom;
1343 named_arg_value<char_type> named_args;
1346 constexpr FMT_ALWAYS_INLINE value() : no_value() {}
1347 constexpr FMT_ALWAYS_INLINE value(int val) : int_value(val) {}
1348 constexpr FMT_ALWAYS_INLINE value(unsigned val) : uint_value(val) {}
1349 constexpr FMT_ALWAYS_INLINE value(long long val) : long_long_value(val) {}
1350 constexpr FMT_ALWAYS_INLINE value(unsigned long long val)
1351 : ulong_long_value(val) {}
1352 FMT_ALWAYS_INLINE value(int128_opt val) : int128_value(val) {}
1353 FMT_ALWAYS_INLINE value(uint128_opt val) : uint128_value(val) {}
1354 constexpr FMT_ALWAYS_INLINE value(float val) : float_value(val) {}
1355 constexpr FMT_ALWAYS_INLINE value(double val) : double_value(val) {}
1356 FMT_ALWAYS_INLINE value(long double val) : long_double_value(val) {}
1357 constexpr FMT_ALWAYS_INLINE value(bool val) : bool_value(val) {}
1358 constexpr FMT_ALWAYS_INLINE value(char_type val) : char_value(val) {}
1359 FMT_CONSTEXPR FMT_ALWAYS_INLINE value(const char_type* val) {
1360 string.data = val;
1361 if (is_constant_evaluated()) string.size = {};
1363 FMT_CONSTEXPR FMT_ALWAYS_INLINE value(basic_string_view<char_type> val) {
1364 string.data = val.data();
1365 string.size = val.size();
1367 FMT_ALWAYS_INLINE value(const void* val) : pointer(val) {}
1368 FMT_ALWAYS_INLINE value(const named_arg_info<char_type>* args, size_t size)
1369 : named_args{args, size} {}
1371 template <typename T> FMT_CONSTEXPR20 FMT_ALWAYS_INLINE value(T& val) {
1372 using value_type = remove_const_t<T>;
1373 // T may overload operator& e.g. std::vector<bool>::reference in libc++.
1374 #if defined(__cpp_if_constexpr)
1375 if constexpr (std::is_same<decltype(&val), T*>::value)
1376 custom.value = const_cast<value_type*>(&val);
1377 #endif
1378 if (!is_constant_evaluated())
1379 custom.value = const_cast<char*>(&reinterpret_cast<const char&>(val));
1380 // Get the formatter type through the context to allow different contexts
1381 // have different extension points, e.g. `formatter<T>` for `format` and
1382 // `printf_formatter<T>` for `printf`.
1383 custom.format = format_custom_arg<
1384 value_type, typename Context::template formatter_type<value_type>>;
1386 value(unformattable);
1387 value(unformattable_char);
1388 value(unformattable_pointer);
1390 private:
1391 // Formats an argument of a custom type, such as a user-defined class.
1392 template <typename T, typename Formatter>
1393 static void format_custom_arg(void* arg,
1394 typename Context::parse_context_type& parse_ctx,
1395 Context& ctx) {
1396 auto f = Formatter();
1397 parse_ctx.advance_to(f.parse(parse_ctx));
1398 using qualified_type =
1399 conditional_t<has_const_formatter<T, Context>(), const T, T>;
1400 // format must be const for compatibility with std::format and compilation.
1401 const auto& cf = f;
1402 ctx.advance_to(cf.format(*static_cast<qualified_type*>(arg), ctx));
1406 // To minimize the number of types we need to deal with, long is translated
1407 // either to int or to long long depending on its size.
1408 enum { long_short = sizeof(long) == sizeof(int) };
1409 using long_type = conditional_t<long_short, int, long long>;
1410 using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
1412 template <typename T> struct format_as_result {
1413 template <typename U,
1414 FMT_ENABLE_IF(std::is_enum<U>::value || std::is_class<U>::value)>
1415 static auto map(U*) -> remove_cvref_t<decltype(format_as(std::declval<U>()))>;
1416 static auto map(...) -> void;
1418 using type = decltype(map(static_cast<T*>(nullptr)));
1420 template <typename T> using format_as_t = typename format_as_result<T>::type;
1422 template <typename T>
1423 struct has_format_as
1424 : bool_constant<!std::is_same<format_as_t<T>, void>::value> {};
1426 #define FMT_MAP_API FMT_CONSTEXPR FMT_ALWAYS_INLINE
1428 // Maps formatting arguments to core types.
1429 // arg_mapper reports errors by returning unformattable instead of using
1430 // static_assert because it's used in the is_formattable trait.
1431 template <typename Context> struct arg_mapper {
1432 using char_type = typename Context::char_type;
1434 FMT_MAP_API auto map(signed char val) -> int { return val; }
1435 FMT_MAP_API auto map(unsigned char val) -> unsigned { return val; }
1436 FMT_MAP_API auto map(short val) -> int { return val; }
1437 FMT_MAP_API auto map(unsigned short val) -> unsigned { return val; }
1438 FMT_MAP_API auto map(int val) -> int { return val; }
1439 FMT_MAP_API auto map(unsigned val) -> unsigned { return val; }
1440 FMT_MAP_API auto map(long val) -> long_type { return val; }
1441 FMT_MAP_API auto map(unsigned long val) -> ulong_type { return val; }
1442 FMT_MAP_API auto map(long long val) -> long long { return val; }
1443 FMT_MAP_API auto map(unsigned long long val) -> unsigned long long {
1444 return val;
1446 FMT_MAP_API auto map(int128_opt val) -> int128_opt { return val; }
1447 FMT_MAP_API auto map(uint128_opt val) -> uint128_opt { return val; }
1448 FMT_MAP_API auto map(bool val) -> bool { return val; }
1450 template <typename T, FMT_ENABLE_IF(std::is_same<T, char>::value ||
1451 std::is_same<T, char_type>::value)>
1452 FMT_MAP_API auto map(T val) -> char_type {
1453 return val;
1455 template <typename T, enable_if_t<(std::is_same<T, wchar_t>::value ||
1456 #ifdef __cpp_char8_t
1457 std::is_same<T, char8_t>::value ||
1458 #endif
1459 std::is_same<T, char16_t>::value ||
1460 std::is_same<T, char32_t>::value) &&
1461 !std::is_same<T, char_type>::value,
1462 int> = 0>
1463 FMT_MAP_API auto map(T) -> unformattable_char {
1464 return {};
1467 FMT_MAP_API auto map(float val) -> float { return val; }
1468 FMT_MAP_API auto map(double val) -> double { return val; }
1469 FMT_MAP_API auto map(long double val) -> long double { return val; }
1471 FMT_MAP_API auto map(char_type* val) -> const char_type* { return val; }
1472 FMT_MAP_API auto map(const char_type* val) -> const char_type* { return val; }
1473 template <typename T, typename Char = char_t<T>,
1474 FMT_ENABLE_IF(std::is_same<Char, char_type>::value &&
1475 !std::is_pointer<T>::value)>
1476 FMT_MAP_API auto map(const T& val) -> basic_string_view<Char> {
1477 return to_string_view(val);
1479 template <typename T, typename Char = char_t<T>,
1480 FMT_ENABLE_IF(!std::is_same<Char, char_type>::value &&
1481 !std::is_pointer<T>::value)>
1482 FMT_MAP_API auto map(const T&) -> unformattable_char {
1483 return {};
1486 FMT_MAP_API auto map(void* val) -> const void* { return val; }
1487 FMT_MAP_API auto map(const void* val) -> const void* { return val; }
1488 FMT_MAP_API auto map(volatile void* val) -> const void* {
1489 return const_cast<const void*>(val);
1491 FMT_MAP_API auto map(const volatile void* val) -> const void* {
1492 return const_cast<const void*>(val);
1494 FMT_MAP_API auto map(std::nullptr_t val) -> const void* { return val; }
1496 // Use SFINAE instead of a const T* parameter to avoid a conflict with the
1497 // array overload.
1498 template <
1499 typename T,
1500 FMT_ENABLE_IF(
1501 std::is_pointer<T>::value || std::is_member_pointer<T>::value ||
1502 std::is_function<typename std::remove_pointer<T>::type>::value ||
1503 (std::is_array<T>::value &&
1504 !std::is_convertible<T, const char_type*>::value))>
1505 FMT_CONSTEXPR auto map(const T&) -> unformattable_pointer {
1506 return {};
1509 template <typename T, std::size_t N,
1510 FMT_ENABLE_IF(!std::is_same<T, wchar_t>::value)>
1511 FMT_MAP_API auto map(const T (&values)[N]) -> const T (&)[N] {
1512 return values;
1515 // Only map owning types because mapping views can be unsafe.
1516 template <typename T, typename U = format_as_t<T>,
1517 FMT_ENABLE_IF(std::is_arithmetic<U>::value)>
1518 FMT_MAP_API auto map(const T& val) -> decltype(FMT_DECLTYPE_THIS map(U())) {
1519 return map(format_as(val));
1522 template <typename T, typename U = remove_const_t<T>>
1523 struct formattable : bool_constant<has_const_formatter<U, Context>() ||
1524 (has_formatter<U, Context>::value &&
1525 !std::is_const<T>::value)> {};
1527 template <typename T, FMT_ENABLE_IF(formattable<T>::value)>
1528 FMT_MAP_API auto do_map(T& val) -> T& {
1529 return val;
1531 template <typename T, FMT_ENABLE_IF(!formattable<T>::value)>
1532 FMT_MAP_API auto do_map(T&) -> unformattable {
1533 return {};
1536 // is_fundamental is used to allow formatters for extended FP types.
1537 template <typename T, typename U = remove_const_t<T>,
1538 FMT_ENABLE_IF(
1539 (std::is_class<U>::value || std::is_enum<U>::value ||
1540 std::is_union<U>::value || std::is_fundamental<U>::value) &&
1541 !has_to_string_view<U>::value && !is_char<U>::value &&
1542 !is_named_arg<U>::value && !std::is_integral<U>::value &&
1543 !std::is_arithmetic<format_as_t<U>>::value)>
1544 FMT_MAP_API auto map(T& val) -> decltype(FMT_DECLTYPE_THIS do_map(val)) {
1545 return do_map(val);
1548 template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
1549 FMT_MAP_API auto map(const T& named_arg)
1550 -> decltype(FMT_DECLTYPE_THIS map(named_arg.value)) {
1551 return map(named_arg.value);
1554 auto map(...) -> unformattable { return {}; }
1557 // A type constant after applying arg_mapper<Context>.
1558 template <typename T, typename Context>
1559 using mapped_type_constant =
1560 type_constant<decltype(arg_mapper<Context>().map(std::declval<const T&>())),
1561 typename Context::char_type>;
1563 enum { packed_arg_bits = 4 };
1564 // Maximum number of arguments with packed types.
1565 enum { max_packed_args = 62 / packed_arg_bits };
1566 enum : unsigned long long { is_unpacked_bit = 1ULL << 63 };
1567 enum : unsigned long long { has_named_args_bit = 1ULL << 62 };
1569 template <typename It, typename T, typename Enable = void>
1570 struct is_output_iterator : std::false_type {};
1572 template <> struct is_output_iterator<appender, char> : std::true_type {};
1574 template <typename It, typename T>
1575 struct is_output_iterator<
1576 It, T, void_t<decltype(*std::declval<It&>()++ = std::declval<T>())>>
1577 : std::true_type {};
1579 // A type-erased reference to an std::locale to avoid a heavy <locale> include.
1580 class locale_ref {
1581 private:
1582 const void* locale_; // A type-erased pointer to std::locale.
1584 public:
1585 constexpr locale_ref() : locale_(nullptr) {}
1586 template <typename Locale> explicit locale_ref(const Locale& loc);
1588 explicit operator bool() const noexcept { return locale_ != nullptr; }
1590 template <typename Locale> auto get() const -> Locale;
1593 template <typename> constexpr auto encode_types() -> unsigned long long {
1594 return 0;
1597 template <typename Context, typename Arg, typename... Args>
1598 constexpr auto encode_types() -> unsigned long long {
1599 return static_cast<unsigned>(mapped_type_constant<Arg, Context>::value) |
1600 (encode_types<Context, Args...>() << packed_arg_bits);
1603 template <typename Context, typename... T, size_t NUM_ARGS = sizeof...(T)>
1604 constexpr unsigned long long make_descriptor() {
1605 return NUM_ARGS <= max_packed_args ? encode_types<Context, T...>()
1606 : is_unpacked_bit | NUM_ARGS;
1609 // This type is intentionally undefined, only used for errors.
1610 template <typename T, typename Char>
1611 #if FMT_CLANG_VERSION && FMT_CLANG_VERSION <= 1500
1612 // https://github.com/fmtlib/fmt/issues/3796
1613 struct type_is_unformattable_for {
1615 #else
1616 struct type_is_unformattable_for;
1617 #endif
1619 template <bool PACKED, typename Context, typename T, FMT_ENABLE_IF(PACKED)>
1620 FMT_CONSTEXPR auto make_arg(T& val) -> value<Context> {
1621 using arg_type = remove_cvref_t<decltype(arg_mapper<Context>().map(val))>;
1623 // Use enum instead of constexpr because the latter may generate code.
1624 enum {
1625 formattable_char = !std::is_same<arg_type, unformattable_char>::value
1627 static_assert(formattable_char, "Mixing character types is disallowed.");
1629 // Formatting of arbitrary pointers is disallowed. If you want to format a
1630 // pointer cast it to `void*` or `const void*`. In particular, this forbids
1631 // formatting of `[const] volatile char*` printed as bool by iostreams.
1632 enum {
1633 formattable_pointer = !std::is_same<arg_type, unformattable_pointer>::value
1635 static_assert(formattable_pointer,
1636 "Formatting of non-void pointers is disallowed.");
1638 enum { formattable = !std::is_same<arg_type, unformattable>::value };
1639 #if defined(__cpp_if_constexpr)
1640 if constexpr (!formattable)
1641 type_is_unformattable_for<T, typename Context::char_type> _;
1642 #endif
1643 static_assert(
1644 formattable,
1645 "Cannot format an argument. To make type T formattable provide a "
1646 "formatter<T> specialization: https://fmt.dev/latest/api.html#udt");
1647 return {arg_mapper<Context>().map(val)};
1650 template <typename Context, typename T>
1651 FMT_CONSTEXPR auto make_arg(T& val) -> basic_format_arg<Context> {
1652 auto arg = basic_format_arg<Context>();
1653 arg.type_ = mapped_type_constant<T, Context>::value;
1654 arg.value_ = make_arg<true, Context>(val);
1655 return arg;
1658 template <bool PACKED, typename Context, typename T, FMT_ENABLE_IF(!PACKED)>
1659 FMT_CONSTEXPR inline auto make_arg(T& val) -> basic_format_arg<Context> {
1660 return make_arg<Context>(val);
1663 template <typename Context, size_t NUM_ARGS>
1664 using arg_t = conditional_t<NUM_ARGS <= max_packed_args, value<Context>,
1665 basic_format_arg<Context>>;
1667 template <typename Char, typename T, FMT_ENABLE_IF(!is_named_arg<T>::value)>
1668 void init_named_arg(named_arg_info<Char>*, int& arg_index, int&, const T&) {
1669 ++arg_index;
1671 template <typename Char, typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
1672 void init_named_arg(named_arg_info<Char>* named_args, int& arg_index,
1673 int& named_arg_index, const T& arg) {
1674 named_args[named_arg_index++] = {arg.name, arg_index++};
1677 // An array of references to arguments. It can be implicitly converted to
1678 // `fmt::basic_format_args` for passing into type-erased formatting functions
1679 // such as `fmt::vformat`.
1680 template <typename Context, size_t NUM_ARGS, size_t NUM_NAMED_ARGS,
1681 unsigned long long DESC>
1682 struct format_arg_store {
1683 // args_[0].named_args points to named_args to avoid bloating format_args.
1684 // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
1685 static constexpr size_t ARGS_ARR_SIZE = 1 + (NUM_ARGS != 0 ? NUM_ARGS : +1);
1687 arg_t<Context, NUM_ARGS> args[ARGS_ARR_SIZE];
1688 named_arg_info<typename Context::char_type> named_args[NUM_NAMED_ARGS];
1690 template <typename... T>
1691 FMT_MAP_API format_arg_store(T&... values)
1692 : args{{named_args, NUM_NAMED_ARGS},
1693 make_arg<NUM_ARGS <= max_packed_args, Context>(values)...} {
1694 using dummy = int[];
1695 int arg_index = 0, named_arg_index = 0;
1696 (void)dummy{
1698 (init_named_arg(named_args, arg_index, named_arg_index, values), 0)...};
1701 format_arg_store(format_arg_store&& rhs) {
1702 args[0] = {named_args, NUM_NAMED_ARGS};
1703 for (size_t i = 1; i < ARGS_ARR_SIZE; ++i) args[i] = rhs.args[i];
1704 for (size_t i = 0; i < NUM_NAMED_ARGS; ++i)
1705 named_args[i] = rhs.named_args[i];
1708 format_arg_store(const format_arg_store& rhs) = delete;
1709 format_arg_store& operator=(const format_arg_store& rhs) = delete;
1710 format_arg_store& operator=(format_arg_store&& rhs) = delete;
1713 // A specialization of format_arg_store without named arguments.
1714 // It is a plain struct to reduce binary size in debug mode.
1715 template <typename Context, size_t NUM_ARGS, unsigned long long DESC>
1716 struct format_arg_store<Context, NUM_ARGS, 0, DESC> {
1717 // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
1718 arg_t<Context, NUM_ARGS> args[NUM_ARGS != 0 ? NUM_ARGS : +1];
1721 } // namespace detail
1722 FMT_BEGIN_EXPORT
1724 // A formatting argument. Context is a template parameter for the compiled API
1725 // where output can be unbuffered.
1726 template <typename Context> class basic_format_arg {
1727 private:
1728 detail::value<Context> value_;
1729 detail::type type_;
1731 template <typename ContextType, typename T>
1732 friend FMT_CONSTEXPR auto detail::make_arg(T& value)
1733 -> basic_format_arg<ContextType>;
1735 friend class basic_format_args<Context>;
1736 friend class dynamic_format_arg_store<Context>;
1738 using char_type = typename Context::char_type;
1740 template <typename, size_t, size_t, unsigned long long>
1741 friend struct detail::format_arg_store;
1743 basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)
1744 : value_(args, size) {}
1746 public:
1747 class handle {
1748 public:
1749 explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}
1751 void format(typename Context::parse_context_type& parse_ctx,
1752 Context& ctx) const {
1753 custom_.format(custom_.value, parse_ctx, ctx);
1756 private:
1757 detail::custom_value<Context> custom_;
1760 constexpr basic_format_arg() : type_(detail::type::none_type) {}
1762 constexpr explicit operator bool() const noexcept {
1763 return type_ != detail::type::none_type;
1766 auto type() const -> detail::type { return type_; }
1768 auto is_integral() const -> bool { return detail::is_integral_type(type_); }
1769 auto is_arithmetic() const -> bool {
1770 return detail::is_arithmetic_type(type_);
1774 * Visits an argument dispatching to the appropriate visit method based on
1775 * the argument type. For example, if the argument type is `double` then
1776 * `vis(value)` will be called with the value of type `double`.
1778 template <typename Visitor>
1779 FMT_CONSTEXPR FMT_INLINE auto visit(Visitor&& vis) const -> decltype(vis(0)) {
1780 switch (type_) {
1781 case detail::type::none_type:
1782 break;
1783 case detail::type::int_type:
1784 return vis(value_.int_value);
1785 case detail::type::uint_type:
1786 return vis(value_.uint_value);
1787 case detail::type::long_long_type:
1788 return vis(value_.long_long_value);
1789 case detail::type::ulong_long_type:
1790 return vis(value_.ulong_long_value);
1791 case detail::type::int128_type:
1792 return vis(detail::convert_for_visit(value_.int128_value));
1793 case detail::type::uint128_type:
1794 return vis(detail::convert_for_visit(value_.uint128_value));
1795 case detail::type::bool_type:
1796 return vis(value_.bool_value);
1797 case detail::type::char_type:
1798 return vis(value_.char_value);
1799 case detail::type::float_type:
1800 return vis(value_.float_value);
1801 case detail::type::double_type:
1802 return vis(value_.double_value);
1803 case detail::type::long_double_type:
1804 return vis(value_.long_double_value);
1805 case detail::type::cstring_type:
1806 return vis(value_.string.data);
1807 case detail::type::string_type:
1808 using sv = basic_string_view<typename Context::char_type>;
1809 return vis(sv(value_.string.data, value_.string.size));
1810 case detail::type::pointer_type:
1811 return vis(value_.pointer);
1812 case detail::type::custom_type:
1813 return vis(typename basic_format_arg<Context>::handle(value_.custom));
1815 return vis(monostate());
1818 auto format_custom(const char_type* parse_begin,
1819 typename Context::parse_context_type& parse_ctx,
1820 Context& ctx) -> bool {
1821 if (type_ != detail::type::custom_type) return false;
1822 parse_ctx.advance_to(parse_begin);
1823 value_.custom.format(value_.custom.value, parse_ctx, ctx);
1824 return true;
1828 template <typename Visitor, typename Context>
1829 FMT_DEPRECATED FMT_CONSTEXPR auto visit_format_arg(
1830 Visitor&& vis, const basic_format_arg<Context>& arg) -> decltype(vis(0)) {
1831 return arg.visit(static_cast<Visitor&&>(vis));
1835 * A view of a collection of formatting arguments. To avoid lifetime issues it
1836 * should only be used as a parameter type in type-erased functions such as
1837 * `vformat`:
1839 * void vlog(fmt::string_view fmt, fmt::format_args args); // OK
1840 * fmt::format_args args = fmt::make_format_args(); // Dangling reference
1842 template <typename Context> class basic_format_args {
1843 public:
1844 using size_type = int;
1845 using format_arg = basic_format_arg<Context>;
1847 private:
1848 // A descriptor that contains information about formatting arguments.
1849 // If the number of arguments is less or equal to max_packed_args then
1850 // argument types are passed in the descriptor. This reduces binary code size
1851 // per formatting function call.
1852 unsigned long long desc_;
1853 union {
1854 // If is_packed() returns true then argument values are stored in values_;
1855 // otherwise they are stored in args_. This is done to improve cache
1856 // locality and reduce compiled code size since storing larger objects
1857 // may require more code (at least on x86-64) even if the same amount of
1858 // data is actually copied to stack. It saves ~10% on the bloat test.
1859 const detail::value<Context>* values_;
1860 const format_arg* args_;
1863 constexpr auto is_packed() const -> bool {
1864 return (desc_ & detail::is_unpacked_bit) == 0;
1866 constexpr auto has_named_args() const -> bool {
1867 return (desc_ & detail::has_named_args_bit) != 0;
1870 FMT_CONSTEXPR auto type(int index) const -> detail::type {
1871 int shift = index * detail::packed_arg_bits;
1872 unsigned int mask = (1 << detail::packed_arg_bits) - 1;
1873 return static_cast<detail::type>((desc_ >> shift) & mask);
1876 public:
1877 constexpr basic_format_args() : desc_(0), args_(nullptr) {}
1879 /// Constructs a `basic_format_args` object from `format_arg_store`.
1880 template <size_t NUM_ARGS, size_t NUM_NAMED_ARGS, unsigned long long DESC,
1881 FMT_ENABLE_IF(NUM_ARGS <= detail::max_packed_args)>
1882 constexpr FMT_ALWAYS_INLINE basic_format_args(
1883 const detail::format_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>&
1884 store)
1885 : desc_(DESC), values_(store.args + (NUM_NAMED_ARGS != 0 ? 1 : 0)) {}
1887 template <size_t NUM_ARGS, size_t NUM_NAMED_ARGS, unsigned long long DESC,
1888 FMT_ENABLE_IF(NUM_ARGS > detail::max_packed_args)>
1889 constexpr basic_format_args(
1890 const detail::format_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>&
1891 store)
1892 : desc_(DESC), args_(store.args + (NUM_NAMED_ARGS != 0 ? 1 : 0)) {}
1894 /// Constructs a `basic_format_args` object from `dynamic_format_arg_store`.
1895 constexpr basic_format_args(const dynamic_format_arg_store<Context>& store)
1896 : desc_(store.get_types()), args_(store.data()) {}
1898 /// Constructs a `basic_format_args` object from a dynamic list of arguments.
1899 constexpr basic_format_args(const format_arg* args, int count)
1900 : desc_(detail::is_unpacked_bit | detail::to_unsigned(count)),
1901 args_(args) {}
1903 /// Returns the argument with the specified id.
1904 FMT_CONSTEXPR auto get(int id) const -> format_arg {
1905 format_arg arg;
1906 if (!is_packed()) {
1907 if (id < max_size()) arg = args_[id];
1908 return arg;
1910 if (static_cast<unsigned>(id) >= detail::max_packed_args) return arg;
1911 arg.type_ = type(id);
1912 if (arg.type_ == detail::type::none_type) return arg;
1913 arg.value_ = values_[id];
1914 return arg;
1917 template <typename Char>
1918 auto get(basic_string_view<Char> name) const -> format_arg {
1919 int id = get_id(name);
1920 return id >= 0 ? get(id) : format_arg();
1923 template <typename Char>
1924 FMT_CONSTEXPR auto get_id(basic_string_view<Char> name) const -> int {
1925 if (!has_named_args()) return -1;
1926 const auto& named_args =
1927 (is_packed() ? values_[-1] : args_[-1].value_).named_args;
1928 for (size_t i = 0; i < named_args.size; ++i) {
1929 if (named_args.data[i].name == name) return named_args.data[i].id;
1931 return -1;
1934 auto max_size() const -> int {
1935 unsigned long long max_packed = detail::max_packed_args;
1936 return static_cast<int>(is_packed() ? max_packed
1937 : desc_ & ~detail::is_unpacked_bit);
1941 // A formatting context.
1942 class context {
1943 private:
1944 appender out_;
1945 basic_format_args<context> args_;
1946 detail::locale_ref loc_;
1948 public:
1949 /// The character type for the output.
1950 using char_type = char;
1952 using iterator = appender;
1953 using format_arg = basic_format_arg<context>;
1954 using parse_context_type = basic_format_parse_context<char>;
1955 template <typename T> using formatter_type = formatter<T, char>;
1957 /// Constructs a `basic_format_context` object. References to the arguments
1958 /// are stored in the object so make sure they have appropriate lifetimes.
1959 FMT_CONSTEXPR context(iterator out, basic_format_args<context> ctx_args,
1960 detail::locale_ref loc = {})
1961 : out_(out), args_(ctx_args), loc_(loc) {}
1962 context(context&&) = default;
1963 context(const context&) = delete;
1964 void operator=(const context&) = delete;
1966 FMT_CONSTEXPR auto arg(int id) const -> format_arg { return args_.get(id); }
1967 auto arg(string_view name) -> format_arg { return args_.get(name); }
1968 FMT_CONSTEXPR auto arg_id(string_view name) -> int {
1969 return args_.get_id(name);
1971 auto args() const -> const basic_format_args<context>& { return args_; }
1973 // Returns an iterator to the beginning of the output range.
1974 FMT_CONSTEXPR auto out() -> iterator { return out_; }
1976 // Advances the begin iterator to `it`.
1977 void advance_to(iterator) {}
1979 FMT_CONSTEXPR auto locale() -> detail::locale_ref { return loc_; }
1982 template <typename OutputIt, typename Char> class generic_context;
1984 // Longer aliases for C++20 compatibility.
1985 template <typename OutputIt, typename Char>
1986 using basic_format_context =
1987 conditional_t<std::is_same<OutputIt, appender>::value, context,
1988 generic_context<OutputIt, Char>>;
1989 using format_context = context;
1991 template <typename Char>
1992 using buffered_context = basic_format_context<basic_appender<Char>, Char>;
1994 template <typename T, typename Char = char>
1995 using is_formattable = bool_constant<!std::is_base_of<
1996 detail::unformattable, decltype(detail::arg_mapper<buffered_context<Char>>()
1997 .map(std::declval<T&>()))>::value>;
1999 #if FMT_USE_CONCEPTS
2000 template <typename T, typename Char = char>
2001 concept formattable = is_formattable<remove_reference_t<T>, Char>::value;
2002 #endif
2005 * Constructs an object that stores references to arguments and can be
2006 * implicitly converted to `format_args`. `Context` can be omitted in which case
2007 * it defaults to `format_context`. See `arg` for lifetime considerations.
2009 // Take arguments by lvalue references to avoid some lifetime issues, e.g.
2010 // auto args = make_format_args(std::string());
2011 template <typename Context = format_context, typename... T,
2012 size_t NUM_ARGS = sizeof...(T),
2013 size_t NUM_NAMED_ARGS = detail::count_named_args<T...>(),
2014 unsigned long long DESC = detail::make_descriptor<Context, T...>(),
2015 FMT_ENABLE_IF(NUM_NAMED_ARGS == 0)>
2016 constexpr FMT_ALWAYS_INLINE auto make_format_args(T&... args)
2017 -> detail::format_arg_store<Context, NUM_ARGS, 0, DESC> {
2018 return {{detail::make_arg<NUM_ARGS <= detail::max_packed_args, Context>(
2019 args)...}};
2022 #ifndef FMT_DOC
2023 template <typename Context = format_context, typename... T,
2024 size_t NUM_NAMED_ARGS = detail::count_named_args<T...>(),
2025 unsigned long long DESC =
2026 detail::make_descriptor<Context, T...>() |
2027 static_cast<unsigned long long>(detail::has_named_args_bit),
2028 FMT_ENABLE_IF(NUM_NAMED_ARGS != 0)>
2029 constexpr auto make_format_args(T&... args)
2030 -> detail::format_arg_store<Context, sizeof...(T), NUM_NAMED_ARGS, DESC> {
2031 return {args...};
2033 #endif
2036 * Returns a named argument to be used in a formatting function.
2037 * It should only be used in a call to a formatting function or
2038 * `dynamic_format_arg_store::push_back`.
2040 * **Example**:
2042 * fmt::print("The answer is {answer}.", fmt::arg("answer", 42));
2044 template <typename Char, typename T>
2045 inline auto arg(const Char* name, const T& arg) -> detail::named_arg<Char, T> {
2046 static_assert(!detail::is_named_arg<T>(), "nested named arguments");
2047 return {name, arg};
2049 FMT_END_EXPORT
2051 /// An alias for `basic_format_args<format_context>`.
2052 // A separate type would result in shorter symbols but break ABI compatibility
2053 // between clang and gcc on ARM (#1919).
2054 FMT_EXPORT using format_args = basic_format_args<format_context>;
2056 // We cannot use enum classes as bit fields because of a gcc bug, so we put them
2057 // in namespaces instead (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414).
2058 // Additionally, if an underlying type is specified, older gcc incorrectly warns
2059 // that the type is too small. Both bugs are fixed in gcc 9.3.
2060 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 903
2061 # define FMT_ENUM_UNDERLYING_TYPE(type)
2062 #else
2063 # define FMT_ENUM_UNDERLYING_TYPE(type) : type
2064 #endif
2065 namespace align {
2066 enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, left, right, center,
2067 numeric};
2069 using align_t = align::type;
2070 namespace sign {
2071 enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, minus, plus, space};
2073 using sign_t = sign::type;
2075 namespace detail {
2077 template <typename Char>
2078 using unsigned_char = typename conditional_t<std::is_integral<Char>::value,
2079 std::make_unsigned<Char>,
2080 type_identity<unsigned>>::type;
2082 // Character (code unit) type is erased to prevent template bloat.
2083 struct fill_t {
2084 private:
2085 enum { max_size = 4 };
2086 char data_[max_size] = {' '};
2087 unsigned char size_ = 1;
2089 public:
2090 template <typename Char>
2091 FMT_CONSTEXPR void operator=(basic_string_view<Char> s) {
2092 auto size = s.size();
2093 size_ = static_cast<unsigned char>(size);
2094 if (size == 1) {
2095 unsigned uchar = static_cast<unsigned_char<Char>>(s[0]);
2096 data_[0] = static_cast<char>(uchar);
2097 data_[1] = static_cast<char>(uchar >> 8);
2098 return;
2100 FMT_ASSERT(size <= max_size, "invalid fill");
2101 for (size_t i = 0; i < size; ++i) data_[i] = static_cast<char>(s[i]);
2104 FMT_CONSTEXPR void operator=(char c) {
2105 data_[0] = c;
2106 size_ = 1;
2109 constexpr auto size() const -> size_t { return size_; }
2111 template <typename Char> constexpr auto get() const -> Char {
2112 using uchar = unsigned char;
2113 return static_cast<Char>(static_cast<uchar>(data_[0]) |
2114 (static_cast<uchar>(data_[1]) << 8));
2117 template <typename Char, FMT_ENABLE_IF(std::is_same<Char, char>::value)>
2118 constexpr auto data() const -> const Char* {
2119 return data_;
2121 template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
2122 constexpr auto data() const -> const Char* {
2123 return nullptr;
2126 } // namespace detail
2128 enum class presentation_type : unsigned char {
2129 // Common specifiers:
2130 none = 0,
2131 debug = 1, // '?'
2132 string = 2, // 's' (string, bool)
2134 // Integral, bool and character specifiers:
2135 dec = 3, // 'd'
2136 hex, // 'x' or 'X'
2137 oct, // 'o'
2138 bin, // 'b' or 'B'
2139 chr, // 'c'
2141 // String and pointer specifiers:
2142 pointer = 3, // 'p'
2144 // Floating-point specifiers:
2145 exp = 1, // 'e' or 'E' (1 since there is no FP debug presentation)
2146 fixed, // 'f' or 'F'
2147 general, // 'g' or 'G'
2148 hexfloat // 'a' or 'A'
2151 // Format specifiers for built-in and string types.
2152 struct format_specs {
2153 int width;
2154 int precision;
2155 presentation_type type;
2156 align_t align : 4;
2157 sign_t sign : 3;
2158 bool upper : 1; // An uppercase version e.g. 'X' for 'x'.
2159 bool alt : 1; // Alternate form ('#').
2160 bool localized : 1;
2161 detail::fill_t fill;
2163 constexpr format_specs()
2164 : width(0),
2165 precision(-1),
2166 type(presentation_type::none),
2167 align(align::none),
2168 sign(sign::none),
2169 upper(false),
2170 alt(false),
2171 localized(false) {}
2174 namespace detail {
2176 enum class arg_id_kind { none, index, name };
2178 // An argument reference.
2179 template <typename Char> struct arg_ref {
2180 FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {}
2182 FMT_CONSTEXPR explicit arg_ref(int index)
2183 : kind(arg_id_kind::index), val(index) {}
2184 FMT_CONSTEXPR explicit arg_ref(basic_string_view<Char> name)
2185 : kind(arg_id_kind::name), val(name) {}
2187 FMT_CONSTEXPR auto operator=(int idx) -> arg_ref& {
2188 kind = arg_id_kind::index;
2189 val.index = idx;
2190 return *this;
2193 arg_id_kind kind;
2194 union value {
2195 FMT_CONSTEXPR value(int idx = 0) : index(idx) {}
2196 FMT_CONSTEXPR value(basic_string_view<Char> n) : name(n) {}
2198 int index;
2199 basic_string_view<Char> name;
2200 } val;
2203 // Format specifiers with width and precision resolved at formatting rather
2204 // than parsing time to allow reusing the same parsed specifiers with
2205 // different sets of arguments (precompilation of format strings).
2206 template <typename Char = char> struct dynamic_format_specs : format_specs {
2207 arg_ref<Char> width_ref;
2208 arg_ref<Char> precision_ref;
2211 // Converts a character to ASCII. Returns '\0' on conversion failure.
2212 template <typename Char, FMT_ENABLE_IF(std::is_integral<Char>::value)>
2213 constexpr auto to_ascii(Char c) -> char {
2214 return c <= 0xff ? static_cast<char>(c) : '\0';
2217 // Returns the number of code units in a code point or 1 on error.
2218 template <typename Char>
2219 FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int {
2220 if (const_check(sizeof(Char) != 1)) return 1;
2221 auto c = static_cast<unsigned char>(*begin);
2222 return static_cast<int>((0x3a55000000000000ull >> (2 * (c >> 3))) & 0x3) + 1;
2225 // Return the result via the out param to workaround gcc bug 77539.
2226 template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>
2227 FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool {
2228 for (out = first; out != last; ++out) {
2229 if (*out == value) return true;
2231 return false;
2234 template <>
2235 inline auto find<false, char>(const char* first, const char* last, char value,
2236 const char*& out) -> bool {
2237 out =
2238 static_cast<const char*>(memchr(first, value, to_unsigned(last - first)));
2239 return out != nullptr;
2242 // Parses the range [begin, end) as an unsigned integer. This function assumes
2243 // that the range is non-empty and the first character is a digit.
2244 template <typename Char>
2245 FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end,
2246 int error_value) noexcept -> int {
2247 FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', "");
2248 unsigned value = 0, prev = 0;
2249 auto p = begin;
2250 do {
2251 prev = value;
2252 value = value * 10 + unsigned(*p - '0');
2253 ++p;
2254 } while (p != end && '0' <= *p && *p <= '9');
2255 auto num_digits = p - begin;
2256 begin = p;
2257 int digits10 = static_cast<int>(sizeof(int) * CHAR_BIT * 3 / 10);
2258 if (num_digits <= digits10) return static_cast<int>(value);
2259 // Check for overflow.
2260 unsigned max = INT_MAX;
2261 return num_digits == digits10 + 1 &&
2262 prev * 10ull + unsigned(p[-1] - '0') <= max
2263 ? static_cast<int>(value)
2264 : error_value;
2267 FMT_CONSTEXPR inline auto parse_align(char c) -> align_t {
2268 switch (c) {
2269 case '<':
2270 return align::left;
2271 case '>':
2272 return align::right;
2273 case '^':
2274 return align::center;
2276 return align::none;
2279 template <typename Char> constexpr auto is_name_start(Char c) -> bool {
2280 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_';
2283 template <typename Char, typename Handler>
2284 FMT_CONSTEXPR auto do_parse_arg_id(const Char* begin, const Char* end,
2285 Handler&& handler) -> const Char* {
2286 Char c = *begin;
2287 if (c >= '0' && c <= '9') {
2288 int index = 0;
2289 if (c != '0')
2290 index = parse_nonnegative_int(begin, end, INT_MAX);
2291 else
2292 ++begin;
2293 if (begin == end || (*begin != '}' && *begin != ':'))
2294 report_error("invalid format string");
2295 else
2296 handler.on_index(index);
2297 return begin;
2299 if (!is_name_start(c)) {
2300 report_error("invalid format string");
2301 return begin;
2303 auto it = begin;
2304 do {
2305 ++it;
2306 } while (it != end && (is_name_start(*it) || ('0' <= *it && *it <= '9')));
2307 handler.on_name({begin, to_unsigned(it - begin)});
2308 return it;
2311 template <typename Char, typename Handler>
2312 FMT_CONSTEXPR auto parse_arg_id(const Char* begin, const Char* end,
2313 Handler&& handler) -> const Char* {
2314 FMT_ASSERT(begin != end, "");
2315 Char c = *begin;
2316 if (c != '}' && c != ':') return do_parse_arg_id(begin, end, handler);
2317 handler.on_auto();
2318 return begin;
2321 template <typename Char> struct dynamic_spec_id_handler {
2322 basic_format_parse_context<Char>& ctx;
2323 arg_ref<Char>& ref;
2325 FMT_CONSTEXPR void on_auto() {
2326 int id = ctx.next_arg_id();
2327 ref = arg_ref<Char>(id);
2328 ctx.check_dynamic_spec(id);
2330 FMT_CONSTEXPR void on_index(int id) {
2331 ref = arg_ref<Char>(id);
2332 ctx.check_arg_id(id);
2333 ctx.check_dynamic_spec(id);
2335 FMT_CONSTEXPR void on_name(basic_string_view<Char> id) {
2336 ref = arg_ref<Char>(id);
2337 ctx.check_arg_id(id);
2341 // Parses [integer | "{" [arg_id] "}"].
2342 template <typename Char>
2343 FMT_CONSTEXPR auto parse_dynamic_spec(const Char* begin, const Char* end,
2344 int& value, arg_ref<Char>& ref,
2345 basic_format_parse_context<Char>& ctx)
2346 -> const Char* {
2347 FMT_ASSERT(begin != end, "");
2348 if ('0' <= *begin && *begin <= '9') {
2349 int val = parse_nonnegative_int(begin, end, -1);
2350 if (val != -1)
2351 value = val;
2352 else
2353 report_error("number is too big");
2354 } else if (*begin == '{') {
2355 ++begin;
2356 auto handler = dynamic_spec_id_handler<Char>{ctx, ref};
2357 if (begin != end) begin = parse_arg_id(begin, end, handler);
2358 if (begin != end && *begin == '}') return ++begin;
2359 report_error("invalid format string");
2361 return begin;
2364 template <typename Char>
2365 FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end,
2366 int& value, arg_ref<Char>& ref,
2367 basic_format_parse_context<Char>& ctx)
2368 -> const Char* {
2369 ++begin;
2370 if (begin == end || *begin == '}') {
2371 report_error("invalid precision");
2372 return begin;
2374 return parse_dynamic_spec(begin, end, value, ref, ctx);
2377 enum class state { start, align, sign, hash, zero, width, precision, locale };
2379 // Parses standard format specifiers.
2380 template <typename Char>
2381 FMT_CONSTEXPR auto parse_format_specs(const Char* begin, const Char* end,
2382 dynamic_format_specs<Char>& specs,
2383 basic_format_parse_context<Char>& ctx,
2384 type arg_type) -> const Char* {
2385 auto c = '\0';
2386 if (end - begin > 1) {
2387 auto next = to_ascii(begin[1]);
2388 c = parse_align(next) == align::none ? to_ascii(*begin) : '\0';
2389 } else {
2390 if (begin == end) return begin;
2391 c = to_ascii(*begin);
2394 struct {
2395 state current_state = state::start;
2396 FMT_CONSTEXPR void operator()(state s, bool valid = true) {
2397 if (current_state >= s || !valid)
2398 report_error("invalid format specifier");
2399 current_state = s;
2401 } enter_state;
2403 using pres = presentation_type;
2404 constexpr auto integral_set = sint_set | uint_set | bool_set | char_set;
2405 struct {
2406 const Char*& begin;
2407 dynamic_format_specs<Char>& specs;
2408 type arg_type;
2410 FMT_CONSTEXPR auto operator()(pres pres_type, int set) -> const Char* {
2411 if (!in(arg_type, set)) {
2412 if (arg_type == type::none_type) return begin;
2413 report_error("invalid format specifier");
2415 specs.type = pres_type;
2416 return begin + 1;
2418 } parse_presentation_type{begin, specs, arg_type};
2420 for (;;) {
2421 switch (c) {
2422 case '<':
2423 case '>':
2424 case '^':
2425 enter_state(state::align);
2426 specs.align = parse_align(c);
2427 ++begin;
2428 break;
2429 case '+':
2430 case '-':
2431 case ' ':
2432 if (arg_type == type::none_type) return begin;
2433 enter_state(state::sign, in(arg_type, sint_set | float_set));
2434 switch (c) {
2435 case '+':
2436 specs.sign = sign::plus;
2437 break;
2438 case '-':
2439 specs.sign = sign::minus;
2440 break;
2441 case ' ':
2442 specs.sign = sign::space;
2443 break;
2445 ++begin;
2446 break;
2447 case '#':
2448 if (arg_type == type::none_type) return begin;
2449 enter_state(state::hash, is_arithmetic_type(arg_type));
2450 specs.alt = true;
2451 ++begin;
2452 break;
2453 case '0':
2454 enter_state(state::zero);
2455 if (!is_arithmetic_type(arg_type)) {
2456 if (arg_type == type::none_type) return begin;
2457 report_error("format specifier requires numeric argument");
2459 if (specs.align == align::none) {
2460 // Ignore 0 if align is specified for compatibility with std::format.
2461 specs.align = align::numeric;
2462 specs.fill = '0';
2464 ++begin;
2465 break;
2466 case '1':
2467 case '2':
2468 case '3':
2469 case '4':
2470 case '5':
2471 case '6':
2472 case '7':
2473 case '8':
2474 case '9':
2475 case '{':
2476 enter_state(state::width);
2477 begin = parse_dynamic_spec(begin, end, specs.width, specs.width_ref, ctx);
2478 break;
2479 case '.':
2480 if (arg_type == type::none_type) return begin;
2481 enter_state(state::precision,
2482 in(arg_type, float_set | string_set | cstring_set));
2483 begin = parse_precision(begin, end, specs.precision, specs.precision_ref,
2484 ctx);
2485 break;
2486 case 'L':
2487 if (arg_type == type::none_type) return begin;
2488 enter_state(state::locale, is_arithmetic_type(arg_type));
2489 specs.localized = true;
2490 ++begin;
2491 break;
2492 case 'd':
2493 return parse_presentation_type(pres::dec, integral_set);
2494 case 'X':
2495 specs.upper = true;
2496 FMT_FALLTHROUGH;
2497 case 'x':
2498 return parse_presentation_type(pres::hex, integral_set);
2499 case 'o':
2500 return parse_presentation_type(pres::oct, integral_set);
2501 case 'B':
2502 specs.upper = true;
2503 FMT_FALLTHROUGH;
2504 case 'b':
2505 return parse_presentation_type(pres::bin, integral_set);
2506 case 'E':
2507 specs.upper = true;
2508 FMT_FALLTHROUGH;
2509 case 'e':
2510 return parse_presentation_type(pres::exp, float_set);
2511 case 'F':
2512 specs.upper = true;
2513 FMT_FALLTHROUGH;
2514 case 'f':
2515 return parse_presentation_type(pres::fixed, float_set);
2516 case 'G':
2517 specs.upper = true;
2518 FMT_FALLTHROUGH;
2519 case 'g':
2520 return parse_presentation_type(pres::general, float_set);
2521 case 'A':
2522 specs.upper = true;
2523 FMT_FALLTHROUGH;
2524 case 'a':
2525 return parse_presentation_type(pres::hexfloat, float_set);
2526 case 'c':
2527 if (arg_type == type::bool_type) report_error("invalid format specifier");
2528 return parse_presentation_type(pres::chr, integral_set);
2529 case 's':
2530 return parse_presentation_type(pres::string,
2531 bool_set | string_set | cstring_set);
2532 case 'p':
2533 return parse_presentation_type(pres::pointer, pointer_set | cstring_set);
2534 case '?':
2535 return parse_presentation_type(pres::debug,
2536 char_set | string_set | cstring_set);
2537 case '}':
2538 return begin;
2539 default: {
2540 if (*begin == '}') return begin;
2541 // Parse fill and alignment.
2542 auto fill_end = begin + code_point_length(begin);
2543 if (end - fill_end <= 0) {
2544 report_error("invalid format specifier");
2545 return begin;
2547 if (*begin == '{') {
2548 report_error("invalid fill character '{'");
2549 return begin;
2551 auto align = parse_align(to_ascii(*fill_end));
2552 enter_state(state::align, align != align::none);
2553 specs.fill =
2554 basic_string_view<Char>(begin, to_unsigned(fill_end - begin));
2555 specs.align = align;
2556 begin = fill_end + 1;
2559 if (begin == end) return begin;
2560 c = to_ascii(*begin);
2564 template <typename Char, typename Handler>
2565 FMT_CONSTEXPR auto parse_replacement_field(const Char* begin, const Char* end,
2566 Handler&& handler) -> const Char* {
2567 struct id_adapter {
2568 Handler& handler;
2569 int arg_id;
2571 FMT_CONSTEXPR void on_auto() { arg_id = handler.on_arg_id(); }
2572 FMT_CONSTEXPR void on_index(int id) { arg_id = handler.on_arg_id(id); }
2573 FMT_CONSTEXPR void on_name(basic_string_view<Char> id) {
2574 arg_id = handler.on_arg_id(id);
2578 ++begin;
2579 if (begin == end) return handler.on_error("invalid format string"), end;
2580 if (*begin == '}') {
2581 handler.on_replacement_field(handler.on_arg_id(), begin);
2582 } else if (*begin == '{') {
2583 handler.on_text(begin, begin + 1);
2584 } else {
2585 auto adapter = id_adapter{handler, 0};
2586 begin = parse_arg_id(begin, end, adapter);
2587 Char c = begin != end ? *begin : Char();
2588 if (c == '}') {
2589 handler.on_replacement_field(adapter.arg_id, begin);
2590 } else if (c == ':') {
2591 begin = handler.on_format_specs(adapter.arg_id, begin + 1, end);
2592 if (begin == end || *begin != '}')
2593 return handler.on_error("unknown format specifier"), end;
2594 } else {
2595 return handler.on_error("missing '}' in format string"), end;
2598 return begin + 1;
2601 template <bool IS_CONSTEXPR, typename Char, typename Handler>
2602 FMT_CONSTEXPR void parse_format_string(basic_string_view<Char> format_str,
2603 Handler&& handler) {
2604 auto begin = format_str.data();
2605 auto end = begin + format_str.size();
2606 if (end - begin < 32) {
2607 // Use a simple loop instead of memchr for small strings.
2608 const Char* p = begin;
2609 while (p != end) {
2610 auto c = *p++;
2611 if (c == '{') {
2612 handler.on_text(begin, p - 1);
2613 begin = p = parse_replacement_field(p - 1, end, handler);
2614 } else if (c == '}') {
2615 if (p == end || *p != '}')
2616 return handler.on_error("unmatched '}' in format string");
2617 handler.on_text(begin, p);
2618 begin = ++p;
2621 handler.on_text(begin, end);
2622 return;
2624 struct writer {
2625 FMT_CONSTEXPR void operator()(const Char* from, const Char* to) {
2626 if (from == to) return;
2627 for (;;) {
2628 const Char* p = nullptr;
2629 if (!find<IS_CONSTEXPR>(from, to, Char('}'), p))
2630 return handler_.on_text(from, to);
2631 ++p;
2632 if (p == to || *p != '}')
2633 return handler_.on_error("unmatched '}' in format string");
2634 handler_.on_text(from, p);
2635 from = p + 1;
2638 Handler& handler_;
2639 } write = {handler};
2640 while (begin != end) {
2641 // Doing two passes with memchr (one for '{' and another for '}') is up to
2642 // 2.5x faster than the naive one-pass implementation on big format strings.
2643 const Char* p = begin;
2644 if (*begin != '{' && !find<IS_CONSTEXPR>(begin + 1, end, Char('{'), p))
2645 return write(begin, end);
2646 write(begin, p);
2647 begin = parse_replacement_field(p, end, handler);
2651 template <typename T, bool = is_named_arg<T>::value> struct strip_named_arg {
2652 using type = T;
2654 template <typename T> struct strip_named_arg<T, true> {
2655 using type = remove_cvref_t<decltype(T::value)>;
2658 template <typename T, typename ParseContext>
2659 FMT_VISIBILITY("hidden") // Suppress an ld warning on macOS (#3769).
2660 FMT_CONSTEXPR auto parse_format_specs(ParseContext& ctx)
2661 -> decltype(ctx.begin()) {
2662 using char_type = typename ParseContext::char_type;
2663 using context = buffered_context<char_type>;
2664 using mapped_type = conditional_t<
2665 mapped_type_constant<T, context>::value != type::custom_type,
2666 decltype(arg_mapper<context>().map(std::declval<const T&>())),
2667 typename strip_named_arg<T>::type>;
2668 #if defined(__cpp_if_constexpr)
2669 if constexpr (std::is_default_constructible<
2670 formatter<mapped_type, char_type>>::value) {
2671 return formatter<mapped_type, char_type>().parse(ctx);
2672 } else {
2673 type_is_unformattable_for<T, char_type> _;
2674 return ctx.begin();
2676 #else
2677 return formatter<mapped_type, char_type>().parse(ctx);
2678 #endif
2681 // Checks char specs and returns true iff the presentation type is char-like.
2682 FMT_CONSTEXPR inline auto check_char_specs(const format_specs& specs) -> bool {
2683 if (specs.type != presentation_type::none &&
2684 specs.type != presentation_type::chr &&
2685 specs.type != presentation_type::debug) {
2686 return false;
2688 if (specs.align == align::numeric || specs.sign != sign::none || specs.alt)
2689 report_error("invalid format specifier for char");
2690 return true;
2693 #if FMT_USE_NONTYPE_TEMPLATE_ARGS
2694 template <int N, typename T, typename... Args, typename Char>
2695 constexpr auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
2696 if constexpr (is_statically_named_arg<T>()) {
2697 if (name == T::name) return N;
2699 if constexpr (sizeof...(Args) > 0)
2700 return get_arg_index_by_name<N + 1, Args...>(name);
2701 (void)name; // Workaround an MSVC bug about "unused" parameter.
2702 return -1;
2704 #endif
2706 template <typename... Args, typename Char>
2707 FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
2708 #if FMT_USE_NONTYPE_TEMPLATE_ARGS
2709 if constexpr (sizeof...(Args) > 0)
2710 return get_arg_index_by_name<0, Args...>(name);
2711 #endif
2712 (void)name;
2713 return -1;
2716 template <typename Char, typename... Args> class format_string_checker {
2717 private:
2718 using parse_context_type = compile_parse_context<Char>;
2719 static constexpr int num_args = sizeof...(Args);
2721 // Format specifier parsing function.
2722 // In the future basic_format_parse_context will replace compile_parse_context
2723 // here and will use is_constant_evaluated and downcasting to access the data
2724 // needed for compile-time checks: https://godbolt.org/z/GvWzcTjh1.
2725 using parse_func = const Char* (*)(parse_context_type&);
2727 type types_[num_args > 0 ? static_cast<size_t>(num_args) : 1];
2728 parse_context_type context_;
2729 parse_func parse_funcs_[num_args > 0 ? static_cast<size_t>(num_args) : 1];
2731 public:
2732 explicit FMT_CONSTEXPR format_string_checker(basic_string_view<Char> fmt)
2733 : types_{mapped_type_constant<Args, buffered_context<Char>>::value...},
2734 context_(fmt, num_args, types_),
2735 parse_funcs_{&parse_format_specs<Args, parse_context_type>...} {}
2737 FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
2739 FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); }
2740 FMT_CONSTEXPR auto on_arg_id(int id) -> int {
2741 return context_.check_arg_id(id), id;
2743 FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
2744 #if FMT_USE_NONTYPE_TEMPLATE_ARGS
2745 auto index = get_arg_index_by_name<Args...>(id);
2746 if (index < 0) on_error("named argument is not found");
2747 return index;
2748 #else
2749 (void)id;
2750 on_error("compile-time checks for named arguments require C++20 support");
2751 return 0;
2752 #endif
2755 FMT_CONSTEXPR void on_replacement_field(int id, const Char* begin) {
2756 on_format_specs(id, begin, begin); // Call parse() on empty specs.
2759 FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char*)
2760 -> const Char* {
2761 context_.advance_to(begin);
2762 // id >= 0 check is a workaround for gcc 10 bug (#2065).
2763 return id >= 0 && id < num_args ? parse_funcs_[id](context_) : begin;
2766 FMT_NORETURN FMT_CONSTEXPR void on_error(const char* message) {
2767 report_error(message);
2771 // A base class for compile-time strings.
2772 struct compile_string {};
2774 template <typename S>
2775 using is_compile_string = std::is_base_of<compile_string, S>;
2777 // Reports a compile-time error if S is not a valid format string.
2778 template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
2779 FMT_ALWAYS_INLINE void check_format_string(const S&) {
2780 #ifdef FMT_ENFORCE_COMPILE_STRING
2781 static_assert(is_compile_string<S>::value,
2782 "FMT_ENFORCE_COMPILE_STRING requires all format strings to use "
2783 "FMT_STRING.");
2784 #endif
2786 template <typename... Args, typename S,
2787 FMT_ENABLE_IF(is_compile_string<S>::value)>
2788 void check_format_string(S format_str) {
2789 using char_t = typename S::char_type;
2790 FMT_CONSTEXPR auto s = basic_string_view<char_t>(format_str);
2791 using checker = format_string_checker<char_t, remove_cvref_t<Args>...>;
2792 FMT_CONSTEXPR bool error = (parse_format_string<true>(s, checker(s)), true);
2793 ignore_unused(error);
2796 // Report truncation to prevent silent data loss.
2797 inline void report_truncation(bool truncated) {
2798 if (truncated) report_error("output is truncated");
2801 // Use vformat_args and avoid type_identity to keep symbols short and workaround
2802 // a GCC <= 4.8 bug.
2803 template <typename Char = char> struct vformat_args {
2804 using type = basic_format_args<buffered_context<Char>>;
2806 template <> struct vformat_args<char> {
2807 using type = format_args;
2810 template <typename Char>
2811 void vformat_to(buffer<Char>& buf, basic_string_view<Char> fmt,
2812 typename vformat_args<Char>::type args, locale_ref loc = {});
2814 FMT_API void vprint_mojibake(FILE*, string_view, format_args, bool = false);
2815 #ifndef _WIN32
2816 inline void vprint_mojibake(FILE*, string_view, format_args, bool) {}
2817 #endif
2819 template <typename T, typename Char, type TYPE> struct native_formatter {
2820 private:
2821 dynamic_format_specs<Char> specs_;
2823 public:
2824 using nonlocking = void;
2826 template <typename ParseContext>
2827 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const Char* {
2828 if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin();
2829 auto end = parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, TYPE);
2830 if (const_check(TYPE == type::char_type)) check_char_specs(specs_);
2831 return end;
2834 template <type U = TYPE,
2835 FMT_ENABLE_IF(U == type::string_type || U == type::cstring_type ||
2836 U == type::char_type)>
2837 FMT_CONSTEXPR void set_debug_format(bool set = true) {
2838 specs_.type = set ? presentation_type::debug : presentation_type::none;
2841 template <typename FormatContext>
2842 FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const
2843 -> decltype(ctx.out());
2845 } // namespace detail
2847 FMT_BEGIN_EXPORT
2849 // A formatter specialization for natively supported types.
2850 template <typename T, typename Char>
2851 struct formatter<T, Char,
2852 enable_if_t<detail::type_constant<T, Char>::value !=
2853 detail::type::custom_type>>
2854 : detail::native_formatter<T, Char, detail::type_constant<T, Char>::value> {
2857 template <typename Char = char> struct runtime_format_string {
2858 basic_string_view<Char> str;
2861 /// A compile-time format string.
2862 template <typename Char, typename... Args> class basic_format_string {
2863 private:
2864 basic_string_view<Char> str_;
2866 public:
2867 template <
2868 typename S,
2869 FMT_ENABLE_IF(
2870 std::is_convertible<const S&, basic_string_view<Char>>::value ||
2871 (detail::is_compile_string<S>::value &&
2872 std::is_constructible<basic_string_view<Char>, const S&>::value))>
2873 FMT_CONSTEVAL FMT_ALWAYS_INLINE basic_format_string(const S& s) : str_(s) {
2874 static_assert(
2875 detail::count<
2876 (std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
2877 std::is_reference<Args>::value)...>() == 0,
2878 "passing views as lvalues is disallowed");
2879 #if FMT_USE_CONSTEVAL
2880 if constexpr (detail::count_named_args<Args...>() ==
2881 detail::count_statically_named_args<Args...>()) {
2882 using checker =
2883 detail::format_string_checker<Char, remove_cvref_t<Args>...>;
2884 detail::parse_format_string<true>(str_, checker(s));
2886 #else
2887 detail::check_format_string<Args...>(s);
2888 #endif
2890 basic_format_string(runtime_format_string<Char> fmt) : str_(fmt.str) {}
2892 FMT_ALWAYS_INLINE operator basic_string_view<Char>() const { return str_; }
2893 auto get() const -> basic_string_view<Char> { return str_; }
2896 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
2897 // Workaround broken conversion on older gcc.
2898 template <typename...> using format_string = string_view;
2899 inline auto runtime(string_view s) -> string_view { return s; }
2900 #else
2901 template <typename... Args>
2902 using format_string = basic_format_string<char, type_identity_t<Args>...>;
2904 * Creates a runtime format string.
2906 * **Example**:
2908 * // Check format string at runtime instead of compile-time.
2909 * fmt::print(fmt::runtime("{:d}"), "I am not a number");
2911 inline auto runtime(string_view s) -> runtime_format_string<> { return {{s}}; }
2912 #endif
2914 /// Formats a string and writes the output to `out`.
2915 template <typename OutputIt,
2916 FMT_ENABLE_IF(detail::is_output_iterator<remove_cvref_t<OutputIt>,
2917 char>::value)>
2918 auto vformat_to(OutputIt&& out, string_view fmt, format_args args)
2919 -> remove_cvref_t<OutputIt> {
2920 auto&& buf = detail::get_buffer<char>(out);
2921 detail::vformat_to(buf, fmt, args, {});
2922 return detail::get_iterator(buf, out);
2926 * Formats `args` according to specifications in `fmt`, writes the result to
2927 * the output iterator `out` and returns the iterator past the end of the output
2928 * range. `format_to` does not append a terminating null character.
2930 * **Example**:
2932 * auto out = std::vector<char>();
2933 * fmt::format_to(std::back_inserter(out), "{}", 42);
2935 template <typename OutputIt, typename... T,
2936 FMT_ENABLE_IF(detail::is_output_iterator<remove_cvref_t<OutputIt>,
2937 char>::value)>
2938 FMT_INLINE auto format_to(OutputIt&& out, format_string<T...> fmt, T&&... args)
2939 -> remove_cvref_t<OutputIt> {
2940 return vformat_to(FMT_FWD(out), fmt, fmt::make_format_args(args...));
2943 template <typename OutputIt> struct format_to_n_result {
2944 /// Iterator past the end of the output range.
2945 OutputIt out;
2946 /// Total (not truncated) output size.
2947 size_t size;
2950 template <typename OutputIt, typename... T,
2951 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
2952 auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args)
2953 -> format_to_n_result<OutputIt> {
2954 using traits = detail::fixed_buffer_traits;
2955 auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);
2956 detail::vformat_to(buf, fmt, args, {});
2957 return {buf.out(), buf.count()};
2961 * Formats `args` according to specifications in `fmt`, writes up to `n`
2962 * characters of the result to the output iterator `out` and returns the total
2963 * (not truncated) output size and the iterator past the end of the output
2964 * range. `format_to_n` does not append a terminating null character.
2966 template <typename OutputIt, typename... T,
2967 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
2968 FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string<T...> fmt,
2969 T&&... args) -> format_to_n_result<OutputIt> {
2970 return vformat_to_n(out, n, fmt, fmt::make_format_args(args...));
2973 template <typename OutputIt, typename Sentinel = OutputIt>
2974 struct format_to_result {
2975 /// Iterator pointing to just after the last successful write in the range.
2976 OutputIt out;
2977 /// Specifies if the output was truncated.
2978 bool truncated;
2980 FMT_CONSTEXPR operator OutputIt&() & {
2981 detail::report_truncation(truncated);
2982 return out;
2984 FMT_CONSTEXPR operator const OutputIt&() const& {
2985 detail::report_truncation(truncated);
2986 return out;
2988 FMT_CONSTEXPR operator OutputIt&&() && {
2989 detail::report_truncation(truncated);
2990 return static_cast<OutputIt&&>(out);
2994 template <size_t N>
2995 auto vformat_to(char (&out)[N], string_view fmt, format_args args)
2996 -> format_to_result<char*> {
2997 auto result = vformat_to_n(out, N, fmt, args);
2998 return {result.out, result.size > N};
3001 template <size_t N, typename... T>
3002 FMT_INLINE auto format_to(char (&out)[N], format_string<T...> fmt, T&&... args)
3003 -> format_to_result<char*> {
3004 auto result = fmt::format_to_n(out, N, fmt, static_cast<T&&>(args)...);
3005 return {result.out, result.size > N};
3008 /// Returns the number of chars in the output of `format(fmt, args...)`.
3009 template <typename... T>
3010 FMT_NODISCARD FMT_INLINE auto formatted_size(format_string<T...> fmt,
3011 T&&... args) -> size_t {
3012 auto buf = detail::counting_buffer<>();
3013 detail::vformat_to<char>(buf, fmt, fmt::make_format_args(args...), {});
3014 return buf.count();
3017 FMT_API void vprint(string_view fmt, format_args args);
3018 FMT_API void vprint(FILE* f, string_view fmt, format_args args);
3019 FMT_API void vprint_buffered(FILE* f, string_view fmt, format_args args);
3020 FMT_API void vprintln(FILE* f, string_view fmt, format_args args);
3023 * Formats `args` according to specifications in `fmt` and writes the output
3024 * to `stdout`.
3026 * **Example**:
3028 * fmt::print("The answer is {}.", 42);
3030 template <typename... T>
3031 FMT_INLINE void print(format_string<T...> fmt, T&&... args) {
3032 const auto& vargs = fmt::make_format_args(args...);
3033 if (!detail::use_utf8()) return detail::vprint_mojibake(stdout, fmt, vargs);
3034 return detail::is_locking<T...>() ? vprint_buffered(stdout, fmt, vargs)
3035 : vprint(fmt, vargs);
3039 * Formats `args` according to specifications in `fmt` and writes the
3040 * output to the file `f`.
3042 * **Example**:
3044 * fmt::print(stderr, "Don't {}!", "panic");
3046 template <typename... T>
3047 FMT_INLINE void print(FILE* f, format_string<T...> fmt, T&&... args) {
3048 const auto& vargs = fmt::make_format_args(args...);
3049 if (!detail::use_utf8()) return detail::vprint_mojibake(f, fmt, vargs);
3050 return detail::is_locking<T...>() ? vprint_buffered(f, fmt, vargs)
3051 : vprint(f, fmt, vargs);
3054 /// Formats `args` according to specifications in `fmt` and writes the output
3055 /// to the file `f` followed by a newline.
3056 template <typename... T>
3057 FMT_INLINE void println(FILE* f, format_string<T...> fmt, T&&... args) {
3058 const auto& vargs = fmt::make_format_args(args...);
3059 return detail::use_utf8() ? vprintln(f, fmt, vargs)
3060 : detail::vprint_mojibake(f, fmt, vargs, true);
3063 /// Formats `args` according to specifications in `fmt` and writes the output
3064 /// to `stdout` followed by a newline.
3065 template <typename... T>
3066 FMT_INLINE void println(format_string<T...> fmt, T&&... args) {
3067 return fmt::println(stdout, fmt, static_cast<T&&>(args)...);
3070 FMT_END_EXPORT
3071 FMT_GCC_PRAGMA("GCC pop_options")
3072 FMT_END_NAMESPACE
3074 #ifdef FMT_HEADER_ONLY
3075 # include "format.h"
3076 #endif
3077 #endif // FMT_BASE_H_