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