RavEngine
Loading...
Searching...
No Matches
base.h
1// Formatting library for C++ - the base API for char/UTF-8
2//
3// Copyright (c) 2012 - present, Victor Zverovich
4// All rights reserved.
5//
6// For the license information refer to format.h.
7
8#ifndef FMT_BASE_H_
9#define FMT_BASE_H_
10
11#include <limits.h> // CHAR_BIT
12#include <stdio.h> // FILE
13#include <string.h> // strlen
14
15#ifndef FMT_IMPORT_STD
16// <cstddef> is also included transitively from <type_traits>.
17# include <cstddef> // std::byte
18# include <type_traits> // std::enable_if
19#else
20import std;
21#endif
22
23// The fmt library version in the form major * 10000 + minor * 100 + patch.
24#define FMT_VERSION 100202
25
26// Detect compiler versions.
27#if defined(__clang__) && !defined(__ibmxl__)
28# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
29#else
30# define FMT_CLANG_VERSION 0
31#endif
32#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
33# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
34#else
35# define FMT_GCC_VERSION 0
36#endif
37#if defined(__ICL)
38# define FMT_ICC_VERSION __ICL
39#elif defined(__INTEL_COMPILER)
40# define FMT_ICC_VERSION __INTEL_COMPILER
41#else
42# define FMT_ICC_VERSION 0
43#endif
44#if defined(_MSC_VER)
45# define FMT_MSC_VERSION _MSC_VER
46#else
47# define FMT_MSC_VERSION 0
48#endif
49
50// Detect standard library versions.
51#ifdef _GLIBCXX_RELEASE
52# define FMT_GLIBCXX_RELEASE _GLIBCXX_RELEASE
53#else
54# define FMT_GLIBCXX_RELEASE 0
55#endif
56#ifdef _LIBCPP_VERSION
57# define FMT_LIBCPP_VERSION _LIBCPP_VERSION
58#else
59# define FMT_LIBCPP_VERSION 0
60#endif
61
62#ifdef _MSVC_LANG
63# define FMT_CPLUSPLUS _MSVC_LANG
64#else
65# define FMT_CPLUSPLUS __cplusplus
66#endif
67
68// Detect __has_*.
69#ifdef __has_feature
70# define FMT_HAS_FEATURE(x) __has_feature(x)
71#else
72# define FMT_HAS_FEATURE(x) 0
73#endif
74#ifdef __has_include
75# define FMT_HAS_INCLUDE(x) __has_include(x)
76#else
77# define FMT_HAS_INCLUDE(x) 0
78#endif
79#ifdef __has_cpp_attribute
80# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
81#else
82# define FMT_HAS_CPP_ATTRIBUTE(x) 0
83#endif
84
85#define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
86 (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
87
88#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \
89 (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))
90
91// Detect C++14 relaxed constexpr.
92#ifdef FMT_USE_CONSTEXPR
93// Use the provided definition.
94#elif FMT_GCC_VERSION >= 600 && FMT_CPLUSPLUS >= 201402L
95// GCC only allows throw in constexpr since version 6:
96// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67371.
97# define FMT_USE_CONSTEXPR 1
98#elif FMT_ICC_VERSION
99# define FMT_USE_CONSTEXPR 0 // https://github.com/fmtlib/fmt/issues/1628
100#elif FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912
101# define FMT_USE_CONSTEXPR 1
102#else
103# define FMT_USE_CONSTEXPR 0
104#endif
105#if FMT_USE_CONSTEXPR
106# define FMT_CONSTEXPR constexpr
107#else
108# define FMT_CONSTEXPR
109#endif
110
111// Detect consteval, C++20 constexpr extensions and std::is_constant_evaluated.
112#if !defined(__cpp_lib_is_constant_evaluated)
113# define FMT_USE_CONSTEVAL 0
114#elif FMT_CPLUSPLUS < 201709L
115# define FMT_USE_CONSTEVAL 0
116#elif FMT_GLIBCXX_RELEASE && FMT_GLIBCXX_RELEASE < 10
117# define FMT_USE_CONSTEVAL 0
118#elif FMT_LIBCPP_VERSION && FMT_LIBCPP_VERSION < 10000
119# define FMT_USE_CONSTEVAL 0
120#elif defined(__apple_build_version__) && __apple_build_version__ < 14000029L
121# define FMT_USE_CONSTEVAL 0 // consteval is broken in Apple clang < 14.
122#elif FMT_MSC_VERSION && FMT_MSC_VERSION < 1929
123# define FMT_USE_CONSTEVAL 0 // consteval is broken in MSVC VS2019 < 16.10.
124#elif defined(__cpp_consteval)
125# define FMT_USE_CONSTEVAL 1
126#elif FMT_GCC_VERSION >= 1002 || FMT_CLANG_VERSION >= 1101
127# define FMT_USE_CONSTEVAL 1
128#else
129# define FMT_USE_CONSTEVAL 0
130#endif
131#if FMT_USE_CONSTEVAL
132# define FMT_CONSTEVAL consteval
133# define FMT_CONSTEXPR20 constexpr
134#else
135# define FMT_CONSTEVAL
136# define FMT_CONSTEXPR20
137#endif
138
139#if defined(FMT_USE_NONTYPE_TEMPLATE_ARGS)
140// Use the provided definition.
141#elif defined(__NVCOMPILER)
142# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0
143#elif FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L
144# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
145#elif defined(__cpp_nontype_template_args) && \
146 __cpp_nontype_template_args >= 201911L
147# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
148#else
149# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0
150#endif
151
152// Check if exceptions are disabled.
153#ifdef FMT_EXCEPTIONS
154// Use the provided definition.
155#elif defined(__GNUC__) && !defined(__EXCEPTIONS)
156# define FMT_EXCEPTIONS 0
157#elif FMT_MSC_VERSION && !_HAS_EXCEPTIONS
158# define FMT_EXCEPTIONS 0
159#else
160# define FMT_EXCEPTIONS 1
161#endif
162#if FMT_EXCEPTIONS
163# define FMT_TRY try
164# define FMT_CATCH(x) catch (x)
165#else
166# define FMT_TRY if (true)
167# define FMT_CATCH(x) if (false)
168#endif
169
170#if FMT_HAS_CPP17_ATTRIBUTE(fallthrough)
171# define FMT_FALLTHROUGH [[fallthrough]]
172#elif defined(__clang__)
173# define FMT_FALLTHROUGH [[clang::fallthrough]]
174#elif FMT_GCC_VERSION >= 700 && \
175 (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)
176# define FMT_FALLTHROUGH [[gnu::fallthrough]]
177#else
178# define FMT_FALLTHROUGH
179#endif
180
181// Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings.
182#if FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && !defined(__NVCC__)
183# define FMT_NORETURN [[noreturn]]
184#else
185# define FMT_NORETURN
186#endif
187
188#ifndef FMT_NODISCARD
189# if FMT_HAS_CPP17_ATTRIBUTE(nodiscard)
190# define FMT_NODISCARD [[nodiscard]]
191# else
192# define FMT_NODISCARD
193# endif
194#endif
195
196#ifdef FMT_DEPRECATED
197// Use the provided definition.
198#elif FMT_HAS_CPP14_ATTRIBUTE(deprecated)
199# define FMT_DEPRECATED [[deprecated]]
200#else
201# define FMT_DEPRECATED /* deprecated */
202#endif
203
204#ifdef FMT_INLINE
205// Use the provided definition.
206#elif FMT_GCC_VERSION || FMT_CLANG_VERSION
207# define FMT_ALWAYS_INLINE inline __attribute__((always_inline))
208#else
209# define FMT_ALWAYS_INLINE inline
210#endif
211// A version of FMT_INLINE to prevent code bloat in debug mode.
212#ifdef NDEBUG
213# define FMT_INLINE FMT_ALWAYS_INLINE
214#else
215# define FMT_INLINE inline
216#endif
217
218#if FMT_GCC_VERSION || FMT_CLANG_VERSION
219# define FMT_VISIBILITY(value) __attribute__((visibility(value)))
220#else
221# define FMT_VISIBILITY(value)
222#endif
223
224#ifndef FMT_GCC_PRAGMA
225// Workaround a _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884
226// and an nvhpc warning: https://github.com/fmtlib/fmt/pull/2582.
227# if FMT_GCC_VERSION >= 504 && !defined(__NVCOMPILER)
228# define FMT_GCC_PRAGMA(arg) _Pragma(arg)
229# else
230# define FMT_GCC_PRAGMA(arg)
231# endif
232#endif
233
234// GCC < 5 requires this-> in decltype.
235#if FMT_GCC_VERSION && FMT_GCC_VERSION < 500
236# define FMT_DECLTYPE_THIS this->
237#else
238# define FMT_DECLTYPE_THIS
239#endif
240
241#if FMT_MSC_VERSION
242# define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__))
243# define FMT_UNCHECKED_ITERATOR(It) \
244 using _Unchecked_type = It // Mark iterator as checked.
245#else
246# define FMT_MSC_WARNING(...)
247# define FMT_UNCHECKED_ITERATOR(It) using unchecked_type = It
248#endif
249
250#ifndef FMT_BEGIN_NAMESPACE
251# define FMT_BEGIN_NAMESPACE \
252 namespace fmt { \
253 inline namespace v10 {
254# define FMT_END_NAMESPACE \
255 } \
256 }
257#endif
258
259#ifndef FMT_EXPORT
260# define FMT_EXPORT
261# define FMT_BEGIN_EXPORT
262# define FMT_END_EXPORT
263#endif
264
265#if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
266# if defined(FMT_LIB_EXPORT)
267# define FMT_API __declspec(dllexport)
268# elif defined(FMT_SHARED)
269# define FMT_API __declspec(dllimport)
270# endif
271#elif defined(FMT_LIB_EXPORT) || defined(FMT_SHARED)
272# define FMT_API FMT_VISIBILITY("default")
273#endif
274#ifndef FMT_API
275# define FMT_API
276#endif
277
278#ifndef FMT_UNICODE
279# define FMT_UNICODE 1
280#endif
281
282#define FMT_FWD(...) static_cast<decltype(__VA_ARGS__)&&>(__VA_ARGS__)
283
284// Enable minimal optimizations for more compact code in debug mode.
285FMT_GCC_PRAGMA("GCC push_options")
286#if !defined(__OPTIMIZE__) && !defined(__CUDACC__)
287FMT_GCC_PRAGMA("GCC optimize(\"Og\")")
288#endif
289
290FMT_BEGIN_NAMESPACE
291
292// Implementations of enable_if_t and other metafunctions for older systems.
293template <bool B, typename T = void>
294using enable_if_t = typename std::enable_if<B, T>::type;
295template <bool B, typename T, typename F>
296using conditional_t = typename std::conditional<B, T, F>::type;
297template <bool B> using bool_constant = std::integral_constant<bool, B>;
298template <typename T>
299using remove_reference_t = typename std::remove_reference<T>::type;
300template <typename T>
301using remove_const_t = typename std::remove_const<T>::type;
302template <typename T>
303using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
304template <typename T> struct type_identity {
305 using type = T;
306};
307template <typename T> using type_identity_t = typename type_identity<T>::type;
308template <typename T>
309using make_unsigned_t = typename std::make_unsigned<T>::type;
310template <typename T>
311using underlying_t = typename std::underlying_type<T>::type;
312
313#if FMT_GCC_VERSION && FMT_GCC_VERSION < 500
314// A workaround for gcc 4.8 to make void_t work in a SFINAE context.
315template <typename...> struct void_t_impl {
316 using type = void;
317};
318template <typename... T> using void_t = typename void_t_impl<T...>::type;
319#else
320template <typename...> using void_t = void;
321#endif
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
336// This is defined in base.h instead of format.h to avoid injecting in std.
337// It is a template to avoid undesirable implicit conversions to std::byte.
338#ifdef __cpp_lib_byte
339template <typename T, FMT_ENABLE_IF(std::is_same<T, std::byte>::value)>
340inline auto format_as(T b) -> unsigned char {
341 return static_cast<unsigned char>(b);
342}
343#endif
344
345namespace detail {
346// Suppresses "unused variable" warnings with the method described in
347// https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/.
348// (void)var does not work on many Intel compilers.
349template <typename... T> FMT_CONSTEXPR void ignore_unused(const T&...) {}
350
351constexpr auto is_constant_evaluated(bool default_value = false) noexcept
352 -> bool {
353// Workaround for incompatibility between libstdc++ consteval-based
354// std::is_constant_evaluated() implementation and clang-14:
355// https://github.com/fmtlib/fmt/issues/3247.
356#if FMT_CPLUSPLUS >= 202002L && FMT_GLIBCXX_RELEASE >= 12 && \
357 (FMT_CLANG_VERSION >= 1400 && FMT_CLANG_VERSION < 1500)
358 ignore_unused(default_value);
359 return __builtin_is_constant_evaluated();
360#elif defined(__cpp_lib_is_constant_evaluated)
361 ignore_unused(default_value);
362 return std::is_constant_evaluated();
363#else
364 return default_value;
365#endif
366}
367
368// Suppresses "conditional expression is constant" warnings.
369template <typename T> constexpr auto const_check(T value) -> T { return value; }
370
371FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
372 const char* message);
373
374#if defined(FMT_ASSERT)
375// Use the provided definition.
376#elif defined(NDEBUG)
377// FMT_ASSERT is not empty to avoid -Wempty-body.
378# define FMT_ASSERT(condition, message) \
379 fmt::detail::ignore_unused((condition), (message))
380#else
381# define FMT_ASSERT(condition, message) \
382 ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
383 ? (void)0 \
384 : fmt::detail::assert_fail(__FILE__, __LINE__, (message)))
385#endif
386
387#ifdef FMT_USE_INT128
388// Do nothing.
389#elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \
390 !(FMT_CLANG_VERSION && FMT_MSC_VERSION)
391# define FMT_USE_INT128 1
392using int128_opt = __int128_t; // An optional native 128-bit integer.
393using uint128_opt = __uint128_t;
394template <typename T> inline auto convert_for_visit(T value) -> T {
395 return value;
396}
397#else
398# define FMT_USE_INT128 0
399#endif
400#if !FMT_USE_INT128
401enum class int128_opt {};
402enum class uint128_opt {};
403// Reduce template instantiations.
404template <typename T> auto convert_for_visit(T) -> monostate { return {}; }
405#endif
406
407// Casts a nonnegative integer to unsigned.
408template <typename Int>
409FMT_CONSTEXPR auto to_unsigned(Int value) -> make_unsigned_t<Int> {
410 FMT_ASSERT(std::is_unsigned<Int>::value || value >= 0, "negative value");
411 return static_cast<make_unsigned_t<Int>>(value);
412}
413
414// A heuristic to detect std::string and std::[experimental::]string_view.
415// It is mainly used to avoid dependency on <[experimental/]string_view>.
416template <typename T, typename Enable = void>
417struct is_std_string_like : std::false_type {};
418template <typename T>
419struct is_std_string_like<T, void_t<decltype(std::declval<T>().find_first_of(
420 typename T::value_type(), 0))>>
421 : std::true_type {};
422
423// Returns true iff the literal encoding is UTF-8.
424constexpr auto is_utf8_enabled() -> bool {
425 // Avoid an MSVC sign extension bug: https://github.com/fmtlib/fmt/pull/2297.
426 using uchar = unsigned char;
427 return sizeof("\u00A7") == 3 && uchar("\u00A7"[0]) == 0xC2 &&
428 uchar("\u00A7"[1]) == 0xA7;
429}
430constexpr auto use_utf8() -> bool {
431 return !FMT_MSC_VERSION || is_utf8_enabled();
432}
433
434static_assert(!FMT_UNICODE || use_utf8(),
435 "Unicode support requires compiling with /utf-8");
436
437template <typename Char> FMT_CONSTEXPR auto length(const Char* s) -> size_t {
438 size_t len = 0;
439 while (*s++) ++len;
440 return len;
441}
442
443template <typename Char>
444FMT_CONSTEXPR auto compare(const Char* s1, const Char* s2, std::size_t n)
445 -> int {
446 for (; n != 0; ++s1, ++s2, --n) {
447 if (*s1 < *s2) return -1;
448 if (*s1 > *s2) return 1;
449 }
450 return 0;
451}
452
453template <typename It, typename Enable = std::true_type>
454struct is_back_insert_iterator : std::false_type {};
455template <typename It>
457 It,
458 bool_constant<std::is_same<
459 decltype(back_inserter(std::declval<typename It::container_type&>())),
460 It>::value>> : std::true_type {};
461
462// Extracts a reference to the container from *insert_iterator.
463template <typename OutputIt>
464inline auto get_container(OutputIt it) -> typename OutputIt::container_type& {
465 struct accessor : OutputIt {
466 accessor(OutputIt base) : OutputIt(base) {}
467 using OutputIt::container;
468 };
469 return *accessor(it).container;
470}
471} // namespace detail
472
473// Checks whether T is a container with contiguous storage.
474template <typename T> struct is_contiguous : std::false_type {};
475
483FMT_EXPORT
484template <typename Char> class basic_string_view {
485 private:
486 const Char* data_;
487 size_t size_;
488
489 public:
490 using value_type = Char;
491 using iterator = const Char*;
492
493 constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {}
494
496 constexpr basic_string_view(const Char* s, size_t count) noexcept
497 : data_(s), size_(count) {}
498
499 constexpr basic_string_view(std::nullptr_t) = delete;
500
504 FMT_CONSTEXPR20
505 basic_string_view(const Char* s)
506 : data_(s),
507 size_(detail::const_check(std::is_same<Char, char>::value &&
508 !detail::is_constant_evaluated(false))
509 ? strlen(reinterpret_cast<const char*>(s))
510 : detail::length(s)) {}
511
516 template <typename S,
517 FMT_ENABLE_IF(detail::is_std_string_like<S>::value&& std::is_same<
518 typename S::value_type, Char>::value)>
519 FMT_CONSTEXPR basic_string_view(const S& s) noexcept
520 : data_(s.data()), size_(s.size()) {}
521
523 constexpr auto data() const noexcept -> const Char* { return data_; }
524
526 constexpr auto size() const noexcept -> size_t { return size_; }
527
528 constexpr auto begin() const noexcept -> iterator { return data_; }
529 constexpr auto end() const noexcept -> iterator { return data_ + size_; }
530
531 constexpr auto operator[](size_t pos) const noexcept -> const Char& {
532 return data_[pos];
533 }
534
535 FMT_CONSTEXPR void remove_prefix(size_t n) noexcept {
536 data_ += n;
537 size_ -= n;
538 }
539
540 FMT_CONSTEXPR auto starts_with(basic_string_view<Char> sv) const noexcept
541 -> bool {
542 return size_ >= sv.size_ && detail::compare(data_, sv.data_, sv.size_) == 0;
543 }
544 FMT_CONSTEXPR auto starts_with(Char c) const noexcept -> bool {
545 return size_ >= 1 && *data_ == c;
546 }
547 FMT_CONSTEXPR auto starts_with(const Char* s) const -> bool {
548 return starts_with(basic_string_view<Char>(s));
549 }
550
551 // Lexicographically compare this string reference to other.
552 FMT_CONSTEXPR auto compare(basic_string_view other) const -> int {
553 size_t str_size = size_ < other.size_ ? size_ : other.size_;
554 int result = detail::compare(data_, other.data_, str_size);
555 if (result == 0)
556 result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
557 return result;
558 }
559
560 FMT_CONSTEXPR friend auto operator==(basic_string_view lhs,
561 basic_string_view rhs) -> bool {
562 return lhs.compare(rhs) == 0;
563 }
564 friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool {
565 return lhs.compare(rhs) != 0;
566 }
567 friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool {
568 return lhs.compare(rhs) < 0;
569 }
570 friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool {
571 return lhs.compare(rhs) <= 0;
572 }
573 friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool {
574 return lhs.compare(rhs) > 0;
575 }
576 friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool {
577 return lhs.compare(rhs) >= 0;
578 }
579};
580
581FMT_EXPORT
583
585FMT_EXPORT
586template <typename T> struct is_char : std::false_type {};
587template <> struct is_char<char> : std::true_type {};
588
589namespace detail {
590
591// Constructs fmt::basic_string_view<Char> from types implicitly convertible
592// to it, deducing Char. Explicitly convertible types such as the ones returned
593// from FMT_STRING are intentionally excluded.
594template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
595auto to_string_view(const Char* s) -> basic_string_view<Char> {
596 return s;
597}
598template <typename T, FMT_ENABLE_IF(is_std_string_like<T>::value)>
599auto to_string_view(const T& s) -> basic_string_view<typename T::value_type> {
600 return s;
601}
602template <typename Char>
603constexpr auto to_string_view(basic_string_view<Char> s)
605 return s;
606}
607
608template <typename T, typename Enable = void>
609struct has_to_string_view : std::false_type {};
610// detail:: is intentional since to_string_view is not an extension point.
611template <typename T>
613 T, void_t<decltype(detail::to_string_view(std::declval<T>()))>>
614 : std::true_type {};
615
616template <typename Char, Char... C> struct string_literal {
617 static constexpr Char value[sizeof...(C)] = {C...};
618 constexpr operator basic_string_view<Char>() const {
619 return {value, sizeof...(C)};
620 }
621};
622#if FMT_CPLUSPLUS < 201703L
623template <typename Char, Char... C>
624constexpr Char string_literal<Char, C...>::value[sizeof...(C)];
625#endif
626
627enum class type {
628 none_type,
629 // Integer types should go first,
630 int_type,
631 uint_type,
632 long_long_type,
633 ulong_long_type,
634 int128_type,
635 uint128_type,
636 bool_type,
637 char_type,
638 last_integer_type = char_type,
639 // followed by floating-point types.
640 float_type,
641 double_type,
642 long_double_type,
643 last_numeric_type = long_double_type,
644 cstring_type,
645 string_type,
646 pointer_type,
647 custom_type
648};
649
650// Maps core type T to the corresponding type enum constant.
651template <typename T, typename Char>
652struct type_constant : std::integral_constant<type, type::custom_type> {};
653
654#define FMT_TYPE_CONSTANT(Type, constant) \
655 template <typename Char> \
656 struct type_constant<Type, Char> \
657 : std::integral_constant<type, type::constant> {}
658
659FMT_TYPE_CONSTANT(int, int_type);
660FMT_TYPE_CONSTANT(unsigned, uint_type);
661FMT_TYPE_CONSTANT(long long, long_long_type);
662FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
663FMT_TYPE_CONSTANT(int128_opt, int128_type);
664FMT_TYPE_CONSTANT(uint128_opt, uint128_type);
665FMT_TYPE_CONSTANT(bool, bool_type);
666FMT_TYPE_CONSTANT(Char, char_type);
667FMT_TYPE_CONSTANT(float, float_type);
668FMT_TYPE_CONSTANT(double, double_type);
669FMT_TYPE_CONSTANT(long double, long_double_type);
670FMT_TYPE_CONSTANT(const Char*, cstring_type);
671FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
672FMT_TYPE_CONSTANT(const void*, pointer_type);
673
674constexpr auto is_integral_type(type t) -> bool {
675 return t > type::none_type && t <= type::last_integer_type;
676}
677constexpr auto is_arithmetic_type(type t) -> bool {
678 return t > type::none_type && t <= type::last_numeric_type;
679}
680
681constexpr auto set(type rhs) -> int { return 1 << static_cast<int>(rhs); }
682constexpr auto in(type t, int set) -> bool {
683 return ((set >> static_cast<int>(t)) & 1) != 0;
684}
685
686// Bitsets of types.
687enum {
688 sint_set =
689 set(type::int_type) | set(type::long_long_type) | set(type::int128_type),
690 uint_set = set(type::uint_type) | set(type::ulong_long_type) |
691 set(type::uint128_type),
692 bool_set = set(type::bool_type),
693 char_set = set(type::char_type),
694 float_set = set(type::float_type) | set(type::double_type) |
695 set(type::long_double_type),
696 string_set = set(type::string_type),
697 cstring_set = set(type::cstring_type),
698 pointer_set = set(type::pointer_type)
699};
700} // namespace detail
701
706// This function is intentionally not constexpr to give a compile-time error.
707FMT_NORETURN FMT_API void report_error(const char* message);
708
709FMT_DEPRECATED FMT_NORETURN inline void throw_format_error(
710 const char* message) {
711 report_error(message);
712}
713
715template <typename S,
716 typename V = decltype(detail::to_string_view(std::declval<S>()))>
717using char_t = typename V::value_type;
718
726FMT_EXPORT
727template <typename Char> class basic_format_parse_context {
728 private:
729 basic_string_view<Char> format_str_;
730 int next_arg_id_;
731
732 FMT_CONSTEXPR void do_check_arg_id(int id);
733
734 public:
735 using char_type = Char;
736 using iterator = const Char*;
737
738 explicit constexpr basic_format_parse_context(
739 basic_string_view<Char> format_str, int next_arg_id = 0)
740 : format_str_(format_str), next_arg_id_(next_arg_id) {}
741
746 constexpr auto begin() const noexcept -> iterator {
747 return format_str_.begin();
748 }
749
753 constexpr auto end() const noexcept -> iterator { return format_str_.end(); }
754
756 FMT_CONSTEXPR void advance_to(iterator it) {
757 format_str_.remove_prefix(detail::to_unsigned(it - begin()));
758 }
759
764 FMT_CONSTEXPR auto next_arg_id() -> int {
765 if (next_arg_id_ < 0) {
766 report_error("cannot switch from manual to automatic argument indexing");
767 return 0;
768 }
769 int id = next_arg_id_++;
770 do_check_arg_id(id);
771 return id;
772 }
773
778 FMT_CONSTEXPR void check_arg_id(int id) {
779 if (next_arg_id_ > 0) {
780 report_error("cannot switch from automatic to manual argument indexing");
781 return;
782 }
783 next_arg_id_ = -1;
784 do_check_arg_id(id);
785 }
786 FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {
787 next_arg_id_ = -1;
788 }
789 FMT_CONSTEXPR void check_dynamic_spec(int arg_id);
790};
791
792FMT_EXPORT
794
795namespace detail {
796// A parse context with extra data used only in compile-time checks.
797template <typename Char>
799 private:
800 int num_args_;
801 const type* types_;
803
804 public:
805 explicit FMT_CONSTEXPR compile_parse_context(
806 basic_string_view<Char> format_str, int num_args, const type* types,
807 int next_arg_id = 0)
808 : base(format_str, next_arg_id), num_args_(num_args), types_(types) {}
809
810 constexpr auto num_args() const -> int { return num_args_; }
811 constexpr auto arg_type(int id) const -> type { return types_[id]; }
812
813 FMT_CONSTEXPR auto next_arg_id() -> int {
814 int id = base::next_arg_id();
815 if (id >= num_args_) report_error("argument not found");
816 return id;
817 }
818
819 FMT_CONSTEXPR void check_arg_id(int id) {
820 base::check_arg_id(id);
821 if (id >= num_args_) report_error("argument not found");
822 }
823 using base::check_arg_id;
824
825 FMT_CONSTEXPR void check_dynamic_spec(int arg_id) {
826 detail::ignore_unused(arg_id);
827 if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id]))
828 report_error("width/precision is not integer");
829 }
830};
831
838template <typename T> class buffer {
839 private:
840 T* ptr_;
841 size_t size_;
842 size_t capacity_;
843
844 using grow_fun = void (*)(buffer& buf, size_t capacity);
845 grow_fun grow_;
846
847 protected:
848 // Don't initialize ptr_ since it is not accessed to save a few cycles.
849 FMT_MSC_WARNING(suppress : 26495)
850 FMT_CONSTEXPR20 buffer(grow_fun grow, size_t sz) noexcept
851 : size_(sz), capacity_(sz), grow_(grow) {}
852
853 constexpr buffer(grow_fun grow, T* p = nullptr, size_t sz = 0,
854 size_t cap = 0) noexcept
855 : ptr_(p), size_(sz), capacity_(cap), grow_(grow) {}
856
857 FMT_CONSTEXPR20 ~buffer() = default;
858 buffer(buffer&&) = default;
859
861 FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept {
862 ptr_ = buf_data;
863 capacity_ = buf_capacity;
864 }
865
866 public:
867 using value_type = T;
868 using const_reference = const T&;
869
870 buffer(const buffer&) = delete;
871 void operator=(const buffer&) = delete;
872
873 auto begin() noexcept -> T* { return ptr_; }
874 auto end() noexcept -> T* { return ptr_ + size_; }
875
876 auto begin() const noexcept -> const T* { return ptr_; }
877 auto end() const noexcept -> const T* { return ptr_ + size_; }
878
880 constexpr auto size() const noexcept -> size_t { return size_; }
881
883 constexpr auto capacity() const noexcept -> size_t { return capacity_; }
884
886 FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; }
887 FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; }
888
890 void clear() { size_ = 0; }
891
892 // Tries resizing the buffer to contain *count* elements. If T is a POD type
893 // the new elements may not be initialized.
894 FMT_CONSTEXPR void try_resize(size_t count) {
895 try_reserve(count);
896 size_ = count <= capacity_ ? count : capacity_;
897 }
898
899 // Tries increasing the buffer capacity to *new_capacity*. It can increase the
900 // capacity by a smaller amount than requested but guarantees there is space
901 // for at least one additional element either by increasing the capacity or by
902 // flushing the buffer if it is full.
903 FMT_CONSTEXPR void try_reserve(size_t new_capacity) {
904 if (new_capacity > capacity_) grow_(*this, new_capacity);
905 }
906
907 FMT_CONSTEXPR void push_back(const T& value) {
908 try_reserve(size_ + 1);
909 ptr_[size_++] = value;
910 }
911
913 template <typename U> void append(const U* begin, const U* end) {
914 while (begin != end) {
915 auto count = to_unsigned(end - begin);
916 try_reserve(size_ + count);
917 auto free_cap = capacity_ - size_;
918 if (free_cap < count) count = free_cap;
919 if (std::is_same<T, U>::value) {
920 memcpy(ptr_ + size_, begin, count * sizeof(T));
921 } else {
922 T* out = ptr_ + size_;
923 for (size_t i = 0; i < count; ++i) out[i] = begin[i];
924 }
925 size_ += count;
926 begin += count;
927 }
928 }
929
930 template <typename Idx> FMT_CONSTEXPR auto operator[](Idx index) -> T& {
931 return ptr_[index];
932 }
933 template <typename Idx>
934 FMT_CONSTEXPR auto operator[](Idx index) const -> const T& {
935 return ptr_[index];
936 }
937};
938
940 explicit buffer_traits(size_t) {}
941 auto count() const -> size_t { return 0; }
942 auto limit(size_t size) -> size_t { return size; }
943};
944
946 private:
947 size_t count_ = 0;
948 size_t limit_;
949
950 public:
951 explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}
952 auto count() const -> size_t { return count_; }
953 auto limit(size_t size) -> size_t {
954 size_t n = limit_ > count_ ? limit_ - count_ : 0;
955 count_ += size;
956 return size < n ? size : n;
957 }
958};
959
960// A buffer that writes to an output iterator when flushed.
961template <typename OutputIt, typename T, typename Traits = buffer_traits>
962class iterator_buffer : public Traits, public buffer<T> {
963 private:
964 OutputIt out_;
965 enum { buffer_size = 256 };
966 T data_[buffer_size];
967
968 static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
969 if (buf.size() == buffer_size) static_cast<iterator_buffer&>(buf).flush();
970 }
971
972 void flush() {
973 auto size = this->size();
974 this->clear();
975 const T* begin = data_;
976 const T* end = begin + this->limit(size);
977 while (begin != end) *out_++ = *begin++;
978 }
979
980 public:
981 explicit iterator_buffer(OutputIt out, size_t n = buffer_size)
982 : Traits(n), buffer<T>(grow, data_, 0, buffer_size), out_(out) {}
983 iterator_buffer(iterator_buffer&& other) noexcept
984 : Traits(other),
985 buffer<T>(grow, data_, 0, buffer_size),
986 out_(other.out_) {}
988 // Don't crash if flush fails during unwinding.
989 FMT_TRY { flush(); }
990 FMT_CATCH(...) {}
991 }
992
993 auto out() -> OutputIt {
994 flush();
995 return out_;
996 }
997 auto count() const -> size_t { return Traits::count() + this->size(); }
998};
999
1000template <typename T>
1002 public buffer<T> {
1003 private:
1004 T* out_;
1005 enum { buffer_size = 256 };
1006 T data_[buffer_size];
1007
1008 static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
1009 if (buf.size() == buf.capacity())
1010 static_cast<iterator_buffer&>(buf).flush();
1011 }
1012
1013 void flush() {
1014 size_t n = this->limit(this->size());
1015 if (this->data() == out_) {
1016 out_ += n;
1017 this->set(data_, buffer_size);
1018 }
1019 this->clear();
1020 }
1021
1022 public:
1023 explicit iterator_buffer(T* out, size_t n = buffer_size)
1024 : fixed_buffer_traits(n), buffer<T>(grow, out, 0, n), out_(out) {}
1025 iterator_buffer(iterator_buffer&& other) noexcept
1026 : fixed_buffer_traits(other),
1027 buffer<T>(static_cast<iterator_buffer&&>(other)),
1028 out_(other.out_) {
1029 if (this->data() != out_) {
1030 this->set(data_, buffer_size);
1031 this->clear();
1032 }
1033 }
1034 ~iterator_buffer() { flush(); }
1035
1036 auto out() -> T* {
1037 flush();
1038 return out_;
1039 }
1040 auto count() const -> size_t {
1041 return fixed_buffer_traits::count() + this->size();
1042 }
1043};
1044
1045template <typename T> class iterator_buffer<T*, T> : public buffer<T> {
1046 public:
1047 explicit iterator_buffer(T* out, size_t = 0)
1048 : buffer<T>([](buffer<T>&, size_t) {}, out, 0, ~size_t()) {}
1049
1050 auto out() -> T* { return &*this->end(); }
1051};
1052
1053// A buffer that writes to a container with the contiguous storage.
1054template <typename OutputIt>
1056 OutputIt,
1057 enable_if_t<detail::is_back_insert_iterator<OutputIt>::value &&
1058 is_contiguous<typename OutputIt::container_type>::value,
1059 typename OutputIt::container_type::value_type>>
1060 : public buffer<typename OutputIt::container_type::value_type> {
1061 private:
1062 using container_type = typename OutputIt::container_type;
1063 using value_type = typename container_type::value_type;
1064 container_type& container_;
1065
1066 static FMT_CONSTEXPR void grow(buffer<value_type>& buf, size_t capacity) {
1067 auto& self = static_cast<iterator_buffer&>(buf);
1068 self.container_.resize(capacity);
1069 self.set(&self.container_[0], capacity);
1070 }
1071
1072 public:
1073 explicit iterator_buffer(container_type& c)
1074 : buffer<value_type>(grow, c.size()), container_(c) {}
1075 explicit iterator_buffer(OutputIt out, size_t = 0)
1076 : iterator_buffer(get_container(out)) {}
1077
1078 auto out() -> OutputIt { return back_inserter(container_); }
1079};
1080
1081// A buffer that counts the number of code units written discarding the output.
1082template <typename T = char> class counting_buffer : public buffer<T> {
1083 private:
1084 enum { buffer_size = 256 };
1085 T data_[buffer_size];
1086 size_t count_ = 0;
1087
1088 static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
1089 if (buf.size() != buffer_size) return;
1090 static_cast<counting_buffer&>(buf).count_ += buf.size();
1091 buf.clear();
1092 }
1093
1094 public:
1095 counting_buffer() : buffer<T>(grow, data_, 0, buffer_size) {}
1096
1097 auto count() -> size_t { return count_ + this->size(); }
1098};
1099} // namespace detail
1100
1101template <typename Char>
1102FMT_CONSTEXPR void basic_format_parse_context<Char>::do_check_arg_id(int id) {
1103 // Argument id is only checked at compile-time during parsing because
1104 // formatting has its own validation.
1105 if (detail::is_constant_evaluated() &&
1106 (!FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200)) {
1108 if (id >= static_cast<context*>(this)->num_args())
1109 report_error("argument not found");
1110 }
1111}
1112
1113template <typename Char>
1115 int arg_id) {
1116 if (detail::is_constant_evaluated() &&
1117 (!FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200)) {
1119 static_cast<context*>(this)->check_dynamic_spec(arg_id);
1120 }
1121}
1122
1123FMT_EXPORT template <typename Context> class basic_format_arg;
1124FMT_EXPORT template <typename Context> class basic_format_args;
1125FMT_EXPORT template <typename Context> class dynamic_format_arg_store;
1126
1127// A formatter for objects of type T.
1128FMT_EXPORT
1129template <typename T, typename Char = char, typename Enable = void>
1131 // A deleted default constructor indicates a disabled formatter.
1132 formatter() = delete;
1133};
1134
1135// Specifies if T has an enabled formatter specialization. A type can be
1136// formattable even if it doesn't have a formatter e.g. via a conversion.
1137template <typename T, typename Context>
1138using has_formatter =
1139 std::is_constructible<typename Context::template formatter_type<T>>;
1140
1141// An output iterator that appends to a buffer. It is used instead of
1142// back_insert_iterator to reduce symbol sizes and avoid <iterator> dependency.
1143template <typename T> class basic_appender {
1144 private:
1145 detail::buffer<T>* buffer_;
1146
1147 friend auto get_container(basic_appender app) -> detail::buffer<T>& {
1148 return *app.buffer_;
1149 }
1150
1151 public:
1152 using iterator_category = int;
1153 using value_type = T;
1154 using difference_type = ptrdiff_t;
1155 using pointer = T*;
1156 using reference = T&;
1157 FMT_UNCHECKED_ITERATOR(basic_appender);
1158
1159 FMT_CONSTEXPR basic_appender(detail::buffer<T>& buf) : buffer_(&buf) {}
1160
1161 auto operator=(T c) -> basic_appender& {
1162 buffer_->push_back(c);
1163 return *this;
1164 }
1165 auto operator*() -> basic_appender& { return *this; }
1166 auto operator++() -> basic_appender& { return *this; }
1167 auto operator++(int) -> basic_appender { return *this; }
1168};
1169
1171
1172namespace detail {
1173
1174template <typename T, typename Enable = void>
1175struct locking : std::true_type {};
1176template <typename T>
1177struct locking<T, void_t<typename formatter<remove_cvref_t<T>>::nonlocking>>
1178 : std::false_type {};
1179
1180template <typename T = int> FMT_CONSTEXPR inline auto is_locking() -> bool {
1181 return locking<T>::value;
1182}
1183template <typename T1, typename T2, typename... Tail>
1184FMT_CONSTEXPR inline auto is_locking() -> bool {
1185 return locking<T1>::value || is_locking<T2, Tail...>();
1186}
1187
1188// An optimized version of std::copy with the output value type (T).
1189template <typename T, typename InputIt>
1190auto copy(InputIt begin, InputIt end, appender out) -> appender {
1191 get_container(out).append(begin, end);
1192 return out;
1193}
1194
1195template <typename T, typename InputIt, typename OutputIt,
1196 FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value)>
1197auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt {
1198 get_container(out).append(begin, end);
1199 return out;
1200}
1201
1202template <typename T, typename InputIt, typename OutputIt,
1203 FMT_ENABLE_IF(!is_back_insert_iterator<OutputIt>::value)>
1204FMT_CONSTEXPR auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt {
1205 while (begin != end) *out++ = static_cast<T>(*begin++);
1206 return out;
1207}
1208
1209template <typename T>
1210FMT_CONSTEXPR auto copy(const T* begin, const T* end, T* out) -> T* {
1211 if (is_constant_evaluated()) return copy<T, const T*, T*>(begin, end, out);
1212 auto size = to_unsigned(end - begin);
1213 if (size > 0) memcpy(out, begin, size * sizeof(T));
1214 return out + size;
1215}
1216
1217template <typename T, typename V, typename OutputIt>
1218FMT_CONSTEXPR auto copy(basic_string_view<V> s, OutputIt out) -> OutputIt {
1219 return copy<T>(s.begin(), s.end(), out);
1220}
1221
1222template <typename Context, typename T>
1223constexpr auto has_const_formatter_impl(T*)
1224 -> decltype(typename Context::template formatter_type<T>().format(
1225 std::declval<const T&>(), std::declval<Context&>()),
1226 true) {
1227 return true;
1228}
1229template <typename Context>
1230constexpr auto has_const_formatter_impl(...) -> bool {
1231 return false;
1232}
1233template <typename T, typename Context>
1234constexpr auto has_const_formatter() -> bool {
1235 return has_const_formatter_impl<Context>(static_cast<T*>(nullptr));
1236}
1237
1238// Maps an output iterator to a buffer.
1239template <typename T, typename OutputIt>
1240auto get_buffer(OutputIt out) -> iterator_buffer<OutputIt, T> {
1241 return iterator_buffer<OutputIt, T>(out);
1242}
1243template <typename T> auto get_buffer(basic_appender<T> out) -> buffer<T>& {
1244 return get_container(out);
1245}
1246
1247template <typename Buf, typename OutputIt>
1248auto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) {
1249 return buf.out();
1250}
1251template <typename T, typename OutputIt>
1252auto get_iterator(buffer<T>&, OutputIt out) -> OutputIt {
1253 return out;
1254}
1255
1256struct view {};
1257
1258template <typename Char, typename T> struct named_arg : view {
1259 const Char* name;
1260 const T& value;
1261 named_arg(const Char* n, const T& v) : name(n), value(v) {}
1262};
1263
1264template <typename Char> struct named_arg_info {
1265 const Char* name;
1266 int id;
1267};
1268
1269template <typename T> struct is_named_arg : std::false_type {};
1270template <typename T> struct is_statically_named_arg : std::false_type {};
1271
1272template <typename T, typename Char>
1273struct is_named_arg<named_arg<Char, T>> : std::true_type {};
1274
1275template <bool B = false> constexpr auto count() -> size_t { return B ? 1 : 0; }
1276template <bool B1, bool B2, bool... Tail> constexpr auto count() -> size_t {
1277 return (B1 ? 1 : 0) + count<B2, Tail...>();
1278}
1279
1280template <typename... Args> constexpr auto count_named_args() -> size_t {
1281 return count<is_named_arg<Args>::value...>();
1282}
1283
1284template <typename... Args>
1285constexpr auto count_statically_named_args() -> size_t {
1286 return count<is_statically_named_arg<Args>::value...>();
1287}
1288
1292
1293template <typename Char> struct string_value {
1294 const Char* data;
1295 size_t size;
1296};
1297
1298template <typename Char> struct named_arg_value {
1299 const named_arg_info<Char>* data;
1300 size_t size;
1301};
1302
1303template <typename Context> struct custom_value {
1304 using parse_context = typename Context::parse_context_type;
1305 void* value;
1306 void (*format)(void* arg, parse_context& parse_ctx, Context& ctx);
1307};
1308
1309// A formatting argument value.
1310template <typename Context> class value {
1311 public:
1312 using char_type = typename Context::char_type;
1313
1314 union {
1315 monostate no_value;
1316 int int_value;
1317 unsigned uint_value;
1318 long long long_long_value;
1319 unsigned long long ulong_long_value;
1320 int128_opt int128_value;
1321 uint128_opt uint128_value;
1322 bool bool_value;
1323 char_type char_value;
1324 float float_value;
1325 double double_value;
1326 long double long_double_value;
1327 const void* pointer;
1329 custom_value<Context> custom;
1330 named_arg_value<char_type> named_args;
1331 };
1332
1333 constexpr FMT_ALWAYS_INLINE value() : no_value() {}
1334 constexpr FMT_ALWAYS_INLINE value(int val) : int_value(val) {}
1335 constexpr FMT_ALWAYS_INLINE value(unsigned val) : uint_value(val) {}
1336 constexpr FMT_ALWAYS_INLINE value(long long val) : long_long_value(val) {}
1337 constexpr FMT_ALWAYS_INLINE value(unsigned long long val)
1338 : ulong_long_value(val) {}
1339 FMT_ALWAYS_INLINE value(int128_opt val) : int128_value(val) {}
1340 FMT_ALWAYS_INLINE value(uint128_opt val) : uint128_value(val) {}
1341 constexpr FMT_ALWAYS_INLINE value(float val) : float_value(val) {}
1342 constexpr FMT_ALWAYS_INLINE value(double val) : double_value(val) {}
1343 FMT_ALWAYS_INLINE value(long double val) : long_double_value(val) {}
1344 constexpr FMT_ALWAYS_INLINE value(bool val) : bool_value(val) {}
1345 constexpr FMT_ALWAYS_INLINE value(char_type val) : char_value(val) {}
1346 FMT_CONSTEXPR FMT_ALWAYS_INLINE value(const char_type* val) {
1347 string.data = val;
1348 if (is_constant_evaluated()) string.size = {};
1349 }
1350 FMT_CONSTEXPR FMT_ALWAYS_INLINE value(basic_string_view<char_type> val) {
1351 string.data = val.data();
1352 string.size = val.size();
1353 }
1354 FMT_ALWAYS_INLINE value(const void* val) : pointer(val) {}
1355 FMT_ALWAYS_INLINE value(const named_arg_info<char_type>* args, size_t size)
1356 : named_args{args, size} {}
1357
1358 template <typename T> FMT_CONSTEXPR20 FMT_ALWAYS_INLINE value(T& val) {
1359 using value_type = remove_const_t<T>;
1360 // T may overload operator& e.g. std::vector<bool>::reference in libc++.
1361#if defined(__cpp_if_constexpr)
1362 if constexpr (std::is_same<decltype(&val), T*>::value)
1363 custom.value = const_cast<value_type*>(&val);
1364#endif
1365 if (!is_constant_evaluated())
1366 custom.value = const_cast<char*>(&reinterpret_cast<const char&>(val));
1367 // Get the formatter type through the context to allow different contexts
1368 // have different extension points, e.g. `formatter<T>` for `format` and
1369 // `printf_formatter<T>` for `printf`.
1370 custom.format = format_custom_arg<
1371 value_type, typename Context::template formatter_type<value_type>>;
1372 }
1376
1377 private:
1378 // Formats an argument of a custom type, such as a user-defined class.
1379 template <typename T, typename Formatter>
1380 static void format_custom_arg(void* arg,
1381 typename Context::parse_context_type& parse_ctx,
1382 Context& ctx) {
1383 auto f = Formatter();
1384 parse_ctx.advance_to(f.parse(parse_ctx));
1385 using qualified_type =
1386 conditional_t<has_const_formatter<T, Context>(), const T, T>;
1387 // format must be const for compatibility with std::format and compilation.
1388 const auto& cf = f;
1389 ctx.advance_to(cf.format(*static_cast<qualified_type*>(arg), ctx));
1390 }
1391};
1392
1393// To minimize the number of types we need to deal with, long is translated
1394// either to int or to long long depending on its size.
1395enum { long_short = sizeof(long) == sizeof(int) };
1396using long_type = conditional_t<long_short, int, long long>;
1397using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
1398
1399template <typename T> struct format_as_result {
1400 template <typename U,
1401 FMT_ENABLE_IF(std::is_enum<U>::value || std::is_class<U>::value)>
1402 static auto map(U*) -> remove_cvref_t<decltype(format_as(std::declval<U>()))>;
1403 static auto map(...) -> void;
1404
1405 using type = decltype(map(static_cast<T*>(nullptr)));
1406};
1407template <typename T> using format_as_t = typename format_as_result<T>::type;
1408
1409template <typename T>
1411 : bool_constant<!std::is_same<format_as_t<T>, void>::value> {};
1412
1413#define FMT_MAP_API FMT_CONSTEXPR FMT_ALWAYS_INLINE
1414
1415// Maps formatting arguments to core types.
1416// arg_mapper reports errors by returning unformattable instead of using
1417// static_assert because it's used in the is_formattable trait.
1418template <typename Context> struct arg_mapper {
1419 using char_type = typename Context::char_type;
1420
1421 FMT_MAP_API auto map(signed char val) -> int { return val; }
1422 FMT_MAP_API auto map(unsigned char val) -> unsigned { return val; }
1423 FMT_MAP_API auto map(short val) -> int { return val; }
1424 FMT_MAP_API auto map(unsigned short val) -> unsigned { return val; }
1425 FMT_MAP_API auto map(int val) -> int { return val; }
1426 FMT_MAP_API auto map(unsigned val) -> unsigned { return val; }
1427 FMT_MAP_API auto map(long val) -> long_type { return val; }
1428 FMT_MAP_API auto map(unsigned long val) -> ulong_type { return val; }
1429 FMT_MAP_API auto map(long long val) -> long long { return val; }
1430 FMT_MAP_API auto map(unsigned long long val) -> unsigned long long {
1431 return val;
1432 }
1433 FMT_MAP_API auto map(int128_opt val) -> int128_opt { return val; }
1434 FMT_MAP_API auto map(uint128_opt val) -> uint128_opt { return val; }
1435 FMT_MAP_API auto map(bool val) -> bool { return val; }
1436
1437 template <typename T, FMT_ENABLE_IF(std::is_same<T, char>::value ||
1438 std::is_same<T, char_type>::value)>
1439 FMT_MAP_API auto map(T val) -> char_type {
1440 return val;
1441 }
1442 template <typename T, enable_if_t<(std::is_same<T, wchar_t>::value ||
1443#ifdef __cpp_char8_t
1444 std::is_same<T, char8_t>::value ||
1445#endif
1446 std::is_same<T, char16_t>::value ||
1447 std::is_same<T, char32_t>::value) &&
1448 !std::is_same<T, char_type>::value,
1449 int> = 0>
1450 FMT_MAP_API auto map(T) -> unformattable_char {
1451 return {};
1452 }
1453
1454 FMT_MAP_API auto map(float val) -> float { return val; }
1455 FMT_MAP_API auto map(double val) -> double { return val; }
1456 FMT_MAP_API auto map(long double val) -> long double { return val; }
1457
1458 FMT_MAP_API auto map(char_type* val) -> const char_type* { return val; }
1459 FMT_MAP_API auto map(const char_type* val) -> const char_type* { return val; }
1460 template <typename T, typename Char = char_t<T>,
1461 FMT_ENABLE_IF(std::is_same<Char, char_type>::value &&
1462 !std::is_pointer<T>::value)>
1463 FMT_MAP_API auto map(const T& val) -> basic_string_view<Char> {
1464 return to_string_view(val);
1465 }
1466 template <typename T, typename Char = char_t<T>,
1467 FMT_ENABLE_IF(!std::is_same<Char, char_type>::value &&
1468 !std::is_pointer<T>::value)>
1469 FMT_MAP_API auto map(const T&) -> unformattable_char {
1470 return {};
1471 }
1472
1473 FMT_MAP_API auto map(void* val) -> const void* { return val; }
1474 FMT_MAP_API auto map(const void* val) -> const void* { return val; }
1475 FMT_MAP_API auto map(std::nullptr_t val) -> const void* { return val; }
1476
1477 // Use SFINAE instead of a const T* parameter to avoid a conflict with the
1478 // array overload.
1479 template <
1480 typename T,
1481 FMT_ENABLE_IF(
1482 std::is_pointer<T>::value || std::is_member_pointer<T>::value ||
1483 std::is_function<typename std::remove_pointer<T>::type>::value ||
1484 (std::is_array<T>::value &&
1485 !std::is_convertible<T, const char_type*>::value))>
1486 FMT_CONSTEXPR auto map(const T&) -> unformattable_pointer {
1487 return {};
1488 }
1489
1490 template <typename T, std::size_t N,
1491 FMT_ENABLE_IF(!std::is_same<T, wchar_t>::value)>
1492 FMT_MAP_API auto map(const T (&values)[N]) -> const T (&)[N] {
1493 return values;
1494 }
1495
1496 // Only map owning types because mapping views can be unsafe.
1497 template <typename T, typename U = format_as_t<T>,
1498 FMT_ENABLE_IF(std::is_arithmetic<U>::value)>
1499 FMT_MAP_API auto map(const T& val) -> decltype(FMT_DECLTYPE_THIS map(U())) {
1500 return map(format_as(val));
1501 }
1502
1503 template <typename T, typename U = remove_const_t<T>>
1504 struct formattable : bool_constant<has_const_formatter<U, Context>() ||
1505 (has_formatter<U, Context>::value &&
1506 !std::is_const<T>::value)> {};
1507
1508 template <typename T, FMT_ENABLE_IF(formattable<T>::value)>
1509 FMT_MAP_API auto do_map(T& val) -> T& {
1510 return val;
1511 }
1512 template <typename T, FMT_ENABLE_IF(!formattable<T>::value)>
1513 FMT_MAP_API auto do_map(T&) -> unformattable {
1514 return {};
1515 }
1516
1517 // is_fundamental is used to allow formatters for extended FP types.
1518 template <typename T, typename U = remove_const_t<T>,
1519 FMT_ENABLE_IF(
1520 (std::is_class<U>::value || std::is_enum<U>::value ||
1521 std::is_union<U>::value || std::is_fundamental<U>::value) &&
1522 !has_to_string_view<U>::value && !is_char<U>::value &&
1523 !is_named_arg<U>::value && !std::is_integral<U>::value &&
1524 !std::is_arithmetic<format_as_t<U>>::value)>
1525 FMT_MAP_API auto map(T& val) -> decltype(FMT_DECLTYPE_THIS do_map(val)) {
1526 return do_map(val);
1527 }
1528
1529 template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
1530 FMT_MAP_API auto map(const T& named_arg)
1531 -> decltype(FMT_DECLTYPE_THIS map(named_arg.value)) {
1532 return map(named_arg.value);
1533 }
1534
1535 auto map(...) -> unformattable { return {}; }
1536};
1537
1538// A type constant after applying arg_mapper<Context>.
1539template <typename T, typename Context>
1540using mapped_type_constant =
1541 type_constant<decltype(arg_mapper<Context>().map(std::declval<const T&>())),
1542 typename Context::char_type>;
1543
1544enum { packed_arg_bits = 4 };
1545// Maximum number of arguments with packed types.
1546enum { max_packed_args = 62 / packed_arg_bits };
1547enum : unsigned long long { is_unpacked_bit = 1ULL << 63 };
1548enum : unsigned long long { has_named_args_bit = 1ULL << 62 };
1549
1550template <typename It, typename T, typename Enable = void>
1551struct is_output_iterator : std::false_type {};
1552
1553template <> struct is_output_iterator<appender, char> : std::true_type {};
1554
1555template <typename It, typename T>
1557 It, T, void_t<decltype(*std::declval<It&>()++ = std::declval<T>())>>
1558 : std::true_type {};
1559
1560// A type-erased reference to an std::locale to avoid a heavy <locale> include.
1562 private:
1563 const void* locale_; // A type-erased pointer to std::locale.
1564
1565 public:
1566 constexpr locale_ref() : locale_(nullptr) {}
1567 template <typename Locale> explicit locale_ref(const Locale& loc);
1568
1569 explicit operator bool() const noexcept { return locale_ != nullptr; }
1570
1571 template <typename Locale> auto get() const -> Locale;
1572};
1573
1574template <typename> constexpr auto encode_types() -> unsigned long long {
1575 return 0;
1576}
1577
1578template <typename Context, typename Arg, typename... Args>
1579constexpr auto encode_types() -> unsigned long long {
1580 return static_cast<unsigned>(mapped_type_constant<Arg, Context>::value) |
1581 (encode_types<Context, Args...>() << packed_arg_bits);
1582}
1583
1584template <typename Context, typename... T, size_t NUM_ARGS = sizeof...(T)>
1585constexpr unsigned long long make_descriptor() {
1586 return NUM_ARGS <= max_packed_args ? encode_types<Context, T...>()
1587 : is_unpacked_bit | NUM_ARGS;
1588}
1589
1590// This type is intentionally undefined, only used for errors.
1591template <typename T, typename Char>
1592#if FMT_CLANG_VERSION && FMT_CLANG_VERSION <= 1500
1593// https://github.com/fmtlib/fmt/issues/3796
1594struct type_is_unformattable_for {
1595};
1596#else
1598#endif
1599
1600template <bool PACKED, typename Context, typename T, FMT_ENABLE_IF(PACKED)>
1601FMT_CONSTEXPR auto make_arg(T& val) -> value<Context> {
1602 using arg_type = remove_cvref_t<decltype(arg_mapper<Context>().map(val))>;
1603
1604 // Use enum instead of constexpr because the latter may generate code.
1605 enum {
1606 formattable_char = !std::is_same<arg_type, unformattable_char>::value
1607 };
1608 static_assert(formattable_char, "Mixing character types is disallowed.");
1609
1610 // Formatting of arbitrary pointers is disallowed. If you want to format a
1611 // pointer cast it to `void*` or `const void*`. In particular, this forbids
1612 // formatting of `[const] volatile char*` printed as bool by iostreams.
1613 enum {
1614 formattable_pointer = !std::is_same<arg_type, unformattable_pointer>::value
1615 };
1616 static_assert(formattable_pointer,
1617 "Formatting of non-void pointers is disallowed.");
1618
1619 enum { formattable = !std::is_same<arg_type, unformattable>::value };
1620#if defined(__cpp_if_constexpr)
1621 if constexpr (!formattable)
1623#endif
1624 static_assert(
1625 formattable,
1626 "Cannot format an argument. To make type T formattable provide a "
1627 "formatter<T> specialization: https://fmt.dev/latest/api.html#udt");
1628 return {arg_mapper<Context>().map(val)};
1629}
1630
1631template <typename Context, typename T>
1632FMT_CONSTEXPR auto make_arg(T& val) -> basic_format_arg<Context> {
1633 auto arg = basic_format_arg<Context>();
1635 arg.value_ = make_arg<true, Context>(val);
1636 return arg;
1637}
1638
1639template <bool PACKED, typename Context, typename T, FMT_ENABLE_IF(!PACKED)>
1640FMT_CONSTEXPR inline auto make_arg(T& val) -> basic_format_arg<Context> {
1641 return make_arg<Context>(val);
1642}
1643
1644template <typename Context, size_t NUM_ARGS>
1645using arg_t = conditional_t<NUM_ARGS <= max_packed_args, value<Context>,
1647
1648template <typename Char, typename T, FMT_ENABLE_IF(!is_named_arg<T>::value)>
1649void init_named_arg(named_arg_info<Char>*, int& arg_index, int&, const T&) {
1650 ++arg_index;
1651}
1652template <typename Char, typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
1653void init_named_arg(named_arg_info<Char>* named_args, int& arg_index,
1654 int& named_arg_index, const T& arg) {
1655 named_args[named_arg_index++] = {arg.name, arg_index++};
1656}
1657
1658// An array of references to arguments. It can be implicitly converted to
1659// `fmt::basic_format_args` for passing into type-erased formatting functions
1660// such as `fmt::vformat`.
1661template <typename Context, size_t NUM_ARGS, size_t NUM_NAMED_ARGS,
1662 unsigned long long DESC>
1664 // args_[0].named_args points to named_args to avoid bloating format_args.
1665 // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
1666 static constexpr size_t ARGS_ARR_SIZE = 1 + (NUM_ARGS != 0 ? NUM_ARGS : +1);
1667
1668 arg_t<Context, NUM_ARGS> args[ARGS_ARR_SIZE];
1669 named_arg_info<typename Context::char_type> named_args[NUM_NAMED_ARGS];
1670
1671 template <typename... T>
1672 FMT_MAP_API format_arg_store(T&... values)
1673 : args{{named_args, NUM_NAMED_ARGS},
1674 make_arg<NUM_ARGS <= max_packed_args, Context>(values)...} {
1675 using dummy = int[];
1676 int arg_index = 0, named_arg_index = 0;
1677 (void)dummy{
1678 0,
1679 (init_named_arg(named_args, arg_index, named_arg_index, values), 0)...};
1680 }
1681
1683 args[0] = {named_args, NUM_NAMED_ARGS};
1684 for (size_t i = 1; i < ARGS_ARR_SIZE; ++i) args[i] = rhs.args[i];
1685 for (size_t i = 0; i < NUM_NAMED_ARGS; ++i)
1686 named_args[i] = rhs.named_args[i];
1687 }
1688
1689 format_arg_store(const format_arg_store& rhs) = delete;
1690 format_arg_store& operator=(const format_arg_store& rhs) = delete;
1691 format_arg_store& operator=(format_arg_store&& rhs) = delete;
1692};
1693
1694// A specialization of format_arg_store without named arguments.
1695// It is a plain struct to reduce binary size in debug mode.
1696template <typename Context, size_t NUM_ARGS, unsigned long long DESC>
1697struct format_arg_store<Context, NUM_ARGS, 0, DESC> {
1698 // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
1699 arg_t<Context, NUM_ARGS> args[NUM_ARGS != 0 ? NUM_ARGS : +1];
1700};
1701
1702} // namespace detail
1703FMT_BEGIN_EXPORT
1704
1705// A formatting argument. Context is a template parameter for the compiled API
1706// where output can be unbuffered.
1707template <typename Context> class basic_format_arg {
1708 private:
1710 detail::type type_;
1711
1712 template <typename ContextType, typename T>
1713 friend FMT_CONSTEXPR auto detail::make_arg(T& value)
1715
1716 friend class basic_format_args<Context>;
1717 friend class dynamic_format_arg_store<Context>;
1718
1719 using char_type = typename Context::char_type;
1720
1721 template <typename, size_t, size_t, unsigned long long>
1722 friend struct detail::format_arg_store;
1723
1724 basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)
1725 : value_(args, size) {}
1726
1727 public:
1728 class handle {
1729 public:
1730 explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}
1731
1732 void format(typename Context::parse_context_type& parse_ctx,
1733 Context& ctx) const {
1734 custom_.format(custom_.value, parse_ctx, ctx);
1735 }
1736
1737 private:
1739 };
1740
1741 constexpr basic_format_arg() : type_(detail::type::none_type) {}
1742
1743 constexpr explicit operator bool() const noexcept {
1744 return type_ != detail::type::none_type;
1745 }
1746
1747 auto type() const -> detail::type { return type_; }
1748
1749 auto is_integral() const -> bool { return detail::is_integral_type(type_); }
1750 auto is_arithmetic() const -> bool {
1751 return detail::is_arithmetic_type(type_);
1752 }
1753
1761 template <typename Visitor>
1762 FMT_CONSTEXPR auto visit(Visitor&& vis) -> decltype(vis(0)) {
1763 switch (type_) {
1764 case detail::type::none_type:
1765 break;
1766 case detail::type::int_type:
1767 return vis(value_.int_value);
1768 case detail::type::uint_type:
1769 return vis(value_.uint_value);
1770 case detail::type::long_long_type:
1771 return vis(value_.long_long_value);
1772 case detail::type::ulong_long_type:
1773 return vis(value_.ulong_long_value);
1774 case detail::type::int128_type:
1775 return vis(detail::convert_for_visit(value_.int128_value));
1776 case detail::type::uint128_type:
1777 return vis(detail::convert_for_visit(value_.uint128_value));
1778 case detail::type::bool_type:
1779 return vis(value_.bool_value);
1780 case detail::type::char_type:
1781 return vis(value_.char_value);
1782 case detail::type::float_type:
1783 return vis(value_.float_value);
1784 case detail::type::double_type:
1785 return vis(value_.double_value);
1786 case detail::type::long_double_type:
1787 return vis(value_.long_double_value);
1788 case detail::type::cstring_type:
1789 return vis(value_.string.data);
1790 case detail::type::string_type:
1792 return vis(sv(value_.string.data, value_.string.size));
1793 case detail::type::pointer_type:
1794 return vis(value_.pointer);
1795 case detail::type::custom_type:
1796 return vis(typename basic_format_arg<Context>::handle(value_.custom));
1797 }
1798 return vis(monostate());
1799 }
1800
1801 auto format_custom(const char_type* parse_begin,
1802 typename Context::parse_context_type& parse_ctx,
1803 Context& ctx) -> bool {
1804 if (type_ != detail::type::custom_type) return false;
1805 parse_ctx.advance_to(parse_begin);
1806 value_.custom.format(value_.custom.value, parse_ctx, ctx);
1807 return true;
1808 }
1809};
1810
1811template <typename Visitor, typename Context>
1812FMT_DEPRECATED FMT_CONSTEXPR auto visit_format_arg(
1813 Visitor&& vis, const basic_format_arg<Context>& arg) -> decltype(vis(0)) {
1814 return arg.visit(static_cast<Visitor&&>(vis));
1815}
1816
1827template <typename Context> class basic_format_args {
1828 public:
1829 using size_type = int;
1831
1832 private:
1833 // A descriptor that contains information about formatting arguments.
1834 // If the number of arguments is less or equal to max_packed_args then
1835 // argument types are passed in the descriptor. This reduces binary code size
1836 // per formatting function call.
1837 unsigned long long desc_;
1838 union {
1839 // If is_packed() returns true then argument values are stored in values_;
1840 // otherwise they are stored in args_. This is done to improve cache
1841 // locality and reduce compiled code size since storing larger objects
1842 // may require more code (at least on x86-64) even if the same amount of
1843 // data is actually copied to stack. It saves ~10% on the bloat test.
1844 const detail::value<Context>* values_;
1845 const format_arg* args_;
1846 };
1847
1848 constexpr auto is_packed() const -> bool {
1849 return (desc_ & detail::is_unpacked_bit) == 0;
1850 }
1851 constexpr auto has_named_args() const -> bool {
1852 return (desc_ & detail::has_named_args_bit) != 0;
1853 }
1854
1855 FMT_CONSTEXPR auto type(int index) const -> detail::type {
1856 int shift = index * detail::packed_arg_bits;
1857 unsigned int mask = (1 << detail::packed_arg_bits) - 1;
1858 return static_cast<detail::type>((desc_ >> shift) & mask);
1859 }
1860
1861 public:
1862 constexpr basic_format_args() : desc_(0), args_(nullptr) {}
1863
1869 template <size_t NUM_ARGS, size_t NUM_NAMED_ARGS, unsigned long long DESC,
1870 FMT_ENABLE_IF(NUM_ARGS <= detail::max_packed_args)>
1871 constexpr FMT_ALWAYS_INLINE basic_format_args(
1873 store)
1874 : desc_(DESC), values_(store.args + (NUM_NAMED_ARGS != 0 ? 1 : 0)) {}
1875
1876 template <size_t NUM_ARGS, size_t NUM_NAMED_ARGS, unsigned long long DESC,
1877 FMT_ENABLE_IF(NUM_ARGS > detail::max_packed_args)>
1878 constexpr basic_format_args(
1880 store)
1881 : desc_(DESC), args_(store.args + (NUM_NAMED_ARGS != 0 ? 1 : 0)) {}
1882
1890 : desc_(store.get_types()), args_(store.data()) {}
1891
1897 constexpr basic_format_args(const format_arg* args, int count)
1898 : desc_(detail::is_unpacked_bit | detail::to_unsigned(count)),
1899 args_(args) {}
1900
1902 FMT_CONSTEXPR auto get(int id) const -> format_arg {
1903 format_arg arg;
1904 if (!is_packed()) {
1905 if (id < max_size()) arg = args_[id];
1906 return arg;
1907 }
1908 if (static_cast<unsigned>(id) >= detail::max_packed_args) return arg;
1909 arg.type_ = type(id);
1910 if (arg.type_ == detail::type::none_type) return arg;
1911 arg.value_ = values_[id];
1912 return arg;
1913 }
1914
1915 template <typename Char>
1916 auto get(basic_string_view<Char> name) const -> format_arg {
1917 int id = get_id(name);
1918 return id >= 0 ? get(id) : format_arg();
1919 }
1920
1921 template <typename Char>
1922 FMT_CONSTEXPR auto get_id(basic_string_view<Char> name) const -> int {
1923 if (!has_named_args()) return -1;
1924 const auto& named_args =
1925 (is_packed() ? values_[-1] : args_[-1].value_).named_args;
1926 for (size_t i = 0; i < named_args.size; ++i) {
1927 if (named_args.data[i].name == name) return named_args.data[i].id;
1928 }
1929 return -1;
1930 }
1931
1932 auto max_size() const -> int {
1933 unsigned long long max_packed = detail::max_packed_args;
1934 return static_cast<int>(is_packed() ? max_packed
1935 : desc_ & ~detail::is_unpacked_bit);
1936 }
1937};
1938
1939// A formatting context.
1940class context {
1941 private:
1942 appender out_;
1944 detail::locale_ref loc_;
1945
1946 public:
1948 using char_type = char;
1949
1950 using iterator = appender;
1953 template <typename T> using formatter_type = formatter<T, char>;
1954
1959 FMT_CONSTEXPR context(iterator out, basic_format_args<context> ctx_args,
1960 detail::locale_ref loc = {})
1961 : out_(out), args_(ctx_args), loc_(loc) {}
1962 context(context&&) = default;
1963 context(const context&) = delete;
1964 void operator=(const context&) = delete;
1965
1966 FMT_CONSTEXPR auto arg(int id) const -> format_arg { return args_.get(id); }
1967 auto arg(string_view name) -> format_arg { return args_.get(name); }
1968 FMT_CONSTEXPR auto arg_id(string_view name) -> int {
1969 return args_.get_id(name);
1970 }
1971 auto args() const -> const basic_format_args<context>& { return args_; }
1972
1973 // Returns an iterator to the beginning of the output range.
1974 FMT_CONSTEXPR auto out() -> iterator { return out_; }
1975
1976 // Advances the begin iterator to ``it``.
1977 void advance_to(iterator) {}
1978
1979 FMT_CONSTEXPR auto locale() -> detail::locale_ref { return loc_; }
1980};
1981
1982template <typename OutputIt, typename Char> class generic_context;
1983
1984// Longer aliases for C++20 compatibility.
1985template <typename OutputIt, typename Char>
1986using basic_format_context =
1987 conditional_t<std::is_same<OutputIt, appender>::value, context,
1989using format_context = context;
1990
1991template <typename Char>
1992using buffered_context = basic_format_context<basic_appender<Char>, Char>;
1993
1994template <typename T, typename Char = char>
1995using is_formattable = bool_constant<!std::is_base_of<
1997 .map(std::declval<T&>()))>::value>;
1998
2007// Take arguments by lvalue references to avoid some lifetime issues, e.g.
2008// auto args = make_format_args(std::string());
2009template <typename Context = format_context, typename... T,
2010 size_t NUM_ARGS = sizeof...(T),
2011 size_t NUM_NAMED_ARGS = detail::count_named_args<T...>(),
2012 unsigned long long DESC = detail::make_descriptor<Context, T...>(),
2013 FMT_ENABLE_IF(NUM_NAMED_ARGS == 0)>
2014constexpr FMT_ALWAYS_INLINE auto make_format_args(T&... args)
2016 return {{detail::make_arg<NUM_ARGS <= detail::max_packed_args, Context>(
2017 args)...}};
2018}
2019
2020#ifndef FMT_DOC
2021template <typename Context = format_context, typename... T,
2022 size_t NUM_NAMED_ARGS = detail::count_named_args<T...>(),
2023 unsigned long long DESC =
2024 detail::make_descriptor<Context, T...>() |
2025 static_cast<unsigned long long>(detail::has_named_args_bit),
2026 FMT_ENABLE_IF(NUM_NAMED_ARGS != 0)>
2027constexpr auto make_format_args(T&... args)
2028 -> detail::format_arg_store<Context, sizeof...(T), NUM_NAMED_ARGS, DESC> {
2029 return {args...};
2030}
2031#endif
2032
2044template <typename Char, typename T>
2045inline auto arg(const Char* name, const T& arg) -> detail::named_arg<Char, T> {
2046 static_assert(!detail::is_named_arg<T>(), "nested named arguments");
2047 return {name, arg};
2048}
2049FMT_END_EXPORT
2050
2052// A separate type would result in shorter symbols but break ABI compatibility
2053// between clang and gcc on ARM (#1919).
2055
2056// We cannot use enum classes as bit fields because of a gcc bug, so we put them
2057// in namespaces instead (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414).
2058// Additionally, if an underlying type is specified, older gcc incorrectly warns
2059// that the type is too small. Both bugs are fixed in gcc 9.3.
2060#if FMT_GCC_VERSION && FMT_GCC_VERSION < 903
2061# define FMT_ENUM_UNDERLYING_TYPE(type)
2062#else
2063# define FMT_ENUM_UNDERLYING_TYPE(type) : type
2064#endif
2065namespace align {
2066enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, left, right, center,
2067 numeric};
2068}
2069using align_t = align::type;
2070namespace sign {
2071enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, minus, plus, space};
2072}
2073using sign_t = sign::type;
2074
2075namespace detail {
2076
2077template <typename Char>
2078using unsigned_char = typename conditional_t<std::is_integral<Char>::value,
2079 std::make_unsigned<Char>,
2081
2082// Character (code unit) type is erased to prevent template bloat.
2083struct fill_t {
2084 private:
2085 enum { max_size = 4 };
2086 char data_[max_size] = {' '};
2087 unsigned char size_ = 1;
2088
2089 public:
2090 template <typename Char>
2091 FMT_CONSTEXPR void operator=(basic_string_view<Char> s) {
2092 auto size = s.size();
2093 size_ = static_cast<unsigned char>(size);
2094 if (size == 1) {
2095 unsigned uchar = static_cast<unsigned_char<Char>>(s[0]);
2096 data_[0] = static_cast<char>(uchar);
2097 data_[1] = static_cast<char>(uchar >> 8);
2098 return;
2099 }
2100 FMT_ASSERT(size <= max_size, "invalid fill");
2101 for (size_t i = 0; i < size; ++i) data_[i] = static_cast<char>(s[i]);
2102 }
2103
2104 FMT_CONSTEXPR void operator=(char c) {
2105 data_[0] = c;
2106 size_ = 1;
2107 }
2108
2109 constexpr auto size() const -> size_t { return size_; }
2110
2111 template <typename Char> constexpr auto get() const -> Char {
2112 using uchar = unsigned char;
2113 return static_cast<Char>(static_cast<uchar>(data_[0]) |
2114 (static_cast<uchar>(data_[1]) << 8));
2115 }
2116
2117 template <typename Char, FMT_ENABLE_IF(std::is_same<Char, char>::value)>
2118 constexpr auto data() const -> const Char* {
2119 return data_;
2120 }
2121 template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
2122 constexpr auto data() const -> const Char* {
2123 return nullptr;
2124 }
2125};
2126} // namespace detail
2127
2128enum class presentation_type : unsigned char {
2129 // Common specifiers:
2130 none = 0,
2131 debug = 1, // '?'
2132 string = 2, // 's' (string, bool)
2133
2134 // Integral, bool and character specifiers:
2135 dec = 3, // 'd'
2136 hex, // 'x' or 'X'
2137 oct, // 'o'
2138 bin, // 'b' or 'B'
2139 chr, // 'c'
2140
2141 // String and pointer specifiers:
2142 pointer = 3, // 'p'
2143
2144 // Floating-point specifiers:
2145 exp = 1, // 'e' or 'E' (1 since there is no FP debug presentation)
2146 fixed, // 'f' or 'F'
2147 general, // 'g' or 'G'
2148 hexfloat // 'a' or 'A'
2149};
2150
2151// Format specifiers for built-in and string types.
2153 int width;
2154 int precision;
2155 presentation_type type;
2156 align_t align : 4;
2157 sign_t sign : 3;
2158 bool upper : 1; // An uppercase version e.g. 'X' for 'x'.
2159 bool alt : 1; // Alternate form ('#').
2160 bool localized : 1;
2161 detail::fill_t fill;
2162
2163 constexpr format_specs()
2164 : width(0),
2165 precision(-1),
2166 type(presentation_type::none),
2167 align(align::none),
2168 sign(sign::none),
2169 upper(false),
2170 alt(false),
2171 localized(false) {}
2172};
2173
2174namespace detail {
2175
2176enum class arg_id_kind { none, index, name };
2177
2178// An argument reference.
2179template <typename Char> struct arg_ref {
2180 FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {}
2181
2182 FMT_CONSTEXPR explicit arg_ref(int index)
2183 : kind(arg_id_kind::index), val(index) {}
2184 FMT_CONSTEXPR explicit arg_ref(basic_string_view<Char> name)
2185 : kind(arg_id_kind::name), val(name) {}
2186
2187 FMT_CONSTEXPR auto operator=(int idx) -> arg_ref& {
2188 kind = arg_id_kind::index;
2189 val.index = idx;
2190 return *this;
2191 }
2192
2193 arg_id_kind kind;
2194 union value {
2195 FMT_CONSTEXPR value(int idx = 0) : index(idx) {}
2196 FMT_CONSTEXPR value(basic_string_view<Char> n) : name(n) {}
2197
2198 int index;
2200 } val;
2201};
2202
2203// Format specifiers with width and precision resolved at formatting rather
2204// than parsing time to allow reusing the same parsed specifiers with
2205// different sets of arguments (precompilation of format strings).
2206template <typename Char = char> struct dynamic_format_specs : format_specs {
2207 arg_ref<Char> width_ref;
2208 arg_ref<Char> precision_ref;
2209};
2210
2211// Converts a character to ASCII. Returns '\0' on conversion failure.
2212template <typename Char, FMT_ENABLE_IF(std::is_integral<Char>::value)>
2213constexpr auto to_ascii(Char c) -> char {
2214 return c <= 0xff ? static_cast<char>(c) : '\0';
2215}
2216
2217// Returns the number of code units in a code point or 1 on error.
2218template <typename Char>
2219FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int {
2220 if (const_check(sizeof(Char) != 1)) return 1;
2221 auto c = static_cast<unsigned char>(*begin);
2222 return static_cast<int>((0x3a55000000000000ull >> (2 * (c >> 3))) & 0x3) + 1;
2223}
2224
2225// Return the result via the out param to workaround gcc bug 77539.
2226template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>
2227FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool {
2228 for (out = first; out != last; ++out) {
2229 if (*out == value) return true;
2230 }
2231 return false;
2232}
2233
2234template <>
2235inline auto find<false, char>(const char* first, const char* last, char value,
2236 const char*& out) -> bool {
2237 out =
2238 static_cast<const char*>(memchr(first, value, to_unsigned(last - first)));
2239 return out != nullptr;
2240}
2241
2242// Parses the range [begin, end) as an unsigned integer. This function assumes
2243// that the range is non-empty and the first character is a digit.
2244template <typename Char>
2245FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end,
2246 int error_value) noexcept -> int {
2247 FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', "");
2248 unsigned value = 0, prev = 0;
2249 auto p = begin;
2250 do {
2251 prev = value;
2252 value = value * 10 + unsigned(*p - '0');
2253 ++p;
2254 } while (p != end && '0' <= *p && *p <= '9');
2255 auto num_digits = p - begin;
2256 begin = p;
2257 int digits10 = static_cast<int>(sizeof(int) * CHAR_BIT * 3 / 10);
2258 if (num_digits <= digits10) return static_cast<int>(value);
2259 // Check for overflow.
2260 unsigned max = INT_MAX;
2261 return num_digits == digits10 + 1 &&
2262 prev * 10ull + unsigned(p[-1] - '0') <= max
2263 ? static_cast<int>(value)
2264 : error_value;
2265}
2266
2267FMT_CONSTEXPR inline auto parse_align(char c) -> align_t {
2268 switch (c) {
2269 case '<':
2270 return align::left;
2271 case '>':
2272 return align::right;
2273 case '^':
2274 return align::center;
2275 }
2276 return align::none;
2277}
2278
2279template <typename Char> constexpr auto is_name_start(Char c) -> bool {
2280 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_';
2281}
2282
2283template <typename Char, typename Handler>
2284FMT_CONSTEXPR auto do_parse_arg_id(const Char* begin, const Char* end,
2285 Handler&& handler) -> const Char* {
2286 Char c = *begin;
2287 if (c >= '0' && c <= '9') {
2288 int index = 0;
2289 if (c != '0')
2290 index = parse_nonnegative_int(begin, end, INT_MAX);
2291 else
2292 ++begin;
2293 if (begin == end || (*begin != '}' && *begin != ':'))
2294 report_error("invalid format string");
2295 else
2296 handler.on_index(index);
2297 return begin;
2298 }
2299 if (!is_name_start(c)) {
2300 report_error("invalid format string");
2301 return begin;
2302 }
2303 auto it = begin;
2304 do {
2305 ++it;
2306 } while (it != end && (is_name_start(*it) || ('0' <= *it && *it <= '9')));
2307 handler.on_name({begin, to_unsigned(it - begin)});
2308 return it;
2309}
2310
2311template <typename Char, typename Handler>
2312FMT_CONSTEXPR auto parse_arg_id(const Char* begin, const Char* end,
2313 Handler&& handler) -> const Char* {
2314 FMT_ASSERT(begin != end, "");
2315 Char c = *begin;
2316 if (c != '}' && c != ':') return do_parse_arg_id(begin, end, handler);
2317 handler.on_auto();
2318 return begin;
2319}
2320
2321template <typename Char> struct dynamic_spec_id_handler {
2323 arg_ref<Char>& ref;
2324
2325 FMT_CONSTEXPR void on_auto() {
2326 int id = ctx.next_arg_id();
2327 ref = arg_ref<Char>(id);
2328 ctx.check_dynamic_spec(id);
2329 }
2330 FMT_CONSTEXPR void on_index(int id) {
2331 ref = arg_ref<Char>(id);
2332 ctx.check_arg_id(id);
2333 ctx.check_dynamic_spec(id);
2334 }
2335 FMT_CONSTEXPR void on_name(basic_string_view<Char> id) {
2336 ref = arg_ref<Char>(id);
2337 ctx.check_arg_id(id);
2338 }
2339};
2340
2341// Parses [integer | "{" [arg_id] "}"].
2342template <typename Char>
2343FMT_CONSTEXPR auto parse_dynamic_spec(const Char* begin, const Char* end,
2344 int& value, arg_ref<Char>& ref,
2346 -> const Char* {
2347 FMT_ASSERT(begin != end, "");
2348 if ('0' <= *begin && *begin <= '9') {
2349 int val = parse_nonnegative_int(begin, end, -1);
2350 if (val != -1)
2351 value = val;
2352 else
2353 report_error("number is too big");
2354 } else if (*begin == '{') {
2355 ++begin;
2356 auto handler = dynamic_spec_id_handler<Char>{ctx, ref};
2357 if (begin != end) begin = parse_arg_id(begin, end, handler);
2358 if (begin != end && *begin == '}') return ++begin;
2359 report_error("invalid format string");
2360 }
2361 return begin;
2362}
2363
2364template <typename Char>
2365FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end,
2366 int& value, arg_ref<Char>& ref,
2368 -> const Char* {
2369 ++begin;
2370 if (begin == end || *begin == '}') {
2371 report_error("invalid precision");
2372 return begin;
2373 }
2374 return parse_dynamic_spec(begin, end, value, ref, ctx);
2375}
2376
2377enum class state { start, align, sign, hash, zero, width, precision, locale };
2378
2379// Parses standard format specifiers.
2380template <typename Char>
2381FMT_CONSTEXPR auto parse_format_specs(const Char* begin, const Char* end,
2382 dynamic_format_specs<Char>& specs,
2384 type arg_type) -> const Char* {
2385 auto c = '\0';
2386 if (end - begin > 1) {
2387 auto next = to_ascii(begin[1]);
2388 c = parse_align(next) == align::none ? to_ascii(*begin) : '\0';
2389 } else {
2390 if (begin == end) return begin;
2391 c = to_ascii(*begin);
2392 }
2393
2394 struct {
2395 state current_state = state::start;
2396 FMT_CONSTEXPR void operator()(state s, bool valid = true) {
2397 if (current_state >= s || !valid)
2398 report_error("invalid format specifier");
2399 current_state = s;
2400 }
2401 } enter_state;
2402
2403 using pres = presentation_type;
2404 constexpr auto integral_set = sint_set | uint_set | bool_set | char_set;
2405 struct {
2406 const Char*& begin;
2407 dynamic_format_specs<Char>& specs;
2408 type arg_type;
2409
2410 FMT_CONSTEXPR auto operator()(pres pres_type, int set) -> const Char* {
2411 if (!in(arg_type, set)) {
2412 if (arg_type == type::none_type) return begin;
2413 report_error("invalid format specifier");
2414 }
2415 specs.type = pres_type;
2416 return begin + 1;
2417 }
2418 } parse_presentation_type{begin, specs, arg_type};
2419
2420 for (;;) {
2421 switch (c) {
2422 case '<':
2423 case '>':
2424 case '^':
2425 enter_state(state::align);
2426 specs.align = parse_align(c);
2427 ++begin;
2428 break;
2429 case '+':
2430 case '-':
2431 case ' ':
2432 if (arg_type == type::none_type) return begin;
2433 enter_state(state::sign, in(arg_type, sint_set | float_set));
2434 switch (c) {
2435 case '+':
2436 specs.sign = sign::plus;
2437 break;
2438 case '-':
2439 specs.sign = sign::minus;
2440 break;
2441 case ' ':
2442 specs.sign = sign::space;
2443 break;
2444 }
2445 ++begin;
2446 break;
2447 case '#':
2448 if (arg_type == type::none_type) return begin;
2449 enter_state(state::hash, is_arithmetic_type(arg_type));
2450 specs.alt = true;
2451 ++begin;
2452 break;
2453 case '0':
2454 enter_state(state::zero);
2455 if (!is_arithmetic_type(arg_type)) {
2456 if (arg_type == type::none_type) return begin;
2457 report_error("format specifier requires numeric argument");
2458 }
2459 if (specs.align == align::none) {
2460 // Ignore 0 if align is specified for compatibility with std::format.
2461 specs.align = align::numeric;
2462 specs.fill = '0';
2463 }
2464 ++begin;
2465 break;
2466 case '1':
2467 case '2':
2468 case '3':
2469 case '4':
2470 case '5':
2471 case '6':
2472 case '7':
2473 case '8':
2474 case '9':
2475 case '{':
2476 enter_state(state::width);
2477 begin = parse_dynamic_spec(begin, end, specs.width, specs.width_ref, ctx);
2478 break;
2479 case '.':
2480 if (arg_type == type::none_type) return begin;
2481 enter_state(state::precision,
2482 in(arg_type, float_set | string_set | cstring_set));
2483 begin = parse_precision(begin, end, specs.precision, specs.precision_ref,
2484 ctx);
2485 break;
2486 case 'L':
2487 if (arg_type == type::none_type) return begin;
2488 enter_state(state::locale, is_arithmetic_type(arg_type));
2489 specs.localized = true;
2490 ++begin;
2491 break;
2492 case 'd':
2493 return parse_presentation_type(pres::dec, integral_set);
2494 case 'X':
2495 specs.upper = true;
2496 FMT_FALLTHROUGH;
2497 case 'x':
2498 return parse_presentation_type(pres::hex, integral_set);
2499 case 'o':
2500 return parse_presentation_type(pres::oct, integral_set);
2501 case 'B':
2502 specs.upper = true;
2503 FMT_FALLTHROUGH;
2504 case 'b':
2505 return parse_presentation_type(pres::bin, integral_set);
2506 case 'E':
2507 specs.upper = true;
2508 FMT_FALLTHROUGH;
2509 case 'e':
2510 return parse_presentation_type(pres::exp, float_set);
2511 case 'F':
2512 specs.upper = true;
2513 FMT_FALLTHROUGH;
2514 case 'f':
2515 return parse_presentation_type(pres::fixed, float_set);
2516 case 'G':
2517 specs.upper = true;
2518 FMT_FALLTHROUGH;
2519 case 'g':
2520 return parse_presentation_type(pres::general, float_set);
2521 case 'A':
2522 specs.upper = true;
2523 FMT_FALLTHROUGH;
2524 case 'a':
2525 return parse_presentation_type(pres::hexfloat, float_set);
2526 case 'c':
2527 if (arg_type == type::bool_type) report_error("invalid format specifier");
2528 return parse_presentation_type(pres::chr, integral_set);
2529 case 's':
2530 return parse_presentation_type(pres::string,
2531 bool_set | string_set | cstring_set);
2532 case 'p':
2533 return parse_presentation_type(pres::pointer, pointer_set | cstring_set);
2534 case '?':
2535 return parse_presentation_type(pres::debug,
2536 char_set | string_set | cstring_set);
2537 case '}':
2538 return begin;
2539 default: {
2540 if (*begin == '}') return begin;
2541 // Parse fill and alignment.
2542 auto fill_end = begin + code_point_length(begin);
2543 if (end - fill_end <= 0) {
2544 report_error("invalid format specifier");
2545 return begin;
2546 }
2547 if (*begin == '{') {
2548 report_error("invalid fill character '{'");
2549 return begin;
2550 }
2551 auto align = parse_align(to_ascii(*fill_end));
2552 enter_state(state::align, align != align::none);
2553 specs.fill =
2554 basic_string_view<Char>(begin, to_unsigned(fill_end - begin));
2555 specs.align = align;
2556 begin = fill_end + 1;
2557 }
2558 }
2559 if (begin == end) return begin;
2560 c = to_ascii(*begin);
2561 }
2562}
2563
2564template <typename Char, typename Handler>
2565FMT_CONSTEXPR auto parse_replacement_field(const Char* begin, const Char* end,
2566 Handler&& handler) -> const Char* {
2567 struct id_adapter {
2568 Handler& handler;
2569 int arg_id;
2570
2571 FMT_CONSTEXPR void on_auto() { arg_id = handler.on_arg_id(); }
2572 FMT_CONSTEXPR void on_index(int id) { arg_id = handler.on_arg_id(id); }
2573 FMT_CONSTEXPR void on_name(basic_string_view<Char> id) {
2574 arg_id = handler.on_arg_id(id);
2575 }
2576 };
2577
2578 ++begin;
2579 if (begin == end) return handler.on_error("invalid format string"), end;
2580 if (*begin == '}') {
2581 handler.on_replacement_field(handler.on_arg_id(), begin);
2582 } else if (*begin == '{') {
2583 handler.on_text(begin, begin + 1);
2584 } else {
2585 auto adapter = id_adapter{handler, 0};
2586 begin = parse_arg_id(begin, end, adapter);
2587 Char c = begin != end ? *begin : Char();
2588 if (c == '}') {
2589 handler.on_replacement_field(adapter.arg_id, begin);
2590 } else if (c == ':') {
2591 begin = handler.on_format_specs(adapter.arg_id, begin + 1, end);
2592 if (begin == end || *begin != '}')
2593 return handler.on_error("unknown format specifier"), end;
2594 } else {
2595 return handler.on_error("missing '}' in format string"), end;
2596 }
2597 }
2598 return begin + 1;
2599}
2600
2601template <bool IS_CONSTEXPR, typename Char, typename Handler>
2602FMT_CONSTEXPR void parse_format_string(basic_string_view<Char> format_str,
2603 Handler&& handler) {
2604 auto begin = format_str.data();
2605 auto end = begin + format_str.size();
2606 if (end - begin < 32) {
2607 // Use a simple loop instead of memchr for small strings.
2608 const Char* p = begin;
2609 while (p != end) {
2610 auto c = *p++;
2611 if (c == '{') {
2612 handler.on_text(begin, p - 1);
2613 begin = p = parse_replacement_field(p - 1, end, handler);
2614 } else if (c == '}') {
2615 if (p == end || *p != '}')
2616 return handler.on_error("unmatched '}' in format string");
2617 handler.on_text(begin, p);
2618 begin = ++p;
2619 }
2620 }
2621 handler.on_text(begin, end);
2622 return;
2623 }
2624 struct writer {
2625 FMT_CONSTEXPR void operator()(const Char* from, const Char* to) {
2626 if (from == to) return;
2627 for (;;) {
2628 const Char* p = nullptr;
2629 if (!find<IS_CONSTEXPR>(from, to, Char('}'), p))
2630 return handler_.on_text(from, to);
2631 ++p;
2632 if (p == to || *p != '}')
2633 return handler_.on_error("unmatched '}' in format string");
2634 handler_.on_text(from, p);
2635 from = p + 1;
2636 }
2637 }
2638 Handler& handler_;
2639 } write = {handler};
2640 while (begin != end) {
2641 // Doing two passes with memchr (one for '{' and another for '}') is up to
2642 // 2.5x faster than the naive one-pass implementation on big format strings.
2643 const Char* p = begin;
2644 if (*begin != '{' && !find<IS_CONSTEXPR>(begin + 1, end, Char('{'), p))
2645 return write(begin, end);
2646 write(begin, p);
2647 begin = parse_replacement_field(p, end, handler);
2648 }
2649}
2650
2651template <typename T, bool = is_named_arg<T>::value> struct strip_named_arg {
2652 using type = T;
2653};
2654template <typename T> struct strip_named_arg<T, true> {
2655 using type = remove_cvref_t<decltype(T::value)>;
2656};
2657
2658template <typename T, typename ParseContext>
2659FMT_VISIBILITY("hidden") // Suppress an ld warning on macOS (#3769).
2660FMT_CONSTEXPR auto parse_format_specs(ParseContext& ctx)
2661 -> decltype(ctx.begin()) {
2662 using char_type = typename ParseContext::char_type;
2663 using context = buffered_context<char_type>;
2664 using mapped_type = conditional_t<
2665 mapped_type_constant<T, context>::value != type::custom_type,
2666 decltype(arg_mapper<context>().map(std::declval<const T&>())),
2667 typename strip_named_arg<T>::type>;
2668#if defined(__cpp_if_constexpr)
2669 if constexpr (std::is_default_constructible<
2671 return formatter<mapped_type, char_type>().parse(ctx);
2672 } else {
2673 type_is_unformattable_for<T, char_type> _;
2674 return ctx.begin();
2675 }
2676#else
2677 return formatter<mapped_type, char_type>().parse(ctx);
2678#endif
2679}
2680
2681// Checks char specs and returns true iff the presentation type is char-like.
2682FMT_CONSTEXPR inline auto check_char_specs(const format_specs& specs) -> bool {
2683 if (specs.type != presentation_type::none &&
2684 specs.type != presentation_type::chr &&
2685 specs.type != presentation_type::debug) {
2686 return false;
2687 }
2688 if (specs.align == align::numeric || specs.sign != sign::none || specs.alt)
2689 report_error("invalid format specifier for char");
2690 return true;
2691}
2692
2693#if FMT_USE_NONTYPE_TEMPLATE_ARGS
2694template <int N, typename T, typename... Args, typename Char>
2695constexpr auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
2696 if constexpr (is_statically_named_arg<T>()) {
2697 if (name == T::name) return N;
2698 }
2699 if constexpr (sizeof...(Args) > 0)
2700 return get_arg_index_by_name<N + 1, Args...>(name);
2701 (void)name; // Workaround an MSVC bug about "unused" parameter.
2702 return -1;
2703}
2704#endif
2705
2706template <typename... Args, typename Char>
2707FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
2708#if FMT_USE_NONTYPE_TEMPLATE_ARGS
2709 if constexpr (sizeof...(Args) > 0)
2710 return get_arg_index_by_name<0, Args...>(name);
2711#endif
2712 (void)name;
2713 return -1;
2714}
2715
2716template <typename Char, typename... Args> class format_string_checker {
2717 private:
2719 static constexpr int num_args = sizeof...(Args);
2720
2721 // Format specifier parsing function.
2722 // In the future basic_format_parse_context will replace compile_parse_context
2723 // here and will use is_constant_evaluated and downcasting to access the data
2724 // needed for compile-time checks: https://godbolt.org/z/GvWzcTjh1.
2725 using parse_func = const Char* (*)(parse_context_type&);
2726
2727 type types_[num_args > 0 ? static_cast<size_t>(num_args) : 1];
2728 parse_context_type context_;
2729 parse_func parse_funcs_[num_args > 0 ? static_cast<size_t>(num_args) : 1];
2730
2731 public:
2732 explicit FMT_CONSTEXPR format_string_checker(basic_string_view<Char> fmt)
2734 context_(fmt, num_args, types_),
2735 parse_funcs_{&parse_format_specs<Args, parse_context_type>...} {}
2736
2737 FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
2738
2739 FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); }
2740 FMT_CONSTEXPR auto on_arg_id(int id) -> int {
2741 return context_.check_arg_id(id), id;
2742 }
2743 FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
2744#if FMT_USE_NONTYPE_TEMPLATE_ARGS
2745 auto index = get_arg_index_by_name<Args...>(id);
2746 if (index < 0) on_error("named argument is not found");
2747 return index;
2748#else
2749 (void)id;
2750 on_error("compile-time checks for named arguments require C++20 support");
2751 return 0;
2752#endif
2753 }
2754
2755 FMT_CONSTEXPR void on_replacement_field(int id, const Char* begin) {
2756 on_format_specs(id, begin, begin); // Call parse() on empty specs.
2757 }
2758
2759 FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char*)
2760 -> const Char* {
2761 context_.advance_to(begin);
2762 // id >= 0 check is a workaround for gcc 10 bug (#2065).
2763 return id >= 0 && id < num_args ? parse_funcs_[id](context_) : begin;
2764 }
2765
2766 FMT_NORETURN FMT_CONSTEXPR void on_error(const char* message) {
2767 report_error(message);
2768 }
2769};
2770
2771// A base class for compile-time strings.
2773
2774template <typename S>
2775using is_compile_string = std::is_base_of<compile_string, S>;
2776
2777// Reports a compile-time error if S is not a valid format string.
2778template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
2779FMT_ALWAYS_INLINE void check_format_string(const S&) {
2780#ifdef FMT_ENFORCE_COMPILE_STRING
2781 static_assert(is_compile_string<S>::value,
2782 "FMT_ENFORCE_COMPILE_STRING requires all format strings to use "
2783 "FMT_STRING.");
2784#endif
2785}
2786template <typename... Args, typename S,
2787 FMT_ENABLE_IF(is_compile_string<S>::value)>
2788void check_format_string(S format_str) {
2789 using char_t = typename S::char_type;
2790 FMT_CONSTEXPR auto s = basic_string_view<char_t>(format_str);
2791 using checker = format_string_checker<char_t, remove_cvref_t<Args>...>;
2792 FMT_CONSTEXPR bool error = (parse_format_string<true>(s, checker(s)), true);
2793 ignore_unused(error);
2794}
2795
2796// Use vformat_args and avoid type_identity to keep symbols short and workaround
2797// a GCC <= 4.8 bug.
2798template <typename Char = char> struct vformat_args {
2800};
2801template <> struct vformat_args<char> {
2802 using type = format_args;
2803};
2804
2805template <typename Char>
2806void vformat_to(buffer<Char>& buf, basic_string_view<Char> fmt,
2807 typename vformat_args<Char>::type args, locale_ref loc = {});
2808
2809FMT_API void vprint_mojibake(FILE*, string_view, format_args, bool = false);
2810#ifndef _WIN32
2811inline void vprint_mojibake(FILE*, string_view, format_args, bool) {}
2812#endif
2813
2814template <typename T, typename Char, type TYPE> struct native_formatter {
2815 private:
2817
2818 public:
2819 using nonlocking = void;
2820
2821 template <typename ParseContext>
2822 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const Char* {
2823 if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin();
2824 auto end = parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, TYPE);
2825 if (const_check(TYPE == type::char_type)) check_char_specs(specs_);
2826 return end;
2827 }
2828
2829 template <type U = TYPE,
2830 FMT_ENABLE_IF(U == type::string_type || U == type::cstring_type ||
2831 U == type::char_type)>
2832 FMT_CONSTEXPR void set_debug_format(bool set = true) {
2833 specs_.type = set ? presentation_type::debug : presentation_type::none;
2834 }
2835
2836 template <typename FormatContext>
2837 FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const
2838 -> decltype(ctx.out());
2839};
2840} // namespace detail
2841
2842FMT_BEGIN_EXPORT
2843
2844// A formatter specialization for natively supported types.
2845template <typename T, typename Char>
2846struct formatter<T, Char,
2847 enable_if_t<detail::type_constant<T, Char>::value !=
2848 detail::type::custom_type>>
2849 : detail::native_formatter<T, Char, detail::type_constant<T, Char>::value> {
2850};
2851
2852template <typename Char = char> struct runtime_format_string {
2854};
2855
2857template <typename Char, typename... Args> class basic_format_string {
2858 private:
2860
2861 public:
2862 template <
2863 typename S,
2864 FMT_ENABLE_IF(
2865 std::is_convertible<const S&, basic_string_view<Char>>::value ||
2866 (detail::is_compile_string<S>::value &&
2867 std::is_constructible<basic_string_view<Char>, const S&>::value))>
2868 FMT_CONSTEVAL FMT_ALWAYS_INLINE basic_format_string(const S& s) : str_(s) {
2869 static_assert(
2870 detail::count<
2871 (std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
2872 std::is_reference<Args>::value)...>() == 0,
2873 "passing views as lvalues is disallowed");
2874#if FMT_USE_CONSTEVAL
2875 if constexpr (detail::count_named_args<Args...>() ==
2876 detail::count_statically_named_args<Args...>()) {
2877 using checker =
2879 detail::parse_format_string<true>(str_, checker(s));
2880 }
2881#else
2882 detail::check_format_string<Args...>(s);
2883#endif
2884 }
2885 basic_format_string(runtime_format_string<Char> fmt) : str_(fmt.str) {}
2886
2887 FMT_ALWAYS_INLINE operator basic_string_view<Char>() const { return str_; }
2888 auto get() const -> basic_string_view<Char> { return str_; }
2889};
2890
2891#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
2892// Workaround broken conversion on older gcc.
2893template <typename...> using format_string = string_view;
2894inline auto runtime(string_view s) -> string_view { return s; }
2895#else
2896template <typename... Args>
2908inline auto runtime(string_view s) -> runtime_format_string<> { return {{s}}; }
2909#endif
2910
2912template <typename OutputIt,
2913 FMT_ENABLE_IF(detail::is_output_iterator<remove_cvref_t<OutputIt>,
2914 char>::value)>
2915auto vformat_to(OutputIt&& out, string_view fmt, format_args args)
2916 -> remove_cvref_t<OutputIt> {
2917 auto&& buf = detail::get_buffer<char>(out);
2918 detail::vformat_to(buf, fmt, args, {});
2919 return detail::get_iterator(buf, out);
2920}
2921
2934template <typename OutputIt, typename... T,
2935 FMT_ENABLE_IF(detail::is_output_iterator<remove_cvref_t<OutputIt>,
2936 char>::value)>
2937FMT_INLINE auto format_to(OutputIt&& out, format_string<T...> fmt, T&&... args)
2938 -> remove_cvref_t<OutputIt> {
2939 return vformat_to(FMT_FWD(out), fmt, fmt::make_format_args(args...));
2940}
2941
2942template <typename OutputIt> struct format_to_n_result {
2944 OutputIt out;
2946 size_t size;
2947};
2948
2949template <typename OutputIt, typename... T,
2951auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args)
2953 using traits = detail::fixed_buffer_traits;
2955 detail::vformat_to(buf, fmt, args, {});
2956 return {buf.out(), buf.count()};
2957}
2958
2967template <typename OutputIt, typename... T,
2969FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string<T...> fmt,
2970 T&&... args) -> format_to_n_result<OutputIt> {
2971 return vformat_to_n(out, n, fmt, fmt::make_format_args(args...));
2972}
2973
2974template <typename OutputIt, typename Sentinel = OutputIt>
2977 OutputIt out;
2980
2981 FMT_CONSTEXPR operator OutputIt&() & noexcept { return out; }
2982 FMT_CONSTEXPR operator const OutputIt&() const& noexcept { return out; }
2983 FMT_CONSTEXPR operator OutputIt&&() && noexcept {
2984 return static_cast<OutputIt&&>(out);
2985 }
2986};
2987
2988template <size_t N>
2989auto vformat_to(char (&out)[N], string_view fmt, format_args args)
2991 auto result = vformat_to_n(out, N, fmt, args);
2992 return {result.out, result.size > N};
2993}
2994
2995template <size_t N, typename... T>
2996FMT_INLINE auto format_to(char (&out)[N], format_string<T...> fmt, T&&... args)
2998 auto result = fmt::format_to_n(out, N, fmt, static_cast<T&&>(args)...);
2999 return {result.out, result.size > N};
3000}
3001
3003template <typename... T>
3004FMT_NODISCARD FMT_INLINE auto formatted_size(format_string<T...> fmt,
3005 T&&... args) -> size_t {
3006 auto buf = detail::counting_buffer<>();
3007 detail::vformat_to<char>(buf, fmt, fmt::make_format_args(args...), {});
3008 return buf.count();
3009}
3010
3011FMT_API void vprint(string_view fmt, format_args args);
3012FMT_API void vprint(FILE* f, string_view fmt, format_args args);
3013FMT_API void vprint_buffered(FILE* f, string_view fmt, format_args args);
3014FMT_API void vprintln(FILE* f, string_view fmt, format_args args);
3015
3026template <typename... T>
3027FMT_INLINE void print(format_string<T...> fmt, T&&... args) {
3028 const auto& vargs = fmt::make_format_args(args...);
3029 if (!detail::use_utf8()) return detail::vprint_mojibake(stdout, fmt, vargs);
3030 return detail::is_locking<T...>() ? vprint_buffered(stdout, fmt, vargs)
3031 : vprint(fmt, vargs);
3032}
3033
3044template <typename... T>
3045FMT_INLINE void print(FILE* f, format_string<T...> fmt, T&&... args) {
3046 const auto& vargs = fmt::make_format_args(args...);
3047 if (!detail::use_utf8()) return detail::vprint_mojibake(f, fmt, vargs);
3048 return detail::is_locking<T...>() ? vprint_buffered(f, fmt, vargs)
3049 : vprint(f, fmt, vargs);
3050}
3051
3056template <typename... T>
3057FMT_INLINE void println(FILE* f, format_string<T...> fmt, T&&... args) {
3058 const auto& vargs = fmt::make_format_args(args...);
3059 return detail::use_utf8() ? vprintln(f, fmt, vargs)
3060 : detail::vprint_mojibake(f, fmt, vargs, true);
3061}
3062
3067template <typename... T>
3068FMT_INLINE void println(format_string<T...> fmt, T&&... args) {
3069 return fmt::println(stdout, fmt, static_cast<T&&>(args)...);
3070}
3071
3072FMT_END_EXPORT
3073FMT_GCC_PRAGMA("GCC pop_options")
3074FMT_END_NAMESPACE
3075
3076#ifdef FMT_HEADER_ONLY
3077# include "format.h"
3078#endif
3079#endif // FMT_BASE_H_
Definition base.h:1143
Definition base.h:1728
Definition base.h:1707
FMT_CONSTEXPR auto visit(Visitor &&vis) -> decltype(vis(0))
Definition base.h:1762
Definition base.h:1827
constexpr basic_format_args(const format_arg *args, int count)
Definition base.h:1897
FMT_CONSTEXPR auto get(int id) const -> format_arg
Definition base.h:1902
constexpr basic_format_args(const dynamic_format_arg_store< Context > &store)
Definition base.h:1889
constexpr FMT_ALWAYS_INLINE basic_format_args(const detail::format_arg_store< Context, NUM_ARGS, NUM_NAMED_ARGS, DESC > &store)
Definition base.h:1871
Definition base.h:727
FMT_CONSTEXPR auto next_arg_id() -> int
Definition base.h:764
constexpr auto end() const noexcept -> iterator
Definition base.h:753
FMT_CONSTEXPR void check_arg_id(int id)
Definition base.h:778
FMT_CONSTEXPR void advance_to(iterator it)
Definition base.h:756
constexpr auto begin() const noexcept -> iterator
Definition base.h:746
Definition base.h:2857
Definition base.h:484
constexpr auto size() const noexcept -> size_t
Definition base.h:526
FMT_CONSTEXPR basic_string_view(const S &s) noexcept
Definition base.h:519
constexpr auto data() const noexcept -> const Char *
Definition base.h:523
constexpr basic_string_view(const Char *s, size_t count) noexcept
Definition base.h:496
FMT_CONSTEXPR20 basic_string_view(const Char *s)
Definition base.h:505
Definition base.h:1940
char char_type
Definition base.h:1948
FMT_CONSTEXPR context(iterator out, basic_format_args< context > ctx_args, detail::locale_ref loc={})
Definition base.h:1959
Definition base.h:838
void append(const U *begin, const U *end)
Definition base.h:913
FMT_CONSTEXPR void set(T *buf_data, size_t buf_capacity) noexcept
Definition base.h:861
void clear()
Definition base.h:890
constexpr auto size() const noexcept -> size_t
Definition base.h:880
constexpr auto capacity() const noexcept -> size_t
Definition base.h:883
FMT_CONSTEXPR auto data() noexcept -> T *
Definition base.h:886
Definition base.h:798
Definition base.h:1082
Definition base.h:945
Definition base.h:2716
Definition base.h:962
Definition base.h:1561
Definition base.h:1310
Definition args.h:82
Definition format.h:1003
GLM_FUNC_DECL GLM_CONSTEXPR genType zero()
Definition constants.inl:6
Definition base.h:1506
Definition base.h:1418
Definition base.h:2179
Definition base.h:939
Definition base.h:2772
Definition base.h:1303
Definition base.h:2206
Definition base.h:2321
Definition base.h:2083
Definition base.h:1663
Definition base.h:1399
Definition base.h:1411
Definition base.h:609
Definition base.h:454
Definition base.h:1269
Definition base.h:1551
Definition base.h:1270
Definition base.h:417
Definition base.h:1175
Definition base.h:1264
Definition base.h:1298
Definition base.h:1258
Definition base.h:2814
Definition base.h:616
Definition base.h:1293
Definition base.h:2651
Definition base.h:652
Definition base.h:1597
Definition base.h:1290
Definition base.h:1291
Definition base.h:1289
Definition base.h:2798
Definition base.h:1256
Definition base.h:2152
Definition base.h:2942
OutputIt out
Definition base.h:2944
size_t size
Definition base.h:2946
Definition base.h:2975
bool truncated
Definition base.h:2979
OutputIt out
Definition base.h:2977
Definition base.h:1130
Definition base.h:586
Definition base.h:474
Definition base.h:323
Definition base.h:2852
Definition base.h:304
Definition base.h:2194