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