Debian Codegraph @

packages/seacas/libraries/aprepro_lib/fmt/base.h

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