1// Formatting library for C++ - the core 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.
7
8#ifndef FMT_CORE_H_
9#define FMT_CORE_H_
10
11#include <cstddef> // std::byte
12#include <cstdio> // std::FILE
13#include <cstring> // std::strlen
14#include <iterator>
15#include <limits>
16#include <string>
17#include <type_traits>
18
19// The fmt library version in the form major * 10000 + minor * 100 + patch.
20#define FMT_VERSION 90101
21
22#if defined(__clang__) && !defined(__ibmxl__)
23# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
24#else
25# define FMT_CLANG_VERSION 0
26#endif
27
28#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && \
29 !defined(__NVCOMPILER)
30# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
31#else
32# define FMT_GCC_VERSION 0
33#endif
34
35#ifndef FMT_GCC_PRAGMA
36// Workaround _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884.
37# if FMT_GCC_VERSION >= 504
38# define FMT_GCC_PRAGMA(arg) _Pragma(arg)
39# else
40# define FMT_GCC_PRAGMA(arg)
41# endif
42#endif
43
44#ifdef __ICL
45# define FMT_ICC_VERSION __ICL
46#elif defined(__INTEL_COMPILER)
47# define FMT_ICC_VERSION __INTEL_COMPILER
48#else
49# define FMT_ICC_VERSION 0
50#endif
51
52#ifdef _MSC_VER
53# define FMT_MSC_VERSION _MSC_VER
54# define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__))
55#else
56# define FMT_MSC_VERSION 0
57# define FMT_MSC_WARNING(...)
58#endif
59
60#ifdef _MSVC_LANG
61# define FMT_CPLUSPLUS _MSVC_LANG
62#else
63# define FMT_CPLUSPLUS __cplusplus
64#endif
65
66#ifdef __has_feature
67# define FMT_HAS_FEATURE(x) __has_feature(x)
68#else
69# define FMT_HAS_FEATURE(x) 0
70#endif
71
72#if defined(__has_include) || FMT_ICC_VERSION >= 1600 || FMT_MSC_VERSION > 1900
73# define FMT_HAS_INCLUDE(x) __has_include(x)
74#else
75# define FMT_HAS_INCLUDE(x) 0
76#endif
77
78#ifdef __has_cpp_attribute
79# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
80#else
81# define FMT_HAS_CPP_ATTRIBUTE(x) 0
82#endif
83
84#define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
85 (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
86
87#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \
88 (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))
89
90// Check if relaxed C++14 constexpr is supported.
91// GCC doesn't allow throw in constexpr until version 6 (bug 67371).
92#ifndef FMT_USE_CONSTEXPR
93# if (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912 || \
94 (FMT_GCC_VERSION >= 600 && FMT_CPLUSPLUS >= 201402L)) && \
95 !FMT_ICC_VERSION && !defined(__NVCC__)
96# define FMT_USE_CONSTEXPR 1
97# else
98# define FMT_USE_CONSTEXPR 0
99# endif
100#endif
101#if FMT_USE_CONSTEXPR
102# define FMT_CONSTEXPR constexpr
103#else
104# define FMT_CONSTEXPR
105#endif
106
107#if ((FMT_CPLUSPLUS >= 202002L) && \
108 (!defined(_GLIBCXX_RELEASE) || _GLIBCXX_RELEASE > 9)) || \
109 (FMT_CPLUSPLUS >= 201709L && FMT_GCC_VERSION >= 1002)
110# define FMT_CONSTEXPR20 constexpr
111#else
112# define FMT_CONSTEXPR20
113#endif
114
115// Check if constexpr std::char_traits<>::{compare,length} are supported.
116#if defined(__GLIBCXX__)
117# if FMT_CPLUSPLUS >= 201703L && defined(_GLIBCXX_RELEASE) && \
118 _GLIBCXX_RELEASE >= 7 // GCC 7+ libstdc++ has _GLIBCXX_RELEASE.
119# define FMT_CONSTEXPR_CHAR_TRAITS constexpr
120# endif
121#elif defined(_LIBCPP_VERSION) && FMT_CPLUSPLUS >= 201703L && \
122 _LIBCPP_VERSION >= 4000
123# define FMT_CONSTEXPR_CHAR_TRAITS constexpr
124#elif FMT_MSC_VERSION >= 1914 && FMT_CPLUSPLUS >= 201703L
125# define FMT_CONSTEXPR_CHAR_TRAITS constexpr
126#endif
127#ifndef FMT_CONSTEXPR_CHAR_TRAITS
128# define FMT_CONSTEXPR_CHAR_TRAITS
129#endif
130
131// Check if exceptions are disabled.
132#ifndef FMT_EXCEPTIONS
133# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \
134 (FMT_MSC_VERSION && !_HAS_EXCEPTIONS)
135# define FMT_EXCEPTIONS 0
136# else
137# define FMT_EXCEPTIONS 1
138# endif
139#endif
140
141#ifndef FMT_DEPRECATED
142# if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VERSION >= 1900
143# define FMT_DEPRECATED [[deprecated]]
144# else
145# if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__)
146# define FMT_DEPRECATED __attribute__((deprecated))
147# elif FMT_MSC_VERSION
148# define FMT_DEPRECATED __declspec(deprecated)
149# else
150# define FMT_DEPRECATED /* deprecated */
151# endif
152# endif
153#endif
154
155// [[noreturn]] is disabled on MSVC and NVCC because of bogus unreachable code
156// warnings.
157#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && \
158 !defined(__NVCC__)
159# define FMT_NORETURN [[noreturn]]
160#else
161# define FMT_NORETURN
162#endif
163
164#if FMT_HAS_CPP17_ATTRIBUTE(fallthrough)
165# define FMT_FALLTHROUGH [[fallthrough]]
166#elif defined(__clang__)
167# define FMT_FALLTHROUGH [[clang::fallthrough]]
168#elif FMT_GCC_VERSION >= 700 && \
169 (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)
170# define FMT_FALLTHROUGH [[gnu::fallthrough]]
171#else
172# define FMT_FALLTHROUGH
173#endif
174
175#ifndef FMT_NODISCARD
176# if FMT_HAS_CPP17_ATTRIBUTE(nodiscard)
177# define FMT_NODISCARD [[nodiscard]]
178# else
179# define FMT_NODISCARD
180# endif
181#endif
182
183#ifndef FMT_USE_FLOAT
184# define FMT_USE_FLOAT 1
185#endif
186#ifndef FMT_USE_DOUBLE
187# define FMT_USE_DOUBLE 1
188#endif
189#ifndef FMT_USE_LONG_DOUBLE
190# define FMT_USE_LONG_DOUBLE 1
191#endif
192
193#ifndef FMT_INLINE
194# if FMT_GCC_VERSION || FMT_CLANG_VERSION
195# define FMT_INLINE inline __attribute__((always_inline))
196# else
197# define FMT_INLINE inline
198# endif
199#endif
200
201// An inline std::forward replacement.
202#define FMT_FORWARD(...) static_cast<decltype(__VA_ARGS__)&&>(__VA_ARGS__)
203
204#ifdef _MSC_VER
205# define FMT_UNCHECKED_ITERATOR(It) \
206 using _Unchecked_type = It // Mark iterator as checked.
207#else
208# define FMT_UNCHECKED_ITERATOR(It) using unchecked_type = It
209#endif
210
211#ifndef FMT_BEGIN_NAMESPACE
212# define FMT_BEGIN_NAMESPACE \
213 namespace fmt { \
214 inline namespace v9 {
215# define FMT_END_NAMESPACE \
216 } \
217 }
218#endif
219
220#ifndef FMT_MODULE_EXPORT
221# define FMT_MODULE_EXPORT
222# define FMT_MODULE_EXPORT_BEGIN
223# define FMT_MODULE_EXPORT_END
224# define FMT_BEGIN_DETAIL_NAMESPACE namespace detail {
225# define FMT_END_DETAIL_NAMESPACE }
226#endif
227
228#if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
229# define FMT_CLASS_API FMT_MSC_WARNING(suppress : 4275)
230# ifdef FMT_EXPORT
231# define FMT_API __declspec(dllexport)
232# elif defined(FMT_SHARED)
233# define FMT_API __declspec(dllimport)
234# endif
235#else
236# define FMT_CLASS_API
237# if defined(FMT_EXPORT) || defined(FMT_SHARED)
238# if defined(__GNUC__) || defined(__clang__)
239# define FMT_API __attribute__((visibility("default")))
240# endif
241# endif
242#endif
243#ifndef FMT_API
244# define FMT_API
245#endif
246
247// libc++ supports string_view in pre-c++17.
248#if FMT_HAS_INCLUDE(<string_view>) && \
249 (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION))
250# include <string_view>
251# define FMT_USE_STRING_VIEW
252#elif FMT_HAS_INCLUDE("experimental/string_view") && FMT_CPLUSPLUS >= 201402L
253# include <experimental/string_view>
254# define FMT_USE_EXPERIMENTAL_STRING_VIEW
255#endif
256
257#ifndef FMT_UNICODE
258# define FMT_UNICODE !FMT_MSC_VERSION
259#endif
260
261#ifndef FMT_CONSTEVAL
262# if ((FMT_GCC_VERSION >= 1000 || FMT_CLANG_VERSION >= 1101) && \
263 FMT_CPLUSPLUS >= 202002L && !defined(__apple_build_version__)) || \
264 (defined(__cpp_consteval) && \
265 (!FMT_MSC_VERSION || _MSC_FULL_VER >= 193030704))
266// consteval is broken in MSVC before VS2022 and Apple clang 13.
267# define FMT_CONSTEVAL consteval
268# define FMT_HAS_CONSTEVAL
269# else
270# define FMT_CONSTEVAL
271# endif
272#endif
273
274#ifndef FMT_USE_NONTYPE_TEMPLATE_ARGS
275# if defined(__cpp_nontype_template_args) && \
276 ((FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L) || \
277 __cpp_nontype_template_args >= 201911L) && \
278 !defined(__NVCOMPILER) && !defined(__LCC__)
279# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
280# else
281# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0
282# endif
283#endif
284
285// Enable minimal optimizations for more compact code in debug mode.
286FMT_GCC_PRAGMA("GCC push_options")
287#if !defined(__OPTIMIZE__) && !defined(__NVCOMPILER) && !defined(__LCC__)
288FMT_GCC_PRAGMA("GCC optimize(\"Og\")")
289#endif
290
291FMT_BEGIN_NAMESPACE
292FMT_MODULE_EXPORT_BEGIN
293
294// Implementations of enable_if_t and other metafunctions for older systems.
295template <bool B, typename T = void>
296using enable_if_t = typename std::enable_if<B, T>::type;
297template <bool B, typename T, typename F>
298using conditional_t = typename std::conditional<B, T, F>::type;
299template <bool B> using bool_constant = std::integral_constant<bool, B>;
300template <typename T>
301using remove_reference_t = typename std::remove_reference<T>::type;
302template <typename T>
303using remove_const_t = typename std::remove_const<T>::type;
304template <typename T>
305using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
306template <typename T> struct type_identity { using type = T; };
307template <typename T> using type_identity_t = typename type_identity<T>::type;
308template <typename T>
309using underlying_t = typename std::underlying_type<T>::type;
310
311template <typename...> struct disjunction : std::false_type {};
312template <typename P> struct disjunction<P> : P {};
313template <typename P1, typename... Pn>
314struct disjunction<P1, Pn...>
315 : conditional_t<bool(P1::value), P1, disjunction<Pn...>> {};
316
317template <typename...> struct conjunction : std::true_type {};
318template <typename P> struct conjunction<P> : P {};
319template <typename P1, typename... Pn>
320struct conjunction<P1, Pn...>
321 : conditional_t<bool(P1::value), conjunction<Pn...>, P1> {};
322
323struct monostate {
324 constexpr monostate() {}
325};
326
327// An enable_if helper to be used in template parameters which results in much
328// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed
329// to workaround a bug in MSVC 2019 (see #1140 and #1186).
330#ifdef FMT_DOC
331# define FMT_ENABLE_IF(...)
332#else
333# define FMT_ENABLE_IF(...) fmt::enable_if_t<(__VA_ARGS__), int> = 0
334#endif
335
336FMT_BEGIN_DETAIL_NAMESPACE
337
338// Suppresses "unused variable" warnings with the method described in
339// https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/.
340// (void)var does not work on many Intel compilers.
341template <typename... T> FMT_CONSTEXPR void ignore_unused(const T&...) {}
342
343constexpr FMT_INLINE auto is_constant_evaluated(
344 bool default_value = false) noexcept -> bool {
345#ifdef __cpp_lib_is_constant_evaluated
346 ignore_unused(default_value);
347 return std::is_constant_evaluated();
348#else
349 return default_value;
350#endif
351}
352
353// Suppresses "conditional expression is constant" warnings.
354template <typename T> constexpr FMT_INLINE auto const_check(T value) -> T {
355 return value;
356}
357
358FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
359 const char* message);
360
361#ifndef FMT_ASSERT
362# ifdef NDEBUG
363// FMT_ASSERT is not empty to avoid -Wempty-body.
364# define FMT_ASSERT(condition, message) \
365 ::fmt::detail::ignore_unused((condition), (message))
366# else
367# define FMT_ASSERT(condition, message) \
368 ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
369 ? (void)0 \
370 : ::fmt::detail::assert_fail(__FILE__, __LINE__, (message)))
371# endif
372#endif
373
374#if defined(FMT_USE_STRING_VIEW)
375template <typename Char> using std_string_view = std::basic_string_view<Char>;
376#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW)
377template <typename Char>
378using std_string_view = std::experimental::basic_string_view<Char>;
379#else
380template <typename T> struct std_string_view {};
381#endif
382
383#ifdef FMT_USE_INT128
384// Do nothing.
385#elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \
386 !(FMT_CLANG_VERSION && FMT_MSC_VERSION)
387# define FMT_USE_INT128 1
388using int128_opt = __int128_t; // An optional native 128-bit integer.
389using uint128_opt = __uint128_t;
390template <typename T> inline auto convert_for_visit(T value) -> T {
391 return value;
392}
393#else
394# define FMT_USE_INT128 0
395#endif
396#if !FMT_USE_INT128
397enum class int128_opt {};
398enum class uint128_opt {};
399// Reduce template instantiations.
400template <typename T> auto convert_for_visit(T) -> monostate { return {}; }
401#endif
402
403// Casts a nonnegative integer to unsigned.
404template <typename Int>
405FMT_CONSTEXPR auto to_unsigned(Int value) ->
406 typename std::make_unsigned<Int>::type {
407 FMT_ASSERT(std::is_unsigned<Int>::value || value >= 0, "negative value");
408 return static_cast<typename std::make_unsigned<Int>::type>(value);
409}
410
411FMT_MSC_WARNING(suppress : 4566) constexpr unsigned char micro[] = "\u00B5";
412
413constexpr auto is_utf8() -> bool {
414 // Avoid buggy sign extensions in MSVC's constant evaluation mode (#2297).
415 using uchar = unsigned char;
416 return FMT_UNICODE || (sizeof(micro) == 3 && uchar(micro[0]) == 0xC2 &&
417 uchar(micro[1]) == 0xB5);
418}
419FMT_END_DETAIL_NAMESPACE
420
421/**
422 An implementation of ``std::basic_string_view`` for pre-C++17. It provides a
423 subset of the API. ``fmt::basic_string_view`` is used for format strings even
424 if ``std::string_view`` is available to prevent issues when a library is
425 compiled with a different ``-std`` option than the client code (which is not
426 recommended).
427 */
428template <typename Char> class basic_string_view {
429 private:
430 const Char* data_;
431 size_t size_;
432
433 public:
434 using value_type = Char;
435 using iterator = const Char*;
436
437 constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {}
438
439 /** Constructs a string reference object from a C string and a size. */
440 constexpr basic_string_view(const Char* s, size_t count) noexcept
441 : data_(s), size_(count) {}
442
443 /**
444 \rst
445 Constructs a string reference object from a C string computing
446 the size with ``std::char_traits<Char>::length``.
447 \endrst
448 */
449 FMT_CONSTEXPR_CHAR_TRAITS
450 FMT_INLINE
451 basic_string_view(const Char* s)
452 : data_(s),
453 size_(detail::const_check(std::is_same<Char, char>::value &&
454 !detail::is_constant_evaluated(true))
455 ? std::strlen(reinterpret_cast<const char*>(s))
456 : std::char_traits<Char>::length(s)) {}
457
458 /** Constructs a string reference from a ``std::basic_string`` object. */
459 template <typename Traits, typename Alloc>
460 FMT_CONSTEXPR basic_string_view(
461 const std::basic_string<Char, Traits, Alloc>& s) noexcept
462 : data_(s.data()), size_(s.size()) {}
463
464 template <typename S, FMT_ENABLE_IF(std::is_same<
465 S, detail::std_string_view<Char>>::value)>
466 FMT_CONSTEXPR basic_string_view(S s) noexcept
467 : data_(s.data()), size_(s.size()) {}
468
469 /** Returns a pointer to the string data. */
470 constexpr auto data() const noexcept -> const Char* { return data_; }
471
472 /** Returns the string size. */
473 constexpr auto size() const noexcept -> size_t { return size_; }
474
475 constexpr auto begin() const noexcept -> iterator { return data_; }
476 constexpr auto end() const noexcept -> iterator { return data_ + size_; }
477
478 constexpr auto operator[](size_t pos) const noexcept -> const Char& {
479 return data_[pos];
480 }
481
482 FMT_CONSTEXPR void remove_prefix(size_t n) noexcept {
483 data_ += n;
484 size_ -= n;
485 }
486
487 FMT_CONSTEXPR_CHAR_TRAITS bool starts_with(
488 basic_string_view<Char> sv) const noexcept {
489 return size_ >= sv.size_ &&
490 std::char_traits<Char>::compare(data_, sv.data_, sv.size_) == 0;
491 }
492 FMT_CONSTEXPR_CHAR_TRAITS bool starts_with(Char c) const noexcept {
493 return size_ >= 1 && std::char_traits<Char>::eq(*data_, c);
494 }
495 FMT_CONSTEXPR_CHAR_TRAITS bool starts_with(const Char* s) const {
496 return starts_with(basic_string_view<Char>(s));
497 }
498
499 // Lexicographically compare this string reference to other.
500 FMT_CONSTEXPR_CHAR_TRAITS auto compare(basic_string_view other) const -> int {
501 size_t str_size = size_ < other.size_ ? size_ : other.size_;
502 int result = std::char_traits<Char>::compare(data_, other.data_, str_size);
503 if (result == 0)
504 result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
505 return result;
506 }
507
508 FMT_CONSTEXPR_CHAR_TRAITS friend auto operator==(basic_string_view lhs,
509 basic_string_view rhs)
510 -> bool {
511 return lhs.compare(rhs) == 0;
512 }
513 friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool {
514 return lhs.compare(rhs) != 0;
515 }
516 friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool {
517 return lhs.compare(rhs) < 0;
518 }
519 friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool {
520 return lhs.compare(rhs) <= 0;
521 }
522 friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool {
523 return lhs.compare(rhs) > 0;
524 }
525 friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool {
526 return lhs.compare(rhs) >= 0;
527 }
528};
529
530using string_view = basic_string_view<char>;
531
532/** Specifies if ``T`` is a character type. Can be specialized by users. */
533template <typename T> struct is_char : std::false_type {};
534template <> struct is_char<char> : std::true_type {};
535
536FMT_BEGIN_DETAIL_NAMESPACE
537
538// A base class for compile-time strings.
539struct compile_string {};
540
541template <typename S>
542struct is_compile_string : std::is_base_of<compile_string, S> {};
543
544// Returns a string view of `s`.
545template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
546FMT_INLINE auto to_string_view(const Char* s) -> basic_string_view<Char> {
547 return s;
548}
549template <typename Char, typename Traits, typename Alloc>
550inline auto to_string_view(const std::basic_string<Char, Traits, Alloc>& s)
551 -> basic_string_view<Char> {
552 return s;
553}
554template <typename Char>
555constexpr auto to_string_view(basic_string_view<Char> s)
556 -> basic_string_view<Char> {
557 return s;
558}
559template <typename Char,
560 FMT_ENABLE_IF(!std::is_empty<std_string_view<Char>>::value)>
561inline auto to_string_view(std_string_view<Char> s) -> basic_string_view<Char> {
562 return s;
563}
564template <typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
565constexpr auto to_string_view(const S& s)
566 -> basic_string_view<typename S::char_type> {
567 return basic_string_view<typename S::char_type>(s);
568}
569void to_string_view(...);
570
571// Specifies whether S is a string type convertible to fmt::basic_string_view.
572// It should be a constexpr function but MSVC 2017 fails to compile it in
573// enable_if and MSVC 2015 fails to compile it as an alias template.
574// ADL invocation of to_string_view is DEPRECATED!
575template <typename S>
576struct is_string : std::is_class<decltype(to_string_view(std::declval<S>()))> {
577};
578
579template <typename S, typename = void> struct char_t_impl {};
580template <typename S> struct char_t_impl<S, enable_if_t<is_string<S>::value>> {
581 using result = decltype(to_string_view(std::declval<S>()));
582 using type = typename result::value_type;
583};
584
585enum class type {
586 none_type,
587 // Integer types should go first,
588 int_type,
589 uint_type,
590 long_long_type,
591 ulong_long_type,
592 int128_type,
593 uint128_type,
594 bool_type,
595 char_type,
596 last_integer_type = char_type,
597 // followed by floating-point types.
598 float_type,
599 double_type,
600 long_double_type,
601 last_numeric_type = long_double_type,
602 cstring_type,
603 string_type,
604 pointer_type,
605 custom_type
606};
607
608// Maps core type T to the corresponding type enum constant.
609template <typename T, typename Char>
610struct type_constant : std::integral_constant<type, type::custom_type> {};
611
612#define FMT_TYPE_CONSTANT(Type, constant) \
613 template <typename Char> \
614 struct type_constant<Type, Char> \
615 : std::integral_constant<type, type::constant> {}
616
617FMT_TYPE_CONSTANT(int, int_type);
618FMT_TYPE_CONSTANT(unsigned, uint_type);
619FMT_TYPE_CONSTANT(long long, long_long_type);
620FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
621FMT_TYPE_CONSTANT(int128_opt, int128_type);
622FMT_TYPE_CONSTANT(uint128_opt, uint128_type);
623FMT_TYPE_CONSTANT(bool, bool_type);
624FMT_TYPE_CONSTANT(Char, char_type);
625FMT_TYPE_CONSTANT(float, float_type);
626FMT_TYPE_CONSTANT(double, double_type);
627FMT_TYPE_CONSTANT(long double, long_double_type);
628FMT_TYPE_CONSTANT(const Char*, cstring_type);
629FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
630FMT_TYPE_CONSTANT(const void*, pointer_type);
631
632constexpr bool is_integral_type(type t) {
633 return t > type::none_type && t <= type::last_integer_type;
634}
635
636constexpr bool is_arithmetic_type(type t) {
637 return t > type::none_type && t <= type::last_numeric_type;
638}
639
640FMT_NORETURN FMT_API void throw_format_error(const char* message);
641
642struct error_handler {
643 constexpr error_handler() = default;
644 constexpr error_handler(const error_handler&) = default;
645
646 // This function is intentionally not constexpr to give a compile-time error.
647 FMT_NORETURN void on_error(const char* message) {
648 throw_format_error(message);
649 }
650};
651FMT_END_DETAIL_NAMESPACE
652
653/** String's character type. */
654template <typename S> using char_t = typename detail::char_t_impl<S>::type;
655
656/**
657 \rst
658 Parsing context consisting of a format string range being parsed and an
659 argument counter for automatic indexing.
660 You can use the ``format_parse_context`` type alias for ``char`` instead.
661 \endrst
662 */
663template <typename Char, typename ErrorHandler = detail::error_handler>
664class basic_format_parse_context : private ErrorHandler {
665 private:
666 basic_string_view<Char> format_str_;
667 int next_arg_id_;
668
669 FMT_CONSTEXPR void do_check_arg_id(int id);
670
671 public:
672 using char_type = Char;
673 using iterator = typename basic_string_view<Char>::iterator;
674
675 explicit constexpr basic_format_parse_context(
676 basic_string_view<Char> format_str, ErrorHandler eh = {},
677 int next_arg_id = 0)
678 : ErrorHandler(eh), format_str_(format_str), next_arg_id_(next_arg_id) {}
679
680 /**
681 Returns an iterator to the beginning of the format string range being
682 parsed.
683 */
684 constexpr auto begin() const noexcept -> iterator {
685 return format_str_.begin();
686 }
687
688 /**
689 Returns an iterator past the end of the format string range being parsed.
690 */
691 constexpr auto end() const noexcept -> iterator { return format_str_.end(); }
692
693 /** Advances the begin iterator to ``it``. */
694 FMT_CONSTEXPR void advance_to(iterator it) {
695 format_str_.remove_prefix(detail::to_unsigned(it - begin()));
696 }
697
698 /**
699 Reports an error if using the manual argument indexing; otherwise returns
700 the next argument index and switches to the automatic indexing.
701 */
702 FMT_CONSTEXPR auto next_arg_id() -> int {
703 if (next_arg_id_ < 0) {
704 on_error("cannot switch from manual to automatic argument indexing");
705 return 0;
706 }
707 int id = next_arg_id_++;
708 do_check_arg_id(id);
709 return id;
710 }
711
712 /**
713 Reports an error if using the automatic argument indexing; otherwise
714 switches to the manual indexing.
715 */
716 FMT_CONSTEXPR void check_arg_id(int id) {
717 if (next_arg_id_ > 0) {
718 on_error("cannot switch from automatic to manual argument indexing");
719 return;
720 }
721 next_arg_id_ = -1;
722 do_check_arg_id(id);
723 }
724 FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {}
725 FMT_CONSTEXPR void check_dynamic_spec(int arg_id);
726
727 FMT_CONSTEXPR void on_error(const char* message) {
728 ErrorHandler::on_error(message);
729 }
730
731 constexpr auto error_handler() const -> ErrorHandler { return *this; }
732};
733
734using format_parse_context = basic_format_parse_context<char>;
735
736FMT_BEGIN_DETAIL_NAMESPACE
737// A parse context with extra data used only in compile-time checks.
738template <typename Char, typename ErrorHandler = detail::error_handler>
739class compile_parse_context
740 : public basic_format_parse_context<Char, ErrorHandler> {
741 private:
742 int num_args_;
743 const type* types_;
744 using base = basic_format_parse_context<Char, ErrorHandler>;
745
746 public:
747 explicit FMT_CONSTEXPR compile_parse_context(
748 basic_string_view<Char> format_str, int num_args, const type* types,
749 ErrorHandler eh = {}, int next_arg_id = 0)
750 : base(format_str, eh, next_arg_id), num_args_(num_args), types_(types) {}
751
752 constexpr auto num_args() const -> int { return num_args_; }
753 constexpr auto arg_type(int id) const -> type { return types_[id]; }
754
755 FMT_CONSTEXPR auto next_arg_id() -> int {
756 int id = base::next_arg_id();
757 if (id >= num_args_) this->on_error("argument not found");
758 return id;
759 }
760
761 FMT_CONSTEXPR void check_arg_id(int id) {
762 base::check_arg_id(id);
763 if (id >= num_args_) this->on_error("argument not found");
764 }
765 using base::check_arg_id;
766
767 FMT_CONSTEXPR void check_dynamic_spec(int arg_id) {
768 detail::ignore_unused(arg_id);
769#if !defined(__LCC__)
770 if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id]))
771 this->on_error("width/precision is not integer");
772#endif
773 }
774};
775FMT_END_DETAIL_NAMESPACE
776
777template <typename Char, typename ErrorHandler>
778FMT_CONSTEXPR void
779basic_format_parse_context<Char, ErrorHandler>::do_check_arg_id(int id) {
780 // Argument id is only checked at compile-time during parsing because
781 // formatting has its own validation.
782 if (detail::is_constant_evaluated() && FMT_GCC_VERSION >= 1200) {
783 using context = detail::compile_parse_context<Char, ErrorHandler>;
784 if (id >= static_cast<context*>(this)->num_args())
785 on_error("argument not found");
786 }
787}
788
789template <typename Char, typename ErrorHandler>
790FMT_CONSTEXPR void
791basic_format_parse_context<Char, ErrorHandler>::check_dynamic_spec(int arg_id) {
792 if (detail::is_constant_evaluated()) {
793 using context = detail::compile_parse_context<Char, ErrorHandler>;
794 static_cast<context*>(this)->check_dynamic_spec(arg_id);
795 }
796}
797
798template <typename Context> class basic_format_arg;
799template <typename Context> class basic_format_args;
800template <typename Context> class dynamic_format_arg_store;
801
802// A formatter for objects of type T.
803template <typename T, typename Char = char, typename Enable = void>
804struct formatter {
805 // A deleted default constructor indicates a disabled formatter.
806 formatter() = delete;
807};
808
809// Specifies if T has an enabled formatter specialization. A type can be
810// formattable even if it doesn't have a formatter e.g. via a conversion.
811template <typename T, typename Context>
812using has_formatter =
813 std::is_constructible<typename Context::template formatter_type<T>>;
814
815// Checks whether T is a container with contiguous storage.
816template <typename T> struct is_contiguous : std::false_type {};
817template <typename Char>
818struct is_contiguous<std::basic_string<Char>> : std::true_type {};
819
820class appender;
821
822FMT_BEGIN_DETAIL_NAMESPACE
823
824template <typename Context, typename T>
825constexpr auto has_const_formatter_impl(T*)
826 -> decltype(typename Context::template formatter_type<T>().format(
827 std::declval<const T&>(), std::declval<Context&>()),
828 true) {
829 return true;
830}
831template <typename Context>
832constexpr auto has_const_formatter_impl(...) -> bool {
833 return false;
834}
835template <typename T, typename Context>
836constexpr auto has_const_formatter() -> bool {
837 return has_const_formatter_impl<Context>(static_cast<T*>(nullptr));
838}
839
840// Extracts a reference to the container from back_insert_iterator.
841template <typename Container>
842inline auto get_container(std::back_insert_iterator<Container> it)
843 -> Container& {
844 using base = std::back_insert_iterator<Container>;
845 struct accessor : base {
846 accessor(base b) : base(b) {}
847 using base::container;
848 };
849 return *accessor(it).container;
850}
851
852template <typename Char, typename InputIt, typename OutputIt>
853FMT_CONSTEXPR auto copy_str(InputIt begin, InputIt end, OutputIt out)
854 -> OutputIt {
855 while (begin != end) *out++ = static_cast<Char>(*begin++);
856 return out;
857}
858
859template <typename Char, typename T, typename U,
860 FMT_ENABLE_IF(
861 std::is_same<remove_const_t<T>, U>::value&& is_char<U>::value)>
862FMT_CONSTEXPR auto copy_str(T* begin, T* end, U* out) -> U* {
863 if (is_constant_evaluated()) return copy_str<Char, T*, U*>(begin, end, out);
864 auto size = to_unsigned(end - begin);
865 memcpy(out, begin, size * sizeof(U));
866 return out + size;
867}
868
869/**
870 \rst
871 A contiguous memory buffer with an optional growing ability. It is an internal
872 class and shouldn't be used directly, only via `~fmt::basic_memory_buffer`.
873 \endrst
874 */
875template <typename T> class buffer {
876 private:
877 T* ptr_;
878 size_t size_;
879 size_t capacity_;
880
881 protected:
882 // Don't initialize ptr_ since it is not accessed to save a few cycles.
883 FMT_MSC_WARNING(suppress : 26495)
884 buffer(size_t sz) noexcept : size_(sz), capacity_(sz) {}
885
886 FMT_CONSTEXPR20 buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) noexcept
887 : ptr_(p), size_(sz), capacity_(cap) {}
888
889 FMT_CONSTEXPR20 ~buffer() = default;
890 buffer(buffer&&) = default;
891
892 /** Sets the buffer data and capacity. */
893 FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept {
894 ptr_ = buf_data;
895 capacity_ = buf_capacity;
896 }
897
898 /** Increases the buffer capacity to hold at least *capacity* elements. */
899 virtual FMT_CONSTEXPR20 void grow(size_t capacity) = 0;
900
901 public:
902 using value_type = T;
903 using const_reference = const T&;
904
905 buffer(const buffer&) = delete;
906 void operator=(const buffer&) = delete;
907
908 FMT_INLINE auto begin() noexcept -> T* { return ptr_; }
909 FMT_INLINE auto end() noexcept -> T* { return ptr_ + size_; }
910
911 FMT_INLINE auto begin() const noexcept -> const T* { return ptr_; }
912 FMT_INLINE auto end() const noexcept -> const T* { return ptr_ + size_; }
913
914 /** Returns the size of this buffer. */
915 constexpr auto size() const noexcept -> size_t { return size_; }
916
917 /** Returns the capacity of this buffer. */
918 constexpr auto capacity() const noexcept -> size_t { return capacity_; }
919
920 /** Returns a pointer to the buffer data. */
921 FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; }
922
923 /** Returns a pointer to the buffer data. */
924 FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; }
925
926 /** Clears this buffer. */
927 void clear() { size_ = 0; }
928
929 // Tries resizing the buffer to contain *count* elements. If T is a POD type
930 // the new elements may not be initialized.
931 FMT_CONSTEXPR20 void try_resize(size_t count) {
932 try_reserve(count);
933 size_ = count <= capacity_ ? count : capacity_;
934 }
935
936 // Tries increasing the buffer capacity to *new_capacity*. It can increase the
937 // capacity by a smaller amount than requested but guarantees there is space
938 // for at least one additional element either by increasing the capacity or by
939 // flushing the buffer if it is full.
940 FMT_CONSTEXPR20 void try_reserve(size_t new_capacity) {
941 if (new_capacity > capacity_) grow(new_capacity);
942 }
943
944 FMT_CONSTEXPR20 void push_back(const T& value) {
945 try_reserve(size_ + 1);
946 ptr_[size_++] = value;
947 }
948
949 /** Appends data to the end of the buffer. */
950 template <typename U> void append(const U* begin, const U* end);
951
952 template <typename Idx> FMT_CONSTEXPR auto operator[](Idx index) -> T& {
953 return ptr_[index];
954 }
955 template <typename Idx>
956 FMT_CONSTEXPR auto operator[](Idx index) const -> const T& {
957 return ptr_[index];
958 }
959};
960
961struct buffer_traits {
962 explicit buffer_traits(size_t) {}
963 auto count() const -> size_t { return 0; }
964 auto limit(size_t size) -> size_t { return size; }
965};
966
967class fixed_buffer_traits {
968 private:
969 size_t count_ = 0;
970 size_t limit_;
971
972 public:
973 explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}
974 auto count() const -> size_t { return count_; }
975 auto limit(size_t size) -> size_t {
976 size_t n = limit_ > count_ ? limit_ - count_ : 0;
977 count_ += size;
978 return size < n ? size : n;
979 }
980};
981
982// A buffer that writes to an output iterator when flushed.
983template <typename OutputIt, typename T, typename Traits = buffer_traits>
984class iterator_buffer final : public Traits, public buffer<T> {
985 private:
986 OutputIt out_;
987 enum { buffer_size = 256 };
988 T data_[buffer_size];
989
990 protected:
991 FMT_CONSTEXPR20 void grow(size_t) override {
992 if (this->size() == buffer_size) flush();
993 }
994
995 void flush() {
996 auto size = this->size();
997 this->clear();
998 out_ = copy_str<T>(data_, data_ + this->limit(size), out_);
999 }
1000
1001 public:
1002 explicit iterator_buffer(OutputIt out, size_t n = buffer_size)
1003 : Traits(n), buffer<T>(data_, 0, buffer_size), out_(out) {}
1004 iterator_buffer(iterator_buffer&& other)
1005 : Traits(other), buffer<T>(data_, 0, buffer_size), out_(other.out_) {}
1006 ~iterator_buffer() { flush(); }
1007
1008 auto out() -> OutputIt {
1009 flush();
1010 return out_;
1011 }
1012 auto count() const -> size_t { return Traits::count() + this->size(); }
1013};
1014
1015template <typename T>
1016class iterator_buffer<T*, T, fixed_buffer_traits> final
1017 : public fixed_buffer_traits,
1018 public buffer<T> {
1019 private:
1020 T* out_;
1021 enum { buffer_size = 256 };
1022 T data_[buffer_size];
1023
1024 protected:
1025 FMT_CONSTEXPR20 void grow(size_t) override {
1026 if (this->size() == this->capacity()) flush();
1027 }
1028
1029 void flush() {
1030 size_t n = this->limit(this->size());
1031 if (this->data() == out_) {
1032 out_ += n;
1033 this->set(data_, buffer_size);
1034 }
1035 this->clear();
1036 }
1037
1038 public:
1039 explicit iterator_buffer(T* out, size_t n = buffer_size)
1040 : fixed_buffer_traits(n), buffer<T>(out, 0, n), out_(out) {}
1041 iterator_buffer(iterator_buffer&& other)
1042 : fixed_buffer_traits(other),
1043 buffer<T>(std::move(other)),
1044 out_(other.out_) {
1045 if (this->data() != out_) {
1046 this->set(data_, buffer_size);
1047 this->clear();
1048 }
1049 }
1050 ~iterator_buffer() { flush(); }
1051
1052 auto out() -> T* {
1053 flush();
1054 return out_;
1055 }
1056 auto count() const -> size_t {
1057 return fixed_buffer_traits::count() + this->size();
1058 }
1059};
1060
1061template <typename T> class iterator_buffer<T*, T> final : public buffer<T> {
1062 protected:
1063 FMT_CONSTEXPR20 void grow(size_t) override {}
1064
1065 public:
1066 explicit iterator_buffer(T* out, size_t = 0) : buffer<T>(out, 0, ~size_t()) {}
1067
1068 auto out() -> T* { return &*this->end(); }
1069};
1070
1071// A buffer that writes to a container with the contiguous storage.
1072template <typename Container>
1073class iterator_buffer<std::back_insert_iterator<Container>,
1074 enable_if_t<is_contiguous<Container>::value,
1075 typename Container::value_type>>
1076 final : public buffer<typename Container::value_type> {
1077 private:
1078 Container& container_;
1079
1080 protected:
1081 FMT_CONSTEXPR20 void grow(size_t capacity) override {
1082 container_.resize(capacity);
1083 this->set(&container_[0], capacity);
1084 }
1085
1086 public:
1087 explicit iterator_buffer(Container& c)
1088 : buffer<typename Container::value_type>(c.size()), container_(c) {}
1089 explicit iterator_buffer(std::back_insert_iterator<Container> out, size_t = 0)
1090 : iterator_buffer(get_container(out)) {}
1091
1092 auto out() -> std::back_insert_iterator<Container> {
1093 return std::back_inserter(container_);
1094 }
1095};
1096
1097// A buffer that counts the number of code units written discarding the output.
1098template <typename T = char> class counting_buffer final : public buffer<T> {
1099 private:
1100 enum { buffer_size = 256 };
1101 T data_[buffer_size];
1102 size_t count_ = 0;
1103
1104 protected:
1105 FMT_CONSTEXPR20 void grow(size_t) override {
1106 if (this->size() != buffer_size) return;
1107 count_ += this->size();
1108 this->clear();
1109 }
1110
1111 public:
1112 counting_buffer() : buffer<T>(data_, 0, buffer_size) {}
1113
1114 auto count() -> size_t { return count_ + this->size(); }
1115};
1116
1117template <typename T>
1118using buffer_appender = conditional_t<std::is_same<T, char>::value, appender,
1119 std::back_insert_iterator<buffer<T>>>;
1120
1121// Maps an output iterator to a buffer.
1122template <typename T, typename OutputIt>
1123auto get_buffer(OutputIt out) -> iterator_buffer<OutputIt, T> {
1124 return iterator_buffer<OutputIt, T>(out);
1125}
1126template <typename T, typename Buf,
1127 FMT_ENABLE_IF(std::is_base_of<buffer<char>, Buf>::value)>
1128auto get_buffer(std::back_insert_iterator<Buf> out) -> buffer<char>& {
1129 return get_container(out);
1130}
1131
1132template <typename Buf, typename OutputIt>
1133FMT_INLINE auto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) {
1134 return buf.out();
1135}
1136template <typename T, typename OutputIt>
1137auto get_iterator(buffer<T>&, OutputIt out) -> OutputIt {
1138 return out;
1139}
1140
1141template <typename T, typename Char = char, typename Enable = void>
1142struct fallback_formatter {
1143 fallback_formatter() = delete;
1144};
1145
1146// Specifies if T has an enabled fallback_formatter specialization.
1147template <typename T, typename Char>
1148using has_fallback_formatter =
1149#ifdef FMT_DEPRECATED_OSTREAM
1150 std::is_constructible<fallback_formatter<T, Char>>;
1151#else
1152 std::false_type;
1153#endif
1154
1155struct view {};
1156
1157template <typename Char, typename T> struct named_arg : view {
1158 const Char* name;
1159 const T& value;
1160 named_arg(const Char* n, const T& v) : name(n), value(v) {}
1161};
1162
1163template <typename Char> struct named_arg_info {
1164 const Char* name;
1165 int id;
1166};
1167
1168template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
1169struct arg_data {
1170 // args_[0].named_args points to named_args_ to avoid bloating format_args.
1171 // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
1172 T args_[1 + (NUM_ARGS != 0 ? NUM_ARGS : +1)];
1173 named_arg_info<Char> named_args_[NUM_NAMED_ARGS];
1174
1175 template <typename... U>
1176 arg_data(const U&... init) : args_{T(named_args_, NUM_NAMED_ARGS), init...} {}
1177 arg_data(const arg_data& other) = delete;
1178 auto args() const -> const T* { return args_ + 1; }
1179 auto named_args() -> named_arg_info<Char>* { return named_args_; }
1180};
1181
1182template <typename T, typename Char, size_t NUM_ARGS>
1183struct arg_data<T, Char, NUM_ARGS, 0> {
1184 // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
1185 T args_[NUM_ARGS != 0 ? NUM_ARGS : +1];
1186
1187 template <typename... U>
1188 FMT_CONSTEXPR FMT_INLINE arg_data(const U&... init) : args_{init...} {}
1189 FMT_CONSTEXPR FMT_INLINE auto args() const -> const T* { return args_; }
1190 FMT_CONSTEXPR FMT_INLINE auto named_args() -> std::nullptr_t {
1191 return nullptr;
1192 }
1193};
1194
1195template <typename Char>
1196inline void init_named_args(named_arg_info<Char>*, int, int) {}
1197
1198template <typename T> struct is_named_arg : std::false_type {};
1199template <typename T> struct is_statically_named_arg : std::false_type {};
1200
1201template <typename T, typename Char>
1202struct is_named_arg<named_arg<Char, T>> : std::true_type {};
1203
1204template <typename Char, typename T, typename... Tail,
1205 FMT_ENABLE_IF(!is_named_arg<T>::value)>
1206void init_named_args(named_arg_info<Char>* named_args, int arg_count,
1207 int named_arg_count, const T&, const Tail&... args) {
1208 init_named_args(named_args, arg_count + 1, named_arg_count, args...);
1209}
1210
1211template <typename Char, typename T, typename... Tail,
1212 FMT_ENABLE_IF(is_named_arg<T>::value)>
1213void init_named_args(named_arg_info<Char>* named_args, int arg_count,
1214 int named_arg_count, const T& arg, const Tail&... args) {
1215 named_args[named_arg_count++] = {arg.name, arg_count};
1216 init_named_args(named_args, arg_count + 1, named_arg_count, args...);
1217}
1218
1219template <typename... Args>
1220FMT_CONSTEXPR FMT_INLINE void init_named_args(std::nullptr_t, int, int,
1221 const Args&...) {}
1222
1223template <bool B = false> constexpr auto count() -> size_t { return B ? 1 : 0; }
1224template <bool B1, bool B2, bool... Tail> constexpr auto count() -> size_t {
1225 return (B1 ? 1 : 0) + count<B2, Tail...>();
1226}
1227
1228template <typename... Args> constexpr auto count_named_args() -> size_t {
1229 return count<is_named_arg<Args>::value...>();
1230}
1231
1232template <typename... Args>
1233constexpr auto count_statically_named_args() -> size_t {
1234 return count<is_statically_named_arg<Args>::value...>();
1235}
1236
1237struct unformattable {};
1238struct unformattable_char : unformattable {};
1239struct unformattable_const : unformattable {};
1240struct unformattable_pointer : unformattable {};
1241
1242template <typename Char> struct string_value {
1243 const Char* data;
1244 size_t size;
1245};
1246
1247template <typename Char> struct named_arg_value {
1248 const named_arg_info<Char>* data;
1249 size_t size;
1250};
1251
1252template <typename Context> struct custom_value {
1253 using parse_context = typename Context::parse_context_type;
1254 void* value;
1255 void (*format)(void* arg, parse_context& parse_ctx, Context& ctx);
1256};
1257
1258// A formatting argument value.
1259template <typename Context> class value {
1260 public:
1261 using char_type = typename Context::char_type;
1262
1263 union {
1264 monostate no_value;
1265 int int_value;
1266 unsigned uint_value;
1267 long long long_long_value;
1268 unsigned long long ulong_long_value;
1269 int128_opt int128_value;
1270 uint128_opt uint128_value;
1271 bool bool_value;
1272 char_type char_value;
1273 float float_value;
1274 double double_value;
1275 long double long_double_value;
1276 const void* pointer;
1277 string_value<char_type> string;
1278 custom_value<Context> custom;
1279 named_arg_value<char_type> named_args;
1280 };
1281
1282 constexpr FMT_INLINE value() : no_value() {}
1283 constexpr FMT_INLINE value(int val) : int_value(val) {}
1284 constexpr FMT_INLINE value(unsigned val) : uint_value(val) {}
1285 constexpr FMT_INLINE value(long long val) : long_long_value(val) {}
1286 constexpr FMT_INLINE value(unsigned long long val) : ulong_long_value(val) {}
1287 FMT_INLINE value(int128_opt val) : int128_value(val) {}
1288 FMT_INLINE value(uint128_opt val) : uint128_value(val) {}
1289 constexpr FMT_INLINE value(float val) : float_value(val) {}
1290 constexpr FMT_INLINE value(double val) : double_value(val) {}
1291 FMT_INLINE value(long double val) : long_double_value(val) {}
1292 constexpr FMT_INLINE value(bool val) : bool_value(val) {}
1293 constexpr FMT_INLINE value(char_type val) : char_value(val) {}
1294 FMT_CONSTEXPR FMT_INLINE value(const char_type* val) {
1295 string.data = val;
1296 if (is_constant_evaluated()) string.size = {};
1297 }
1298 FMT_CONSTEXPR FMT_INLINE value(basic_string_view<char_type> val) {
1299 string.data = val.data();
1300 string.size = val.size();
1301 }
1302 FMT_INLINE value(const void* val) : pointer(val) {}
1303 FMT_INLINE value(const named_arg_info<char_type>* args, size_t size)
1304 : named_args{args, size} {}
1305
1306 template <typename T> FMT_CONSTEXPR FMT_INLINE value(T& val) {
1307 using value_type = remove_cvref_t<T>;
1308 custom.value = const_cast<value_type*>(&val);
1309 // Get the formatter type through the context to allow different contexts
1310 // have different extension points, e.g. `formatter<T>` for `format` and
1311 // `printf_formatter<T>` for `printf`.
1312 custom.format = format_custom_arg<
1313 value_type,
1314 conditional_t<has_formatter<value_type, Context>::value,
1315 typename Context::template formatter_type<value_type>,
1316 fallback_formatter<value_type, char_type>>>;
1317 }
1318 value(unformattable);
1319 value(unformattable_char);
1320 value(unformattable_const);
1321 value(unformattable_pointer);
1322
1323 private:
1324 // Formats an argument of a custom type, such as a user-defined class.
1325 template <typename T, typename Formatter>
1326 static void format_custom_arg(void* arg,
1327 typename Context::parse_context_type& parse_ctx,
1328 Context& ctx) {
1329 auto f = Formatter();
1330 parse_ctx.advance_to(f.parse(parse_ctx));
1331 using qualified_type =
1332 conditional_t<has_const_formatter<T, Context>(), const T, T>;
1333 ctx.advance_to(f.format(*static_cast<qualified_type*>(arg), ctx));
1334 }
1335};
1336
1337template <typename Context, typename T>
1338FMT_CONSTEXPR auto make_arg(T&& value) -> basic_format_arg<Context>;
1339
1340// To minimize the number of types we need to deal with, long is translated
1341// either to int or to long long depending on its size.
1342enum { long_short = sizeof(long) == sizeof(int) };
1343using long_type = conditional_t<long_short, int, long long>;
1344using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
1345
1346#ifdef __cpp_lib_byte
1347inline auto format_as(std::byte b) -> unsigned char {
1348 return static_cast<unsigned char>(b);
1349}
1350#endif
1351
1352template <typename T> struct has_format_as {
1353 template <typename U, typename V = decltype(format_as(U())),
1354 FMT_ENABLE_IF(std::is_enum<U>::value&& std::is_integral<V>::value)>
1355 static auto check(U*) -> std::true_type;
1356 static auto check(...) -> std::false_type;
1357
1358 enum { value = decltype(check(static_cast<T*>(nullptr)))::value };
1359};
1360
1361// Maps formatting arguments to core types.
1362// arg_mapper reports errors by returning unformattable instead of using
1363// static_assert because it's used in the is_formattable trait.
1364template <typename Context> struct arg_mapper {
1365 using char_type = typename Context::char_type;
1366
1367 FMT_CONSTEXPR FMT_INLINE auto map(signed char val) -> int { return val; }
1368 FMT_CONSTEXPR FMT_INLINE auto map(unsigned char val) -> unsigned {
1369 return val;
1370 }
1371 FMT_CONSTEXPR FMT_INLINE auto map(short val) -> int { return val; }
1372 FMT_CONSTEXPR FMT_INLINE auto map(unsigned short val) -> unsigned {
1373 return val;
1374 }
1375 FMT_CONSTEXPR FMT_INLINE auto map(int val) -> int { return val; }
1376 FMT_CONSTEXPR FMT_INLINE auto map(unsigned val) -> unsigned { return val; }
1377 FMT_CONSTEXPR FMT_INLINE auto map(long val) -> long_type { return val; }
1378 FMT_CONSTEXPR FMT_INLINE auto map(unsigned long val) -> ulong_type {
1379 return val;
1380 }
1381 FMT_CONSTEXPR FMT_INLINE auto map(long long val) -> long long { return val; }
1382 FMT_CONSTEXPR FMT_INLINE auto map(unsigned long long val)
1383 -> unsigned long long {
1384 return val;
1385 }
1386 FMT_CONSTEXPR FMT_INLINE auto map(int128_opt val) -> int128_opt {
1387 return val;
1388 }
1389 FMT_CONSTEXPR FMT_INLINE auto map(uint128_opt val) -> uint128_opt {
1390 return val;
1391 }
1392 FMT_CONSTEXPR FMT_INLINE auto map(bool val) -> bool { return val; }
1393
1394 template <typename T, FMT_ENABLE_IF(std::is_same<T, char>::value ||
1395 std::is_same<T, char_type>::value)>
1396 FMT_CONSTEXPR FMT_INLINE auto map(T val) -> char_type {
1397 return val;
1398 }
1399 template <typename T, enable_if_t<(std::is_same<T, wchar_t>::value ||
1400#ifdef __cpp_char8_t
1401 std::is_same<T, char8_t>::value ||
1402#endif
1403 std::is_same<T, char16_t>::value ||
1404 std::is_same<T, char32_t>::value) &&
1405 !std::is_same<T, char_type>::value,
1406 int> = 0>
1407 FMT_CONSTEXPR FMT_INLINE auto map(T) -> unformattable_char {
1408 return {};
1409 }
1410
1411 FMT_CONSTEXPR FMT_INLINE auto map(float val) -> float { return val; }
1412 FMT_CONSTEXPR FMT_INLINE auto map(double val) -> double { return val; }
1413 FMT_CONSTEXPR FMT_INLINE auto map(long double val) -> long double {
1414 return val;
1415 }
1416
1417 FMT_CONSTEXPR FMT_INLINE auto map(char_type* val) -> const char_type* {
1418 return val;
1419 }
1420 FMT_CONSTEXPR FMT_INLINE auto map(const char_type* val) -> const char_type* {
1421 return val;
1422 }
1423 template <typename T,
1424 FMT_ENABLE_IF(is_string<T>::value && !std::is_pointer<T>::value &&
1425 std::is_same<char_type, char_t<T>>::value)>
1426 FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
1427 -> basic_string_view<char_type> {
1428 return to_string_view(val);
1429 }
1430 template <typename T,
1431 FMT_ENABLE_IF(is_string<T>::value && !std::is_pointer<T>::value &&
1432 !std::is_same<char_type, char_t<T>>::value)>
1433 FMT_CONSTEXPR FMT_INLINE auto map(const T&) -> unformattable_char {
1434 return {};
1435 }
1436 template <typename T,
1437 FMT_ENABLE_IF(
1438 std::is_convertible<T, basic_string_view<char_type>>::value &&
1439 !is_string<T>::value && !has_formatter<T, Context>::value &&
1440 !has_fallback_formatter<T, char_type>::value)>
1441 FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
1442 -> basic_string_view<char_type> {
1443 return basic_string_view<char_type>(val);
1444 }
1445 template <typename T,
1446 FMT_ENABLE_IF(
1447 std::is_convertible<T, std_string_view<char_type>>::value &&
1448 !std::is_convertible<T, basic_string_view<char_type>>::value &&
1449 !is_string<T>::value && !has_formatter<T, Context>::value &&
1450 !has_fallback_formatter<T, char_type>::value)>
1451 FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
1452 -> basic_string_view<char_type> {
1453 return std_string_view<char_type>(val);
1454 }
1455
1456 FMT_CONSTEXPR FMT_INLINE auto map(void* val) -> const void* { return val; }
1457 FMT_CONSTEXPR FMT_INLINE auto map(const void* val) -> const void* {
1458 return val;
1459 }
1460 FMT_CONSTEXPR FMT_INLINE auto map(std::nullptr_t val) -> const void* {
1461 return val;
1462 }
1463
1464 // We use SFINAE instead of a const T* parameter to avoid conflicting with
1465 // the C array overload.
1466 template <
1467 typename T,
1468 FMT_ENABLE_IF(
1469 std::is_pointer<T>::value || std::is_member_pointer<T>::value ||
1470 std::is_function<typename std::remove_pointer<T>::type>::value ||
1471 (std::is_convertible<const T&, const void*>::value &&
1472 !std::is_convertible<const T&, const char_type*>::value &&
1473 !has_formatter<T, Context>::value))>
1474 FMT_CONSTEXPR auto map(const T&) -> unformattable_pointer {
1475 return {};
1476 }
1477
1478 template <typename T, std::size_t N,
1479 FMT_ENABLE_IF(!std::is_same<T, wchar_t>::value)>
1480 FMT_CONSTEXPR FMT_INLINE auto map(const T (&values)[N]) -> const T (&)[N] {
1481 return values;
1482 }
1483
1484 template <typename T,
1485 FMT_ENABLE_IF(
1486 std::is_enum<T>::value&& std::is_convertible<T, int>::value &&
1487 !has_format_as<T>::value && !has_formatter<T, Context>::value &&
1488 !has_fallback_formatter<T, char_type>::value)>
1489 FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
1490 -> decltype(std::declval<arg_mapper>().map(
1491 static_cast<underlying_t<T>>(val))) {
1492 return map(static_cast<underlying_t<T>>(val));
1493 }
1494
1495 template <typename T, FMT_ENABLE_IF(has_format_as<T>::value &&
1496 !has_formatter<T, Context>::value)>
1497 FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
1498 -> decltype(std::declval<arg_mapper>().map(format_as(T()))) {
1499 return map(format_as(val));
1500 }
1501
1502 template <typename T, typename U = remove_cvref_t<T>>
1503 struct formattable
1504 : bool_constant<has_const_formatter<U, Context>() ||
1505 !std::is_const<remove_reference_t<T>>::value ||
1506 has_fallback_formatter<U, char_type>::value> {};
1507
1508#if (FMT_MSC_VERSION != 0 && FMT_MSC_VERSION < 1910) || \
1509 FMT_ICC_VERSION != 0 || defined(__NVCC__)
1510 // Workaround a bug in MSVC and Intel (Issue 2746).
1511 template <typename T> FMT_CONSTEXPR FMT_INLINE auto do_map(T&& val) -> T& {
1512 return val;
1513 }
1514#else
1515 template <typename T, FMT_ENABLE_IF(formattable<T>::value)>
1516 FMT_CONSTEXPR FMT_INLINE auto do_map(T&& val) -> T& {
1517 return val;
1518 }
1519 template <typename T, FMT_ENABLE_IF(!formattable<T>::value)>
1520 FMT_CONSTEXPR FMT_INLINE auto do_map(T&&) -> unformattable_const {
1521 return {};
1522 }
1523#endif
1524
1525 template <typename T, typename U = remove_cvref_t<T>,
1526 FMT_ENABLE_IF(!is_string<U>::value && !is_char<U>::value &&
1527 !std::is_array<U>::value &&
1528 !std::is_pointer<U>::value &&
1529 !has_format_as<U>::value &&
1530 (has_formatter<U, Context>::value ||
1531 has_fallback_formatter<U, char_type>::value))>
1532 FMT_CONSTEXPR FMT_INLINE auto map(T&& val)
1533 -> decltype(this->do_map(std::forward<T>(val))) {
1534 return do_map(std::forward<T>(val));
1535 }
1536
1537 template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
1538 FMT_CONSTEXPR FMT_INLINE auto map(const T& named_arg)
1539 -> decltype(std::declval<arg_mapper>().map(named_arg.value)) {
1540 return map(named_arg.value);
1541 }
1542
1543 auto map(...) -> unformattable { return {}; }
1544};
1545
1546// A type constant after applying arg_mapper<Context>.
1547template <typename T, typename Context>
1548using mapped_type_constant =
1549 type_constant<decltype(arg_mapper<Context>().map(std::declval<const T&>())),
1550 typename Context::char_type>;
1551
1552enum { packed_arg_bits = 4 };
1553// Maximum number of arguments with packed types.
1554enum { max_packed_args = 62 / packed_arg_bits };
1555enum : unsigned long long { is_unpacked_bit = 1ULL << 63 };
1556enum : unsigned long long { has_named_args_bit = 1ULL << 62 };
1557
1558FMT_END_DETAIL_NAMESPACE
1559
1560// An output iterator that appends to a buffer.
1561// It is used to reduce symbol sizes for the common case.
1562class appender : public std::back_insert_iterator<detail::buffer<char>> {
1563 using base = std::back_insert_iterator<detail::buffer<char>>;
1564
1565 public:
1566 using std::back_insert_iterator<detail::buffer<char>>::back_insert_iterator;
1567 appender(base it) noexcept : base(it) {}
1568 FMT_UNCHECKED_ITERATOR(appender);
1569
1570 auto operator++() noexcept -> appender& { return *this; }
1571 auto operator++(int) noexcept -> appender { return *this; }
1572};
1573
1574// A formatting argument. It is a trivially copyable/constructible type to
1575// allow storage in basic_memory_buffer.
1576template <typename Context> class basic_format_arg {
1577 private:
1578 detail::value<Context> value_;
1579 detail::type type_;
1580
1581 template <typename ContextType, typename T>
1582 friend FMT_CONSTEXPR auto detail::make_arg(T&& value)
1583 -> basic_format_arg<ContextType>;
1584
1585 template <typename Visitor, typename Ctx>
1586 friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis,
1587 const basic_format_arg<Ctx>& arg)
1588 -> decltype(vis(0));
1589
1590 friend class basic_format_args<Context>;
1591 friend class dynamic_format_arg_store<Context>;
1592
1593 using char_type = typename Context::char_type;
1594
1595 template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
1596 friend struct detail::arg_data;
1597
1598 basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)
1599 : value_(args, size) {}
1600
1601 public:
1602 class handle {
1603 public:
1604 explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}
1605
1606 void format(typename Context::parse_context_type& parse_ctx,
1607 Context& ctx) const {
1608 custom_.format(custom_.value, parse_ctx, ctx);
1609 }
1610
1611 private:
1612 detail::custom_value<Context> custom_;
1613 };
1614
1615 constexpr basic_format_arg() : type_(detail::type::none_type) {}
1616
1617 constexpr explicit operator bool() const noexcept {
1618 return type_ != detail::type::none_type;
1619 }
1620
1621 auto type() const -> detail::type { return type_; }
1622
1623 auto is_integral() const -> bool { return detail::is_integral_type(type_); }
1624 auto is_arithmetic() const -> bool {
1625 return detail::is_arithmetic_type(type_);
1626 }
1627};
1628
1629/**
1630 \rst
1631 Visits an argument dispatching to the appropriate visit method based on
1632 the argument type. For example, if the argument type is ``double`` then
1633 ``vis(value)`` will be called with the value of type ``double``.
1634 \endrst
1635 */
1636template <typename Visitor, typename Context>
1637FMT_CONSTEXPR FMT_INLINE auto visit_format_arg(
1638 Visitor&& vis, const basic_format_arg<Context>& arg) -> decltype(vis(0)) {
1639 switch (arg.type_) {
1640 case detail::type::none_type:
1641 break;
1642 case detail::type::int_type:
1643 return vis(arg.value_.int_value);
1644 case detail::type::uint_type:
1645 return vis(arg.value_.uint_value);
1646 case detail::type::long_long_type:
1647 return vis(arg.value_.long_long_value);
1648 case detail::type::ulong_long_type:
1649 return vis(arg.value_.ulong_long_value);
1650 case detail::type::int128_type:
1651 return vis(detail::convert_for_visit(arg.value_.int128_value));
1652 case detail::type::uint128_type:
1653 return vis(detail::convert_for_visit(arg.value_.uint128_value));
1654 case detail::type::bool_type:
1655 return vis(arg.value_.bool_value);
1656 case detail::type::char_type:
1657 return vis(arg.value_.char_value);
1658 case detail::type::float_type:
1659 return vis(arg.value_.float_value);
1660 case detail::type::double_type:
1661 return vis(arg.value_.double_value);
1662 case detail::type::long_double_type:
1663 return vis(arg.value_.long_double_value);
1664 case detail::type::cstring_type:
1665 return vis(arg.value_.string.data);
1666 case detail::type::string_type:
1667 using sv = basic_string_view<typename Context::char_type>;
1668 return vis(sv(arg.value_.string.data, arg.value_.string.size));
1669 case detail::type::pointer_type:
1670 return vis(arg.value_.pointer);
1671 case detail::type::custom_type:
1672 return vis(typename basic_format_arg<Context>::handle(arg.value_.custom));
1673 }
1674 return vis(monostate());
1675}
1676
1677FMT_BEGIN_DETAIL_NAMESPACE
1678
1679template <typename Char, typename InputIt>
1680auto copy_str(InputIt begin, InputIt end, appender out) -> appender {
1681 get_container(out).append(begin, end);
1682 return out;
1683}
1684
1685template <typename Char, typename R, typename OutputIt>
1686FMT_CONSTEXPR auto copy_str(R&& rng, OutputIt out) -> OutputIt {
1687 return detail::copy_str<Char>(rng.begin(), rng.end(), out);
1688}
1689
1690#if FMT_GCC_VERSION && FMT_GCC_VERSION < 500
1691// A workaround for gcc 4.8 to make void_t work in a SFINAE context.
1692template <typename... Ts> struct void_t_impl { using type = void; };
1693template <typename... Ts>
1694using void_t = typename detail::void_t_impl<Ts...>::type;
1695#else
1696template <typename...> using void_t = void;
1697#endif
1698
1699template <typename It, typename T, typename Enable = void>
1700struct is_output_iterator : std::false_type {};
1701
1702template <typename It, typename T>
1703struct is_output_iterator<
1704 It, T,
1705 void_t<typename std::iterator_traits<It>::iterator_category,
1706 decltype(*std::declval<It>() = std::declval<T>())>>
1707 : std::true_type {};
1708
1709template <typename OutputIt>
1710struct is_back_insert_iterator : std::false_type {};
1711template <typename Container>
1712struct is_back_insert_iterator<std::back_insert_iterator<Container>>
1713 : std::true_type {};
1714
1715template <typename OutputIt>
1716struct is_contiguous_back_insert_iterator : std::false_type {};
1717template <typename Container>
1718struct is_contiguous_back_insert_iterator<std::back_insert_iterator<Container>>
1719 : is_contiguous<Container> {};
1720template <>
1721struct is_contiguous_back_insert_iterator<appender> : std::true_type {};
1722
1723// A type-erased reference to an std::locale to avoid a heavy <locale> include.
1724class locale_ref {
1725 private:
1726 const void* locale_; // A type-erased pointer to std::locale.
1727
1728 public:
1729 constexpr FMT_INLINE locale_ref() : locale_(nullptr) {}
1730 template <typename Locale> explicit locale_ref(const Locale& loc);
1731
1732 explicit operator bool() const noexcept { return locale_ != nullptr; }
1733
1734 template <typename Locale> auto get() const -> Locale;
1735};
1736
1737template <typename> constexpr auto encode_types() -> unsigned long long {
1738 return 0;
1739}
1740
1741template <typename Context, typename Arg, typename... Args>
1742constexpr auto encode_types() -> unsigned long long {
1743 return static_cast<unsigned>(mapped_type_constant<Arg, Context>::value) |
1744 (encode_types<Context, Args...>() << packed_arg_bits);
1745}
1746
1747template <typename Context, typename T>
1748FMT_CONSTEXPR FMT_INLINE auto make_value(T&& val) -> value<Context> {
1749 const auto& arg = arg_mapper<Context>().map(FMT_FORWARD(val));
1750
1751 constexpr bool formattable_char =
1752 !std::is_same<decltype(arg), const unformattable_char&>::value;
1753 static_assert(formattable_char, "Mixing character types is disallowed.");
1754
1755 constexpr bool formattable_const =
1756 !std::is_same<decltype(arg), const unformattable_const&>::value;
1757 static_assert(formattable_const, "Cannot format a const argument.");
1758
1759 // Formatting of arbitrary pointers is disallowed. If you want to output
1760 // a pointer cast it to "void *" or "const void *". In particular, this
1761 // forbids formatting of "[const] volatile char *" which is printed as bool
1762 // by iostreams.
1763 constexpr bool formattable_pointer =
1764 !std::is_same<decltype(arg), const unformattable_pointer&>::value;
1765 static_assert(formattable_pointer,
1766 "Formatting of non-void pointers is disallowed.");
1767
1768 constexpr bool formattable =
1769 !std::is_same<decltype(arg), const unformattable&>::value;
1770 static_assert(
1771 formattable,
1772 "Cannot format an argument. To make type T formattable provide a "
1773 "formatter<T> specialization: https://fmt.dev/latest/api.html#udt");
1774 return {arg};
1775}
1776
1777template <typename Context, typename T>
1778FMT_CONSTEXPR auto make_arg(T&& value) -> basic_format_arg<Context> {
1779 basic_format_arg<Context> arg;
1780 arg.type_ = mapped_type_constant<T, Context>::value;
1781 arg.value_ = make_value<Context>(value);
1782 return arg;
1783}
1784
1785// The type template parameter is there to avoid an ODR violation when using
1786// a fallback formatter in one translation unit and an implicit conversion in
1787// another (not recommended).
1788template <bool IS_PACKED, typename Context, type, typename T,
1789 FMT_ENABLE_IF(IS_PACKED)>
1790FMT_CONSTEXPR FMT_INLINE auto make_arg(T&& val) -> value<Context> {
1791 return make_value<Context>(val);
1792}
1793
1794template <bool IS_PACKED, typename Context, type, typename T,
1795 FMT_ENABLE_IF(!IS_PACKED)>
1796FMT_CONSTEXPR inline auto make_arg(T&& value) -> basic_format_arg<Context> {
1797 return make_arg<Context>(value);
1798}
1799FMT_END_DETAIL_NAMESPACE
1800
1801// Formatting context.
1802template <typename OutputIt, typename Char> class basic_format_context {
1803 public:
1804 /** The character type for the output. */
1805 using char_type = Char;
1806
1807 private:
1808 OutputIt out_;
1809 basic_format_args<basic_format_context> args_;
1810 detail::locale_ref loc_;
1811
1812 public:
1813 using iterator = OutputIt;
1814 using format_arg = basic_format_arg<basic_format_context>;
1815 using parse_context_type = basic_format_parse_context<Char>;
1816 template <typename T> using formatter_type = formatter<T, char_type>;
1817
1818 basic_format_context(basic_format_context&&) = default;
1819 basic_format_context(const basic_format_context&) = delete;
1820 void operator=(const basic_format_context&) = delete;
1821 /**
1822 Constructs a ``basic_format_context`` object. References to the arguments are
1823 stored in the object so make sure they have appropriate lifetimes.
1824 */
1825 constexpr basic_format_context(
1826 OutputIt out, basic_format_args<basic_format_context> ctx_args,
1827 detail::locale_ref loc = detail::locale_ref())
1828 : out_(out), args_(ctx_args), loc_(loc) {}
1829
1830 constexpr auto arg(int id) const -> format_arg { return args_.get(id); }
1831 FMT_CONSTEXPR auto arg(basic_string_view<char_type> name) -> format_arg {
1832 return args_.get(name);
1833 }
1834 FMT_CONSTEXPR auto arg_id(basic_string_view<char_type> name) -> int {
1835 return args_.get_id(name);
1836 }
1837 auto args() const -> const basic_format_args<basic_format_context>& {
1838 return args_;
1839 }
1840
1841 FMT_CONSTEXPR auto error_handler() -> detail::error_handler { return {}; }
1842 void on_error(const char* message) { error_handler().on_error(message); }
1843
1844 // Returns an iterator to the beginning of the output range.
1845 FMT_CONSTEXPR auto out() -> iterator { return out_; }
1846
1847 // Advances the begin iterator to ``it``.
1848 void advance_to(iterator it) {
1849 if (!detail::is_back_insert_iterator<iterator>()) out_ = it;
1850 }
1851
1852 FMT_CONSTEXPR auto locale() -> detail::locale_ref { return loc_; }
1853};
1854
1855template <typename Char>
1856using buffer_context =
1857 basic_format_context<detail::buffer_appender<Char>, Char>;
1858using format_context = buffer_context<char>;
1859
1860// Workaround an alias issue: https://stackoverflow.com/q/62767544/471164.
1861#define FMT_BUFFER_CONTEXT(Char) \
1862 basic_format_context<detail::buffer_appender<Char>, Char>
1863
1864template <typename T, typename Char = char>
1865using is_formattable = bool_constant<
1866 !std::is_base_of<detail::unformattable,
1867 decltype(detail::arg_mapper<buffer_context<Char>>().map(
1868 std::declval<T>()))>::value &&
1869 !detail::has_fallback_formatter<T, Char>::value>;
1870
1871/**
1872 \rst
1873 An array of references to arguments. It can be implicitly converted into
1874 `~fmt::basic_format_args` for passing into type-erased formatting functions
1875 such as `~fmt::vformat`.
1876 \endrst
1877 */
1878template <typename Context, typename... Args>
1879class format_arg_store
1880#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
1881 // Workaround a GCC template argument substitution bug.
1882 : public basic_format_args<Context>
1883#endif
1884{
1885 private:
1886 static const size_t num_args = sizeof...(Args);
1887 static const size_t num_named_args = detail::count_named_args<Args...>();
1888 static const bool is_packed = num_args <= detail::max_packed_args;
1889
1890 using value_type = conditional_t<is_packed, detail::value<Context>,
1891 basic_format_arg<Context>>;
1892
1893 detail::arg_data<value_type, typename Context::char_type, num_args,
1894 num_named_args>
1895 data_;
1896
1897 friend class basic_format_args<Context>;
1898
1899 static constexpr unsigned long long desc =
1900 (is_packed ? detail::encode_types<Context, Args...>()
1901 : detail::is_unpacked_bit | num_args) |
1902 (num_named_args != 0
1903 ? static_cast<unsigned long long>(detail::has_named_args_bit)
1904 : 0);
1905
1906 public:
1907 template <typename... T>
1908 FMT_CONSTEXPR FMT_INLINE format_arg_store(T&&... args)
1909 :
1910#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
1911 basic_format_args<Context>(*this),
1912#endif
1913 data_{detail::make_arg<
1914 is_packed, Context,
1915 detail::mapped_type_constant<remove_cvref_t<T>, Context>::value>(
1916 FMT_FORWARD(args))...} {
1917 detail::init_named_args(data_.named_args(), 0, 0, args...);
1918 }
1919};
1920
1921/**
1922 \rst
1923 Constructs a `~fmt::format_arg_store` object that contains references to
1924 arguments and can be implicitly converted to `~fmt::format_args`. `Context`
1925 can be omitted in which case it defaults to `~fmt::context`.
1926 See `~fmt::arg` for lifetime considerations.
1927 \endrst
1928 */
1929template <typename Context = format_context, typename... Args>
1930constexpr auto make_format_args(Args&&... args)
1931 -> format_arg_store<Context, remove_cvref_t<Args>...> {
1932 return {FMT_FORWARD(args)...};
1933}
1934
1935/**
1936 \rst
1937 Returns a named argument to be used in a formatting function.
1938 It should only be used in a call to a formatting function or
1939 `dynamic_format_arg_store::push_back`.
1940
1941 **Example**::
1942
1943 fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23));
1944 \endrst
1945 */
1946template <typename Char, typename T>
1947inline auto arg(const Char* name, const T& arg) -> detail::named_arg<Char, T> {
1948 static_assert(!detail::is_named_arg<T>(), "nested named arguments");
1949 return {name, arg};
1950}
1951
1952/**
1953 \rst
1954 A view of a collection of formatting arguments. To avoid lifetime issues it
1955 should only be used as a parameter type in type-erased functions such as
1956 ``vformat``::
1957
1958 void vlog(string_view format_str, format_args args); // OK
1959 format_args args = make_format_args(42); // Error: dangling reference
1960 \endrst
1961 */
1962template <typename Context> class basic_format_args {
1963 public:
1964 using size_type = int;
1965 using format_arg = basic_format_arg<Context>;
1966
1967 private:
1968 // A descriptor that contains information about formatting arguments.
1969 // If the number of arguments is less or equal to max_packed_args then
1970 // argument types are passed in the descriptor. This reduces binary code size
1971 // per formatting function call.
1972 unsigned long long desc_;
1973 union {
1974 // If is_packed() returns true then argument values are stored in values_;
1975 // otherwise they are stored in args_. This is done to improve cache
1976 // locality and reduce compiled code size since storing larger objects
1977 // may require more code (at least on x86-64) even if the same amount of
1978 // data is actually copied to stack. It saves ~10% on the bloat test.
1979 const detail::value<Context>* values_;
1980 const format_arg* args_;
1981 };
1982
1983 constexpr auto is_packed() const -> bool {
1984 return (desc_ & detail::is_unpacked_bit) == 0;
1985 }
1986 auto has_named_args() const -> bool {
1987 return (desc_ & detail::has_named_args_bit) != 0;
1988 }
1989
1990 FMT_CONSTEXPR auto type(int index) const -> detail::type {
1991 int shift = index * detail::packed_arg_bits;
1992 unsigned int mask = (1 << detail::packed_arg_bits) - 1;
1993 return static_cast<detail::type>((desc_ >> shift) & mask);
1994 }
1995
1996 constexpr FMT_INLINE basic_format_args(unsigned long long desc,
1997 const detail::value<Context>* values)
1998 : desc_(desc), values_(values) {}
1999 constexpr basic_format_args(unsigned long long desc, const format_arg* args)
2000 : desc_(desc), args_(args) {}
2001
2002 public:
2003 constexpr basic_format_args() : desc_(0), args_(nullptr) {}
2004
2005 /**
2006 \rst
2007 Constructs a `basic_format_args` object from `~fmt::format_arg_store`.
2008 \endrst
2009 */
2010 template <typename... Args>
2011 constexpr FMT_INLINE basic_format_args(
2012 const format_arg_store<Context, Args...>& store)
2013 : basic_format_args(format_arg_store<Context, Args...>::desc,
2014 store.data_.args()) {}
2015
2016 /**
2017 \rst
2018 Constructs a `basic_format_args` object from
2019 `~fmt::dynamic_format_arg_store`.
2020 \endrst
2021 */
2022 constexpr FMT_INLINE basic_format_args(
2023 const dynamic_format_arg_store<Context>& store)
2024 : basic_format_args(store.get_types(), store.data()) {}
2025
2026 /**
2027 \rst
2028 Constructs a `basic_format_args` object from a dynamic set of arguments.
2029 \endrst
2030 */
2031 constexpr basic_format_args(const format_arg* args, int count)
2032 : basic_format_args(detail::is_unpacked_bit | detail::to_unsigned(count),
2033 args) {}
2034
2035 /** Returns the argument with the specified id. */
2036 FMT_CONSTEXPR auto get(int id) const -> format_arg {
2037 format_arg arg;
2038 if (!is_packed()) {
2039 if (id < max_size()) arg = args_[id];
2040 return arg;
2041 }
2042 if (id >= detail::max_packed_args) return arg;
2043 arg.type_ = type(id);
2044 if (arg.type_ == detail::type::none_type) return arg;
2045 arg.value_ = values_[id];
2046 return arg;
2047 }
2048
2049 template <typename Char>
2050 auto get(basic_string_view<Char> name) const -> format_arg {
2051 int id = get_id(name);
2052 return id >= 0 ? get(id) : format_arg();
2053 }
2054
2055 template <typename Char>
2056 auto get_id(basic_string_view<Char> name) const -> int {
2057 if (!has_named_args()) return -1;
2058 const auto& named_args =
2059 (is_packed() ? values_[-1] : args_[-1].value_).named_args;
2060 for (size_t i = 0; i < named_args.size; ++i) {
2061 if (named_args.data[i].name == name) return named_args.data[i].id;
2062 }
2063 return -1;
2064 }
2065
2066 auto max_size() const -> int {
2067 unsigned long long max_packed = detail::max_packed_args;
2068 return static_cast<int>(is_packed() ? max_packed
2069 : desc_ & ~detail::is_unpacked_bit);
2070 }
2071};
2072
2073/** An alias to ``basic_format_args<format_context>``. */
2074// A separate type would result in shorter symbols but break ABI compatibility
2075// between clang and gcc on ARM (#1919).
2076using format_args = basic_format_args<format_context>;
2077
2078// We cannot use enum classes as bit fields because of a gcc bug, so we put them
2079// in namespaces instead (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414).
2080// Additionally, if an underlying type is specified, older gcc incorrectly warns
2081// that the type is too small. Both bugs are fixed in gcc 9.3.
2082#if FMT_GCC_VERSION && FMT_GCC_VERSION < 903
2083# define FMT_ENUM_UNDERLYING_TYPE(type)
2084#else
2085# define FMT_ENUM_UNDERLYING_TYPE(type) : type
2086#endif
2087namespace align {
2088enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, left, right, center,
2089 numeric};
2090}
2091using align_t = align::type;
2092namespace sign {
2093enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, minus, plus, space};
2094}
2095using sign_t = sign::type;
2096
2097FMT_BEGIN_DETAIL_NAMESPACE
2098
2099// Workaround an array initialization issue in gcc 4.8.
2100template <typename Char> struct fill_t {
2101 private:
2102 enum { max_size = 4 };
2103 Char data_[max_size] = {Char(' '), Char(0), Char(0), Char(0)};
2104 unsigned char size_ = 1;
2105
2106 public:
2107 FMT_CONSTEXPR void operator=(basic_string_view<Char> s) {
2108 auto size = s.size();
2109 if (size > max_size) return throw_format_error("invalid fill");
2110 for (size_t i = 0; i < size; ++i) data_[i] = s[i];
2111 size_ = static_cast<unsigned char>(size);
2112 }
2113
2114 constexpr auto size() const -> size_t { return size_; }
2115 constexpr auto data() const -> const Char* { return data_; }
2116
2117 FMT_CONSTEXPR auto operator[](size_t index) -> Char& { return data_[index]; }
2118 FMT_CONSTEXPR auto operator[](size_t index) const -> const Char& {
2119 return data_[index];
2120 }
2121};
2122FMT_END_DETAIL_NAMESPACE
2123
2124enum class presentation_type : unsigned char {
2125 none,
2126 // Integer types should go first,
2127 dec, // 'd'
2128 oct, // 'o'
2129 hex_lower, // 'x'
2130 hex_upper, // 'X'
2131 bin_lower, // 'b'
2132 bin_upper, // 'B'
2133 hexfloat_lower, // 'a'
2134 hexfloat_upper, // 'A'
2135 exp_lower, // 'e'
2136 exp_upper, // 'E'
2137 fixed_lower, // 'f'
2138 fixed_upper, // 'F'
2139 general_lower, // 'g'
2140 general_upper, // 'G'
2141 chr, // 'c'
2142 string, // 's'
2143 pointer, // 'p'
2144 debug // '?'
2145};
2146
2147// Format specifiers for built-in and string types.
2148template <typename Char> struct basic_format_specs {
2149 int width;
2150 int precision;
2151 presentation_type type;
2152 align_t align : 4;
2153 sign_t sign : 3;
2154 bool alt : 1; // Alternate form ('#').
2155 bool localized : 1;
2156 detail::fill_t<Char> fill;
2157
2158 constexpr basic_format_specs()
2159 : width(0),
2160 precision(-1),
2161 type(presentation_type::none),
2162 align(align::none),
2163 sign(sign::none),
2164 alt(false),
2165 localized(false) {}
2166};
2167
2168using format_specs = basic_format_specs<char>;
2169
2170FMT_BEGIN_DETAIL_NAMESPACE
2171
2172enum class arg_id_kind { none, index, name };
2173
2174// An argument reference.
2175template <typename Char> struct arg_ref {
2176 FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {}
2177
2178 FMT_CONSTEXPR explicit arg_ref(int index)
2179 : kind(arg_id_kind::index), val(index) {}
2180 FMT_CONSTEXPR explicit arg_ref(basic_string_view<Char> name)
2181 : kind(arg_id_kind::name), val(name) {}
2182
2183 FMT_CONSTEXPR auto operator=(int idx) -> arg_ref& {
2184 kind = arg_id_kind::index;
2185 val.index = idx;
2186 return *this;
2187 }
2188
2189 arg_id_kind kind;
2190 union value {
2191 FMT_CONSTEXPR value(int id = 0) : index{id} {}
2192 FMT_CONSTEXPR value(basic_string_view<Char> n) : name(n) {}
2193
2194 int index;
2195 basic_string_view<Char> name;
2196 } val;
2197};
2198
2199// Format specifiers with width and precision resolved at formatting rather
2200// than parsing time to allow re-using the same parsed specifiers with
2201// different sets of arguments (precompilation of format strings).
2202template <typename Char>
2203struct dynamic_format_specs : basic_format_specs<Char> {
2204 arg_ref<Char> width_ref;
2205 arg_ref<Char> precision_ref;
2206};
2207
2208struct auto_id {};
2209
2210// A format specifier handler that sets fields in basic_format_specs.
2211template <typename Char> class specs_setter {
2212 protected:
2213 basic_format_specs<Char>& specs_;
2214
2215 public:
2216 explicit FMT_CONSTEXPR specs_setter(basic_format_specs<Char>& specs)
2217 : specs_(specs) {}
2218
2219 FMT_CONSTEXPR specs_setter(const specs_setter& other)
2220 : specs_(other.specs_) {}
2221
2222 FMT_CONSTEXPR void on_align(align_t align) { specs_.align = align; }
2223 FMT_CONSTEXPR void on_fill(basic_string_view<Char> fill) {
2224 specs_.fill = fill;
2225 }
2226 FMT_CONSTEXPR void on_sign(sign_t s) { specs_.sign = s; }
2227 FMT_CONSTEXPR void on_hash() { specs_.alt = true; }
2228 FMT_CONSTEXPR void on_localized() { specs_.localized = true; }
2229
2230 FMT_CONSTEXPR void on_zero() {
2231 if (specs_.align == align::none) specs_.align = align::numeric;
2232 specs_.fill[0] = Char('0');
2233 }
2234
2235 FMT_CONSTEXPR void on_width(int width) { specs_.width = width; }
2236 FMT_CONSTEXPR void on_precision(int precision) {
2237 specs_.precision = precision;
2238 }
2239 FMT_CONSTEXPR void end_precision() {}
2240
2241 FMT_CONSTEXPR void on_type(presentation_type type) { specs_.type = type; }
2242};
2243
2244// Format spec handler that saves references to arguments representing dynamic
2245// width and precision to be resolved at formatting time.
2246template <typename ParseContext>
2247class dynamic_specs_handler
2248 : public specs_setter<typename ParseContext::char_type> {
2249 public:
2250 using char_type = typename ParseContext::char_type;
2251
2252 FMT_CONSTEXPR dynamic_specs_handler(dynamic_format_specs<char_type>& specs,
2253 ParseContext& ctx)
2254 : specs_setter<char_type>(specs), specs_(specs), context_(ctx) {}
2255
2256 FMT_CONSTEXPR dynamic_specs_handler(const dynamic_specs_handler& other)
2257 : specs_setter<char_type>(other),
2258 specs_(other.specs_),
2259 context_(other.context_) {}
2260
2261 template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
2262 specs_.width_ref = make_arg_ref(arg_id);
2263 }
2264
2265 template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
2266 specs_.precision_ref = make_arg_ref(arg_id);
2267 }
2268
2269 FMT_CONSTEXPR void on_error(const char* message) {
2270 context_.on_error(message);
2271 }
2272
2273 private:
2274 dynamic_format_specs<char_type>& specs_;
2275 ParseContext& context_;
2276
2277 using arg_ref_type = arg_ref<char_type>;
2278
2279 FMT_CONSTEXPR auto make_arg_ref(int arg_id) -> arg_ref_type {
2280 context_.check_arg_id(arg_id);
2281 context_.check_dynamic_spec(arg_id);
2282 return arg_ref_type(arg_id);
2283 }
2284
2285 FMT_CONSTEXPR auto make_arg_ref(auto_id) -> arg_ref_type {
2286 int arg_id = context_.next_arg_id();
2287 context_.check_dynamic_spec(arg_id);
2288 return arg_ref_type(arg_id);
2289 }
2290
2291 FMT_CONSTEXPR auto make_arg_ref(basic_string_view<char_type> arg_id)
2292 -> arg_ref_type {
2293 context_.check_arg_id(arg_id);
2294 basic_string_view<char_type> format_str(
2295 context_.begin(), to_unsigned(context_.end() - context_.begin()));
2296 return arg_ref_type(arg_id);
2297 }
2298};
2299
2300template <typename Char> constexpr bool is_ascii_letter(Char c) {
2301 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
2302}
2303
2304// Converts a character to ASCII. Returns a number > 127 on conversion failure.
2305template <typename Char, FMT_ENABLE_IF(std::is_integral<Char>::value)>
2306constexpr auto to_ascii(Char c) -> Char {
2307 return c;
2308}
2309template <typename Char, FMT_ENABLE_IF(std::is_enum<Char>::value)>
2310constexpr auto to_ascii(Char c) -> underlying_t<Char> {
2311 return c;
2312}
2313
2314FMT_CONSTEXPR inline auto code_point_length_impl(char c) -> int {
2315 return "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0\0\0\2\2\2\2\3\3\4"
2316 [static_cast<unsigned char>(c) >> 3];
2317}
2318
2319template <typename Char>
2320FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int {
2321 if (const_check(sizeof(Char) != 1)) return 1;
2322 int len = code_point_length_impl(static_cast<char>(*begin));
2323
2324 // Compute the pointer to the next character early so that the next
2325 // iteration can start working on the next character. Neither Clang
2326 // nor GCC figure out this reordering on their own.
2327 return len + !len;
2328}
2329
2330// Return the result via the out param to workaround gcc bug 77539.
2331template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>
2332FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool {
2333 for (out = first; out != last; ++out) {
2334 if (*out == value) return true;
2335 }
2336 return false;
2337}
2338
2339template <>
2340inline auto find<false, char>(const char* first, const char* last, char value,
2341 const char*& out) -> bool {
2342 out = static_cast<const char*>(
2343 std::memchr(first, value, to_unsigned(last - first)));
2344 return out != nullptr;
2345}
2346
2347// Parses the range [begin, end) as an unsigned integer. This function assumes
2348// that the range is non-empty and the first character is a digit.
2349template <typename Char>
2350FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end,
2351 int error_value) noexcept -> int {
2352 FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', "");
2353 unsigned value = 0, prev = 0;
2354 auto p = begin;
2355 do {
2356 prev = value;
2357 value = value * 10 + unsigned(*p - '0');
2358 ++p;
2359 } while (p != end && '0' <= *p && *p <= '9');
2360 auto num_digits = p - begin;
2361 begin = p;
2362 if (num_digits <= std::numeric_limits<int>::digits10)
2363 return static_cast<int>(value);
2364 // Check for overflow.
2365 const unsigned max = to_unsigned((std::numeric_limits<int>::max)());
2366 return num_digits == std::numeric_limits<int>::digits10 + 1 &&
2367 prev * 10ull + unsigned(p[-1] - '0') <= max
2368 ? static_cast<int>(value)
2369 : error_value;
2370}
2371
2372// Parses fill and alignment.
2373template <typename Char, typename Handler>
2374FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end,
2375 Handler&& handler) -> const Char* {
2376 FMT_ASSERT(begin != end, "");
2377 auto align = align::none;
2378 auto p = begin + code_point_length(begin);
2379 if (end - p <= 0) p = begin;
2380 for (;;) {
2381 switch (to_ascii(*p)) {
2382 case '<':
2383 align = align::left;
2384 break;
2385 case '>':
2386 align = align::right;
2387 break;
2388 case '^':
2389 align = align::center;
2390 break;
2391 default:
2392 break;
2393 }
2394 if (align != align::none) {
2395 if (p != begin) {
2396 auto c = *begin;
2397 if (c == '{')
2398 return handler.on_error("invalid fill character '{'"), begin;
2399 if (c == '}') return begin;
2400 handler.on_fill(basic_string_view<Char>(begin, to_unsigned(p - begin)));
2401 begin = p + 1;
2402 } else
2403 ++begin;
2404 handler.on_align(align);
2405 break;
2406 } else if (p == begin) {
2407 break;
2408 }
2409 p = begin;
2410 }
2411 return begin;
2412}
2413
2414template <typename Char> FMT_CONSTEXPR bool is_name_start(Char c) {
2415 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c;
2416}
2417
2418template <typename Char, typename IDHandler>
2419FMT_CONSTEXPR auto do_parse_arg_id(const Char* begin, const Char* end,
2420 IDHandler&& handler) -> const Char* {
2421 FMT_ASSERT(begin != end, "");
2422 Char c = *begin;
2423 if (c >= '0' && c <= '9') {
2424 int index = 0;
2425 if (c != '0')
2426 index =
2427 parse_nonnegative_int(begin, end, (std::numeric_limits<int>::max)());
2428 else
2429 ++begin;
2430 if (begin == end || (*begin != '}' && *begin != ':'))
2431 handler.on_error("invalid format string");
2432 else
2433 handler(index);
2434 return begin;
2435 }
2436 if (!is_name_start(c)) {
2437 handler.on_error("invalid format string");
2438 return begin;
2439 }
2440 auto it = begin;
2441 do {
2442 ++it;
2443 } while (it != end && (is_name_start(c = *it) || ('0' <= c && c <= '9')));
2444 handler(basic_string_view<Char>(begin, to_unsigned(it - begin)));
2445 return it;
2446}
2447
2448template <typename Char, typename IDHandler>
2449FMT_CONSTEXPR FMT_INLINE auto parse_arg_id(const Char* begin, const Char* end,
2450 IDHandler&& handler) -> const Char* {
2451 Char c = *begin;
2452 if (c != '}' && c != ':') return do_parse_arg_id(begin, end, handler);
2453 handler();
2454 return begin;
2455}
2456
2457template <typename Char, typename Handler>
2458FMT_CONSTEXPR auto parse_width(const Char* begin, const Char* end,
2459 Handler&& handler) -> const Char* {
2460 using detail::auto_id;
2461 struct width_adapter {
2462 Handler& handler;
2463
2464 FMT_CONSTEXPR void operator()() { handler.on_dynamic_width(auto_id()); }
2465 FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_width(id); }
2466 FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
2467 handler.on_dynamic_width(id);
2468 }
2469 FMT_CONSTEXPR void on_error(const char* message) {
2470 if (message) handler.on_error(message);
2471 }
2472 };
2473
2474 FMT_ASSERT(begin != end, "");
2475 if ('0' <= *begin && *begin <= '9') {
2476 int width = parse_nonnegative_int(begin, end, -1);
2477 if (width != -1)
2478 handler.on_width(width);
2479 else
2480 handler.on_error("number is too big");
2481 } else if (*begin == '{') {
2482 ++begin;
2483 if (begin != end) begin = parse_arg_id(begin, end, width_adapter{handler});
2484 if (begin == end || *begin != '}')
2485 return handler.on_error("invalid format string"), begin;
2486 ++begin;
2487 }
2488 return begin;
2489}
2490
2491template <typename Char, typename Handler>
2492FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end,
2493 Handler&& handler) -> const Char* {
2494 using detail::auto_id;
2495 struct precision_adapter {
2496 Handler& handler;
2497
2498 FMT_CONSTEXPR void operator()() { handler.on_dynamic_precision(auto_id()); }
2499 FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_precision(id); }
2500 FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
2501 handler.on_dynamic_precision(id);
2502 }
2503 FMT_CONSTEXPR void on_error(const char* message) {
2504 if (message) handler.on_error(message);
2505 }
2506 };
2507
2508 ++begin;
2509 auto c = begin != end ? *begin : Char();
2510 if ('0' <= c && c <= '9') {
2511 auto precision = parse_nonnegative_int(begin, end, -1);
2512 if (precision != -1)
2513 handler.on_precision(precision);
2514 else
2515 handler.on_error("number is too big");
2516 } else if (c == '{') {
2517 ++begin;
2518 if (begin != end)
2519 begin = parse_arg_id(begin, end, precision_adapter{handler});
2520 if (begin == end || *begin++ != '}')
2521 return handler.on_error("invalid format string"), begin;
2522 } else {
2523 return handler.on_error("missing precision specifier"), begin;
2524 }
2525 handler.end_precision();
2526 return begin;
2527}
2528
2529template <typename Char>
2530FMT_CONSTEXPR auto parse_presentation_type(Char type) -> presentation_type {
2531 switch (to_ascii(type)) {
2532 case 'd':
2533 return presentation_type::dec;
2534 case 'o':
2535 return presentation_type::oct;
2536 case 'x':
2537 return presentation_type::hex_lower;
2538 case 'X':
2539 return presentation_type::hex_upper;
2540 case 'b':
2541 return presentation_type::bin_lower;
2542 case 'B':
2543 return presentation_type::bin_upper;
2544 case 'a':
2545 return presentation_type::hexfloat_lower;
2546 case 'A':
2547 return presentation_type::hexfloat_upper;
2548 case 'e':
2549 return presentation_type::exp_lower;
2550 case 'E':
2551 return presentation_type::exp_upper;
2552 case 'f':
2553 return presentation_type::fixed_lower;
2554 case 'F':
2555 return presentation_type::fixed_upper;
2556 case 'g':
2557 return presentation_type::general_lower;
2558 case 'G':
2559 return presentation_type::general_upper;
2560 case 'c':
2561 return presentation_type::chr;
2562 case 's':
2563 return presentation_type::string;
2564 case 'p':
2565 return presentation_type::pointer;
2566 case '?':
2567 return presentation_type::debug;
2568 default:
2569 return presentation_type::none;
2570 }
2571}
2572
2573// Parses standard format specifiers and sends notifications about parsed
2574// components to handler.
2575template <typename Char, typename SpecHandler>
2576FMT_CONSTEXPR FMT_INLINE auto parse_format_specs(const Char* begin,
2577 const Char* end,
2578 SpecHandler&& handler)
2579 -> const Char* {
2580 if (1 < end - begin && begin[1] == '}' && is_ascii_letter(*begin) &&
2581 *begin != 'L') {
2582 presentation_type type = parse_presentation_type(*begin++);
2583 if (type == presentation_type::none)
2584 handler.on_error("invalid type specifier");
2585 handler.on_type(type);
2586 return begin;
2587 }
2588
2589 if (begin == end) return begin;
2590
2591 begin = parse_align(begin, end, handler);
2592 if (begin == end) return begin;
2593
2594 // Parse sign.
2595 switch (to_ascii(*begin)) {
2596 case '+':
2597 handler.on_sign(sign::plus);
2598 ++begin;
2599 break;
2600 case '-':
2601 handler.on_sign(sign::minus);
2602 ++begin;
2603 break;
2604 case ' ':
2605 handler.on_sign(sign::space);
2606 ++begin;
2607 break;
2608 default:
2609 break;
2610 }
2611 if (begin == end) return begin;
2612
2613 if (*begin == '#') {
2614 handler.on_hash();
2615 if (++begin == end) return begin;
2616 }
2617
2618 // Parse zero flag.
2619 if (*begin == '0') {
2620 handler.on_zero();
2621 if (++begin == end) return begin;
2622 }
2623
2624 begin = parse_width(begin, end, handler);
2625 if (begin == end) return begin;
2626
2627 // Parse precision.
2628 if (*begin == '.') {
2629 begin = parse_precision(begin, end, handler);
2630 if (begin == end) return begin;
2631 }
2632
2633 if (*begin == 'L') {
2634 handler.on_localized();
2635 ++begin;
2636 }
2637
2638 // Parse type.
2639 if (begin != end && *begin != '}') {
2640 presentation_type type = parse_presentation_type(*begin++);
2641 if (type == presentation_type::none)
2642 handler.on_error("invalid type specifier");
2643 handler.on_type(type);
2644 }
2645 return begin;
2646}
2647
2648template <typename Char, typename Handler>
2649FMT_CONSTEXPR auto parse_replacement_field(const Char* begin, const Char* end,
2650 Handler&& handler) -> const Char* {
2651 struct id_adapter {
2652 Handler& handler;
2653 int arg_id;
2654
2655 FMT_CONSTEXPR void operator()() { arg_id = handler.on_arg_id(); }
2656 FMT_CONSTEXPR void operator()(int id) { arg_id = handler.on_arg_id(id); }
2657 FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
2658 arg_id = handler.on_arg_id(id);
2659 }
2660 FMT_CONSTEXPR void on_error(const char* message) {
2661 if (message) handler.on_error(message);
2662 }
2663 };
2664
2665 ++begin;
2666 if (begin == end) return handler.on_error("invalid format string"), end;
2667 if (*begin == '}') {
2668 handler.on_replacement_field(handler.on_arg_id(), begin);
2669 } else if (*begin == '{') {
2670 handler.on_text(begin, begin + 1);
2671 } else {
2672 auto adapter = id_adapter{handler, 0};
2673 begin = parse_arg_id(begin, end, adapter);
2674 Char c = begin != end ? *begin : Char();
2675 if (c == '}') {
2676 handler.on_replacement_field(adapter.arg_id, begin);
2677 } else if (c == ':') {
2678 begin = handler.on_format_specs(adapter.arg_id, begin + 1, end);
2679 if (begin == end || *begin != '}')
2680 return handler.on_error("unknown format specifier"), end;
2681 } else {
2682 return handler.on_error("missing '}' in format string"), end;
2683 }
2684 }
2685 return begin + 1;
2686}
2687
2688template <bool IS_CONSTEXPR, typename Char, typename Handler>
2689FMT_CONSTEXPR FMT_INLINE void parse_format_string(
2690 basic_string_view<Char> format_str, Handler&& handler) {
2691 // Workaround a name-lookup bug in MSVC's modules implementation.
2692 using detail::find;
2693
2694 auto begin = format_str.data();
2695 auto end = begin + format_str.size();
2696 if (end - begin < 32) {
2697 // Use a simple loop instead of memchr for small strings.
2698 const Char* p = begin;
2699 while (p != end) {
2700 auto c = *p++;
2701 if (c == '{') {
2702 handler.on_text(begin, p - 1);
2703 begin = p = parse_replacement_field(p - 1, end, handler);
2704 } else if (c == '}') {
2705 if (p == end || *p != '}')
2706 return handler.on_error("unmatched '}' in format string");
2707 handler.on_text(begin, p);
2708 begin = ++p;
2709 }
2710 }
2711 handler.on_text(begin, end);
2712 return;
2713 }
2714 struct writer {
2715 FMT_CONSTEXPR void operator()(const Char* from, const Char* to) {
2716 if (from == to) return;
2717 for (;;) {
2718 const Char* p = nullptr;
2719 if (!find<IS_CONSTEXPR>(from, to, Char('}'), p))
2720 return handler_.on_text(from, to);
2721 ++p;
2722 if (p == to || *p != '}')
2723 return handler_.on_error("unmatched '}' in format string");
2724 handler_.on_text(from, p);
2725 from = p + 1;
2726 }
2727 }
2728 Handler& handler_;
2729 } write = {handler};
2730 while (begin != end) {
2731 // Doing two passes with memchr (one for '{' and another for '}') is up to
2732 // 2.5x faster than the naive one-pass implementation on big format strings.
2733 const Char* p = begin;
2734 if (*begin != '{' && !find<IS_CONSTEXPR>(begin + 1, end, Char('{'), p))
2735 return write(begin, end);
2736 write(begin, p);
2737 begin = parse_replacement_field(p, end, handler);
2738 }
2739}
2740
2741template <typename T, bool = is_named_arg<T>::value> struct strip_named_arg {
2742 using type = T;
2743};
2744template <typename T> struct strip_named_arg<T, true> {
2745 using type = remove_cvref_t<decltype(T::value)>;
2746};
2747
2748template <typename T, typename ParseContext>
2749FMT_CONSTEXPR auto parse_format_specs(ParseContext& ctx)
2750 -> decltype(ctx.begin()) {
2751 using char_type = typename ParseContext::char_type;
2752 using context = buffer_context<char_type>;
2753 using stripped_type = typename strip_named_arg<T>::type;
2754 using mapped_type = conditional_t<
2755 mapped_type_constant<T, context>::value != type::custom_type,
2756 decltype(arg_mapper<context>().map(std::declval<const T&>())),
2757 stripped_type>;
2758 auto f = conditional_t<has_formatter<mapped_type, context>::value,
2759 formatter<mapped_type, char_type>,
2760 fallback_formatter<stripped_type, char_type>>();
2761 return f.parse(ctx);
2762}
2763
2764template <typename ErrorHandler>
2765FMT_CONSTEXPR void check_int_type_spec(presentation_type type,
2766 ErrorHandler&& eh) {
2767 if (type > presentation_type::bin_upper && type != presentation_type::chr)
2768 eh.on_error("invalid type specifier");
2769}
2770
2771// Checks char specs and returns true if the type spec is char (and not int).
2772template <typename Char, typename ErrorHandler = error_handler>
2773FMT_CONSTEXPR auto check_char_specs(const basic_format_specs<Char>& specs,
2774 ErrorHandler&& eh = {}) -> bool {
2775 if (specs.type != presentation_type::none &&
2776 specs.type != presentation_type::chr &&
2777 specs.type != presentation_type::debug) {
2778 check_int_type_spec(specs.type, eh);
2779 return false;
2780 }
2781 if (specs.align == align::numeric || specs.sign != sign::none || specs.alt)
2782 eh.on_error("invalid format specifier for char");
2783 return true;
2784}
2785
2786// A floating-point presentation format.
2787enum class float_format : unsigned char {
2788 general, // General: exponent notation or fixed point based on magnitude.
2789 exp, // Exponent notation with the default precision of 6, e.g. 1.2e-3.
2790 fixed, // Fixed point with the default precision of 6, e.g. 0.0012.
2791 hex
2792};
2793
2794struct float_specs {
2795 int precision;
2796 float_format format : 8;
2797 sign_t sign : 8;
2798 bool upper : 1;
2799 bool locale : 1;
2800 bool binary32 : 1;
2801 bool showpoint : 1;
2802};
2803
2804template <typename ErrorHandler = error_handler, typename Char>
2805FMT_CONSTEXPR auto parse_float_type_spec(const basic_format_specs<Char>& specs,
2806 ErrorHandler&& eh = {})
2807 -> float_specs {
2808 auto result = float_specs();
2809 result.showpoint = specs.alt;
2810 result.locale = specs.localized;
2811 switch (specs.type) {
2812 case presentation_type::none:
2813 result.format = float_format::general;
2814 break;
2815 case presentation_type::general_upper:
2816 result.upper = true;
2817 FMT_FALLTHROUGH;
2818 case presentation_type::general_lower:
2819 result.format = float_format::general;
2820 break;
2821 case presentation_type::exp_upper:
2822 result.upper = true;
2823 FMT_FALLTHROUGH;
2824 case presentation_type::exp_lower:
2825 result.format = float_format::exp;
2826 result.showpoint |= specs.precision != 0;
2827 break;
2828 case presentation_type::fixed_upper:
2829 result.upper = true;
2830 FMT_FALLTHROUGH;
2831 case presentation_type::fixed_lower:
2832 result.format = float_format::fixed;
2833 result.showpoint |= specs.precision != 0;
2834 break;
2835 case presentation_type::hexfloat_upper:
2836 result.upper = true;
2837 FMT_FALLTHROUGH;
2838 case presentation_type::hexfloat_lower:
2839 result.format = float_format::hex;
2840 break;
2841 default:
2842 eh.on_error("invalid type specifier");
2843 break;
2844 }
2845 return result;
2846}
2847
2848template <typename ErrorHandler = error_handler>
2849FMT_CONSTEXPR auto check_cstring_type_spec(presentation_type type,
2850 ErrorHandler&& eh = {}) -> bool {
2851 if (type == presentation_type::none || type == presentation_type::string ||
2852 type == presentation_type::debug)
2853 return true;
2854 if (type != presentation_type::pointer) eh.on_error("invalid type specifier");
2855 return false;
2856}
2857
2858template <typename ErrorHandler = error_handler>
2859FMT_CONSTEXPR void check_string_type_spec(presentation_type type,
2860 ErrorHandler&& eh = {}) {
2861 if (type != presentation_type::none && type != presentation_type::string &&
2862 type != presentation_type::debug)
2863 eh.on_error("invalid type specifier");
2864}
2865
2866template <typename ErrorHandler>
2867FMT_CONSTEXPR void check_pointer_type_spec(presentation_type type,
2868 ErrorHandler&& eh) {
2869 if (type != presentation_type::none && type != presentation_type::pointer)
2870 eh.on_error("invalid type specifier");
2871}
2872
2873// A parse_format_specs handler that checks if specifiers are consistent with
2874// the argument type.
2875template <typename Handler> class specs_checker : public Handler {
2876 private:
2877 detail::type arg_type_;
2878
2879 FMT_CONSTEXPR void require_numeric_argument() {
2880 if (!is_arithmetic_type(arg_type_))
2881 this->on_error("format specifier requires numeric argument");
2882 }
2883
2884 public:
2885 FMT_CONSTEXPR specs_checker(const Handler& handler, detail::type arg_type)
2886 : Handler(handler), arg_type_(arg_type) {}
2887
2888 FMT_CONSTEXPR void on_align(align_t align) {
2889 if (align == align::numeric) require_numeric_argument();
2890 Handler::on_align(align);
2891 }
2892
2893 FMT_CONSTEXPR void on_sign(sign_t s) {
2894 require_numeric_argument();
2895 if (is_integral_type(arg_type_) && arg_type_ != type::int_type &&
2896 arg_type_ != type::long_long_type && arg_type_ != type::int128_type &&
2897 arg_type_ != type::char_type) {
2898 this->on_error("format specifier requires signed argument");
2899 }
2900 Handler::on_sign(s);
2901 }
2902
2903 FMT_CONSTEXPR void on_hash() {
2904 require_numeric_argument();
2905 Handler::on_hash();
2906 }
2907
2908 FMT_CONSTEXPR void on_localized() {
2909 require_numeric_argument();
2910 Handler::on_localized();
2911 }
2912
2913 FMT_CONSTEXPR void on_zero() {
2914 require_numeric_argument();
2915 Handler::on_zero();
2916 }
2917
2918 FMT_CONSTEXPR void end_precision() {
2919 if (is_integral_type(arg_type_) || arg_type_ == type::pointer_type)
2920 this->on_error("precision not allowed for this argument type");
2921 }
2922};
2923
2924constexpr int invalid_arg_index = -1;
2925
2926#if FMT_USE_NONTYPE_TEMPLATE_ARGS
2927template <int N, typename T, typename... Args, typename Char>
2928constexpr auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
2929 if constexpr (detail::is_statically_named_arg<T>()) {
2930 if (name == T::name) return N;
2931 }
2932 if constexpr (sizeof...(Args) > 0)
2933 return get_arg_index_by_name<N + 1, Args...>(name);
2934 (void)name; // Workaround an MSVC bug about "unused" parameter.
2935 return invalid_arg_index;
2936}
2937#endif
2938
2939template <typename... Args, typename Char>
2940FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
2941#if FMT_USE_NONTYPE_TEMPLATE_ARGS
2942 if constexpr (sizeof...(Args) > 0)
2943 return get_arg_index_by_name<0, Args...>(name);
2944#endif
2945 (void)name;
2946 return invalid_arg_index;
2947}
2948
2949template <typename Char, typename ErrorHandler, typename... Args>
2950class format_string_checker {
2951 private:
2952 // In the future basic_format_parse_context will replace compile_parse_context
2953 // here and will use is_constant_evaluated and downcasting to access the data
2954 // needed for compile-time checks: https://godbolt.org/z/GvWzcTjh1.
2955 using parse_context_type = compile_parse_context<Char, ErrorHandler>;
2956 static constexpr int num_args = sizeof...(Args);
2957
2958 // Format specifier parsing function.
2959 using parse_func = const Char* (*)(parse_context_type&);
2960
2961 parse_context_type context_;
2962 parse_func parse_funcs_[num_args > 0 ? static_cast<size_t>(num_args) : 1];
2963 type types_[num_args > 0 ? static_cast<size_t>(num_args) : 1];
2964
2965 public:
2966 explicit FMT_CONSTEXPR format_string_checker(
2967 basic_string_view<Char> format_str, ErrorHandler eh)
2968 : context_(format_str, num_args, types_, eh),
2969 parse_funcs_{&parse_format_specs<Args, parse_context_type>...},
2970 types_{
2971 mapped_type_constant<Args,
2972 basic_format_context<Char*, Char>>::value...} {
2973 }
2974
2975 FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
2976
2977 FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); }
2978 FMT_CONSTEXPR auto on_arg_id(int id) -> int {
2979 return context_.check_arg_id(id), id;
2980 }
2981 FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
2982#if FMT_USE_NONTYPE_TEMPLATE_ARGS
2983 auto index = get_arg_index_by_name<Args...>(id);
2984 if (index == invalid_arg_index) on_error("named argument is not found");
2985 return context_.check_arg_id(index), index;
2986#else
2987 (void)id;
2988 on_error("compile-time checks for named arguments require C++20 support");
2989 return 0;
2990#endif
2991 }
2992
2993 FMT_CONSTEXPR void on_replacement_field(int, const Char*) {}
2994
2995 FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char*)
2996 -> const Char* {
2997 context_.advance_to(context_.begin() + (begin - &*context_.begin()));
2998 // id >= 0 check is a workaround for gcc 10 bug (#2065).
2999 return id >= 0 && id < num_args ? parse_funcs_[id](context_) : begin;
3000 }
3001
3002 FMT_CONSTEXPR void on_error(const char* message) {
3003 context_.on_error(message);
3004 }
3005};
3006
3007// Reports a compile-time error if S is not a valid format string.
3008template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
3009FMT_INLINE void check_format_string(const S&) {
3010#ifdef FMT_ENFORCE_COMPILE_STRING
3011 static_assert(is_compile_string<S>::value,
3012 "FMT_ENFORCE_COMPILE_STRING requires all format strings to use "
3013 "FMT_STRING.");
3014#endif
3015}
3016template <typename... Args, typename S,
3017 FMT_ENABLE_IF(is_compile_string<S>::value)>
3018void check_format_string(S format_str) {
3019 FMT_CONSTEXPR auto s = basic_string_view<typename S::char_type>(format_str);
3020 using checker = format_string_checker<typename S::char_type, error_handler,
3021 remove_cvref_t<Args>...>;
3022 FMT_CONSTEXPR bool invalid_format =
3023 (parse_format_string<true>(s, checker(s, {})), true);
3024 ignore_unused(invalid_format);
3025}
3026
3027// Don't use type_identity for args to simplify symbols.
3028template <typename Char>
3029void vformat_to(buffer<Char>& buf, basic_string_view<Char> fmt,
3030 basic_format_args<FMT_BUFFER_CONTEXT(Char)> args,
3031 locale_ref loc = {});
3032
3033FMT_API void vprint_mojibake(std::FILE*, string_view, format_args);
3034#ifndef _WIN32
3035inline void vprint_mojibake(std::FILE*, string_view, format_args) {}
3036#endif
3037FMT_END_DETAIL_NAMESPACE
3038
3039// A formatter specialization for the core types corresponding to detail::type
3040// constants.
3041template <typename T, typename Char>
3042struct formatter<T, Char,
3043 enable_if_t<detail::type_constant<T, Char>::value !=
3044 detail::type::custom_type>> {
3045 private:
3046 detail::dynamic_format_specs<Char> specs_;
3047
3048 public:
3049 // Parses format specifiers stopping either at the end of the range or at the
3050 // terminating '}'.
3051 template <typename ParseContext>
3052 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
3053 auto begin = ctx.begin(), end = ctx.end();
3054 if (begin == end) return begin;
3055 using handler_type = detail::dynamic_specs_handler<ParseContext>;
3056 auto type = detail::type_constant<T, Char>::value;
3057 auto checker =
3058 detail::specs_checker<handler_type>(handler_type(specs_, ctx), type);
3059 auto it = detail::parse_format_specs(begin, end, checker);
3060 auto eh = ctx.error_handler();
3061 switch (type) {
3062 case detail::type::none_type:
3063 FMT_ASSERT(false, "invalid argument type");
3064 break;
3065 case detail::type::bool_type:
3066 if (specs_.type == presentation_type::none ||
3067 specs_.type == presentation_type::string) {
3068 break;
3069 }
3070 FMT_FALLTHROUGH;
3071 case detail::type::int_type:
3072 case detail::type::uint_type:
3073 case detail::type::long_long_type:
3074 case detail::type::ulong_long_type:
3075 case detail::type::int128_type:
3076 case detail::type::uint128_type:
3077 detail::check_int_type_spec(specs_.type, eh);
3078 break;
3079 case detail::type::char_type:
3080 detail::check_char_specs(specs_, eh);
3081 break;
3082 case detail::type::float_type:
3083 if (detail::const_check(FMT_USE_FLOAT))
3084 detail::parse_float_type_spec(specs_, eh);
3085 else
3086 FMT_ASSERT(false, "float support disabled");
3087 break;
3088 case detail::type::double_type:
3089 if (detail::const_check(FMT_USE_DOUBLE))
3090 detail::parse_float_type_spec(specs_, eh);
3091 else
3092 FMT_ASSERT(false, "double support disabled");
3093 break;
3094 case detail::type::long_double_type:
3095 if (detail::const_check(FMT_USE_LONG_DOUBLE))
3096 detail::parse_float_type_spec(specs_, eh);
3097 else
3098 FMT_ASSERT(false, "long double support disabled");
3099 break;
3100 case detail::type::cstring_type:
3101 detail::check_cstring_type_spec(specs_.type, eh);
3102 break;
3103 case detail::type::string_type:
3104 detail::check_string_type_spec(specs_.type, eh);
3105 break;
3106 case detail::type::pointer_type:
3107 detail::check_pointer_type_spec(specs_.type, eh);
3108 break;
3109 case detail::type::custom_type:
3110 // Custom format specifiers are checked in parse functions of
3111 // formatter specializations.
3112 break;
3113 }
3114 return it;
3115 }
3116
3117 template <detail::type U = detail::type_constant<T, Char>::value,
3118 enable_if_t<(U == detail::type::string_type ||
3119 U == detail::type::cstring_type ||
3120 U == detail::type::char_type),
3121 int> = 0>
3122 FMT_CONSTEXPR void set_debug_format() {
3123 specs_.type = presentation_type::debug;
3124 }
3125
3126 template <typename FormatContext>
3127 FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const
3128 -> decltype(ctx.out());
3129};
3130
3131#define FMT_FORMAT_AS(Type, Base) \
3132 template <typename Char> \
3133 struct formatter<Type, Char> : formatter<Base, Char> { \
3134 template <typename FormatContext> \
3135 auto format(Type const& val, FormatContext& ctx) const \
3136 -> decltype(ctx.out()) { \
3137 return formatter<Base, Char>::format(static_cast<Base>(val), ctx); \
3138 } \
3139 }
3140
3141FMT_FORMAT_AS(signed char, int);
3142FMT_FORMAT_AS(unsigned char, unsigned);
3143FMT_FORMAT_AS(short, int);
3144FMT_FORMAT_AS(unsigned short, unsigned);
3145FMT_FORMAT_AS(long, long long);
3146FMT_FORMAT_AS(unsigned long, unsigned long long);
3147FMT_FORMAT_AS(Char*, const Char*);
3148FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>);
3149FMT_FORMAT_AS(std::nullptr_t, const void*);
3150FMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>);
3151
3152template <typename Char> struct basic_runtime { basic_string_view<Char> str; };
3153
3154/** A compile-time format string. */
3155template <typename Char, typename... Args> class basic_format_string {
3156 private:
3157 basic_string_view<Char> str_;
3158
3159 public:
3160 template <typename S,
3161 FMT_ENABLE_IF(
3162 std::is_convertible<const S&, basic_string_view<Char>>::value)>
3163 FMT_CONSTEVAL FMT_INLINE basic_format_string(const S& s) : str_(s) {
3164 static_assert(
3165 detail::count<
3166 (std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
3167 std::is_reference<Args>::value)...>() == 0,
3168 "passing views as lvalues is disallowed");
3169#ifdef FMT_HAS_CONSTEVAL
3170 if constexpr (detail::count_named_args<Args...>() ==
3171 detail::count_statically_named_args<Args...>()) {
3172 using checker = detail::format_string_checker<Char, detail::error_handler,
3173 remove_cvref_t<Args>...>;
3174 detail::parse_format_string<true>(str_, checker(s, {}));
3175 }
3176#else
3177 detail::check_format_string<Args...>(s);
3178#endif
3179 }
3180 basic_format_string(basic_runtime<Char> r) : str_(r.str) {}
3181
3182 FMT_INLINE operator basic_string_view<Char>() const { return str_; }
3183};
3184
3185#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
3186// Workaround broken conversion on older gcc.
3187template <typename...> using format_string = string_view;
3188inline auto runtime(string_view s) -> string_view { return s; }
3189#else
3190template <typename... Args>
3191using format_string = basic_format_string<char, type_identity_t<Args>...>;
3192/**
3193 \rst
3194 Creates a runtime format string.
3195
3196 **Example**::
3197
3198 // Check format string at runtime instead of compile-time.
3199 fmt::print(fmt::runtime("{:d}"), "I am not a number");
3200 \endrst
3201 */
3202inline auto runtime(string_view s) -> basic_runtime<char> { return {{s}}; }
3203#endif
3204
3205FMT_API auto vformat(string_view fmt, format_args args) -> std::string;
3206
3207/**
3208 \rst
3209 Formats ``args`` according to specifications in ``fmt`` and returns the result
3210 as a string.
3211
3212 **Example**::
3213
3214 #include <fmt/core.h>
3215 std::string message = fmt::format("The answer is {}.", 42);
3216 \endrst
3217*/
3218template <typename... T>
3219FMT_NODISCARD FMT_INLINE auto format(format_string<T...> fmt, T&&... args)
3220 -> std::string {
3221 return vformat(fmt, fmt::make_format_args(args...));
3222}
3223
3224/** Formats a string and writes the output to ``out``. */
3225template <typename OutputIt,
3226 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
3227auto vformat_to(OutputIt out, string_view fmt, format_args args) -> OutputIt {
3228 auto&& buf = detail::get_buffer<char>(out);
3229 detail::vformat_to(buf, fmt, args, {});
3230 return detail::get_iterator(buf, out);
3231}
3232
3233/**
3234 \rst
3235 Formats ``args`` according to specifications in ``fmt``, writes the result to
3236 the output iterator ``out`` and returns the iterator past the end of the output
3237 range. `format_to` does not append a terminating null character.
3238
3239 **Example**::
3240
3241 auto out = std::vector<char>();
3242 fmt::format_to(std::back_inserter(out), "{}", 42);
3243 \endrst
3244 */
3245template <typename OutputIt, typename... T,
3246 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
3247FMT_INLINE auto format_to(OutputIt out, format_string<T...> fmt, T&&... args)
3248 -> OutputIt {
3249 return vformat_to(out, fmt, fmt::make_format_args(args...));
3250}
3251
3252template <typename OutputIt> struct format_to_n_result {
3253 /** Iterator past the end of the output range. */
3254 OutputIt out;
3255 /** Total (not truncated) output size. */
3256 size_t size;
3257};
3258
3259template <typename OutputIt, typename... T,
3260 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
3261auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args)
3262 -> format_to_n_result<OutputIt> {
3263 using traits = detail::fixed_buffer_traits;
3264 auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);
3265 detail::vformat_to(buf, fmt, args, {});
3266 return {buf.out(), buf.count()};
3267}
3268
3269/**
3270 \rst
3271 Formats ``args`` according to specifications in ``fmt``, writes up to ``n``
3272 characters of the result to the output iterator ``out`` and returns the total
3273 (not truncated) output size and the iterator past the end of the output range.
3274 `format_to_n` does not append a terminating null character.
3275 \endrst
3276 */
3277template <typename OutputIt, typename... T,
3278 FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
3279FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string<T...> fmt,
3280 T&&... args) -> format_to_n_result<OutputIt> {
3281 return vformat_to_n(out, n, fmt, fmt::make_format_args(args...));
3282}
3283
3284/** Returns the number of chars in the output of ``format(fmt, args...)``. */
3285template <typename... T>
3286FMT_NODISCARD FMT_INLINE auto formatted_size(format_string<T...> fmt,
3287 T&&... args) -> size_t {
3288 auto buf = detail::counting_buffer<>();
3289 detail::vformat_to(buf, string_view(fmt),
3290 format_args(fmt::make_format_args(args...)), {});
3291 return buf.count();
3292}
3293
3294FMT_API void vprint(string_view fmt, format_args args);
3295FMT_API void vprint(std::FILE* f, string_view fmt, format_args args);
3296
3297/**
3298 \rst
3299 Formats ``args`` according to specifications in ``fmt`` and writes the output
3300 to ``stdout``.
3301
3302 **Example**::
3303
3304 fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
3305 \endrst
3306 */
3307template <typename... T>
3308FMT_INLINE void print(format_string<T...> fmt, T&&... args) {
3309 const auto& vargs = fmt::make_format_args(args...);
3310 return detail::is_utf8() ? vprint(fmt, vargs)
3311 : detail::vprint_mojibake(stdout, fmt, vargs);
3312}
3313
3314/**
3315 \rst
3316 Formats ``args`` according to specifications in ``fmt`` and writes the
3317 output to the file ``f``.
3318
3319 **Example**::
3320
3321 fmt::print(stderr, "Don't {}!", "panic");
3322 \endrst
3323 */
3324template <typename... T>
3325FMT_INLINE void print(std::FILE* f, format_string<T...> fmt, T&&... args) {
3326 const auto& vargs = fmt::make_format_args(args...);
3327 return detail::is_utf8() ? vprint(f, fmt, vargs)
3328 : detail::vprint_mojibake(f, fmt, vargs);
3329}
3330
3331FMT_MODULE_EXPORT_END
3332FMT_GCC_PRAGMA("GCC pop_options")
3333FMT_END_NAMESPACE
3334
3335#ifdef FMT_HEADER_ONLY
3336# include "format.h"
3337#endif
3338#endif // FMT_CORE_H_
3339