1 // Formatting library for C++ - the core API
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7 
8 #ifndef FMT_CORE_H_
9 #define FMT_CORE_H_
10 
11 #include <cstdio>  // std::FILE
12 #include <cstring>
13 #include <functional>
14 #include <iterator>
15 #include <memory>
16 #include <string>
17 #include <type_traits>
18 #include <vector>
19 
20 // The fmt library version in the form major * 10000 + minor * 100 + patch.
21 #define FMT_VERSION 70103
22 
23 #ifdef __clang__
24 #  define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
25 #else
26 #  define FMT_CLANG_VERSION 0
27 #endif
28 
29 #if defined(__GNUC__) && !defined(__clang__)
30 #  define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
31 #else
32 #  define FMT_GCC_VERSION 0
33 #endif
34 
35 #if defined(__INTEL_COMPILER)
36 #  define FMT_ICC_VERSION __INTEL_COMPILER
37 #else
38 #  define FMT_ICC_VERSION 0
39 #endif
40 
41 #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
42 #  define FMT_HAS_GXX_CXX11 FMT_GCC_VERSION
43 #else
44 #  define FMT_HAS_GXX_CXX11 0
45 #endif
46 
47 #ifdef __NVCC__
48 #  define FMT_NVCC __NVCC__
49 #else
50 #  define FMT_NVCC 0
51 #endif
52 
53 #ifdef _MSC_VER
54 #  define FMT_MSC_VER _MSC_VER
55 #  define FMT_SUPPRESS_MSC_WARNING(n) __pragma(warning(suppress : n))
56 #else
57 #  define FMT_MSC_VER 0
58 #  define FMT_SUPPRESS_MSC_WARNING(n)
59 #endif
60 
61 #ifdef __has_feature
62 #  define FMT_HAS_FEATURE(x) __has_feature(x)
63 #else
64 #  define FMT_HAS_FEATURE(x) 0
65 #endif
66 
67 #if defined(__has_include) && !defined(__INTELLISENSE__) && \
68     (!FMT_ICC_VERSION || FMT_ICC_VERSION >= 1600)
69 #  define FMT_HAS_INCLUDE(x) __has_include(x)
70 #else
71 #  define FMT_HAS_INCLUDE(x) 0
72 #endif
73 
74 #ifdef __has_cpp_attribute
75 #  define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
76 #else
77 #  define FMT_HAS_CPP_ATTRIBUTE(x) 0
78 #endif
79 
80 #define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
81   (__cplusplus >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
82 
83 #define FMT_HAS_CPP17_ATTRIBUTE(attribute) \
84   (__cplusplus >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))
85 
86 // Check if relaxed C++14 constexpr is supported.
87 // GCC doesn't allow throw in constexpr until version 6 (bug 67371).
88 #ifndef FMT_USE_CONSTEXPR
89 #  define FMT_USE_CONSTEXPR                                           \
90     (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1910 || \
91      (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) &&           \
92         !FMT_NVCC && !FMT_ICC_VERSION
93 #endif
94 #if FMT_USE_CONSTEXPR
95 #  define FMT_CONSTEXPR constexpr
96 #  define FMT_CONSTEXPR_DECL constexpr
97 #else
98 #  define FMT_CONSTEXPR inline
99 #  define FMT_CONSTEXPR_DECL
100 #endif
101 
102 #ifndef FMT_OVERRIDE
103 #  if FMT_HAS_FEATURE(cxx_override_control) || \
104       (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900
105 #    define FMT_OVERRIDE override
106 #  else
107 #    define FMT_OVERRIDE
108 #  endif
109 #endif
110 
111 // Check if exceptions are disabled.
112 #ifndef FMT_EXCEPTIONS
113 #  if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \
114       FMT_MSC_VER && !_HAS_EXCEPTIONS
115 #    define FMT_EXCEPTIONS 0
116 #  else
117 #    define FMT_EXCEPTIONS 1
118 #  endif
119 #endif
120 
121 // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature).
122 #ifndef FMT_USE_NOEXCEPT
123 #  define FMT_USE_NOEXCEPT 0
124 #endif
125 
126 #if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
127     (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900
128 #  define FMT_DETECTED_NOEXCEPT noexcept
129 #  define FMT_HAS_CXX11_NOEXCEPT 1
130 #else
131 #  define FMT_DETECTED_NOEXCEPT throw()
132 #  define FMT_HAS_CXX11_NOEXCEPT 0
133 #endif
134 
135 #ifndef FMT_NOEXCEPT
136 #  if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT
137 #    define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT
138 #  else
139 #    define FMT_NOEXCEPT
140 #  endif
141 #endif
142 
143 // [[noreturn]] is disabled on MSVC and NVCC because of bogus unreachable code
144 // warnings.
145 #if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VER && \
146     !FMT_NVCC
147 #  define FMT_NORETURN [[noreturn]]
148 #else
149 #  define FMT_NORETURN
150 #endif
151 
152 #ifndef FMT_DEPRECATED
153 #  if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VER >= 1900
154 #    define FMT_DEPRECATED [[deprecated]]
155 #  else
156 #    if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__)
157 #      define FMT_DEPRECATED __attribute__((deprecated))
158 #    elif FMT_MSC_VER
159 #      define FMT_DEPRECATED __declspec(deprecated)
160 #    else
161 #      define FMT_DEPRECATED /* deprecated */
162 #    endif
163 #  endif
164 #endif
165 
166 // Workaround broken [[deprecated]] in the Intel, PGI and NVCC compilers.
167 #if FMT_ICC_VERSION || defined(__PGI) || FMT_NVCC
168 #  define FMT_DEPRECATED_ALIAS
169 #else
170 #  define FMT_DEPRECATED_ALIAS FMT_DEPRECATED
171 #endif
172 
173 #ifndef FMT_INLINE
174 #  if FMT_GCC_VERSION || FMT_CLANG_VERSION
175 #    define FMT_INLINE inline __attribute__((always_inline))
176 #  else
177 #    define FMT_INLINE inline
178 #  endif
179 #endif
180 
181 #ifndef FMT_USE_INLINE_NAMESPACES
182 #  if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \
183       (FMT_MSC_VER >= 1900 && !_MANAGED)
184 #    define FMT_USE_INLINE_NAMESPACES 1
185 #  else
186 #    define FMT_USE_INLINE_NAMESPACES 0
187 #  endif
188 #endif
189 
190 #ifndef FMT_BEGIN_NAMESPACE
191 #  if FMT_USE_INLINE_NAMESPACES
192 #    define FMT_INLINE_NAMESPACE inline namespace
193 #    define FMT_END_NAMESPACE \
194       }                       \
195       }
196 #  else
197 #    define FMT_INLINE_NAMESPACE namespace
198 #    define FMT_END_NAMESPACE \
199       }                       \
200       using namespace v7;     \
201       }
202 #  endif
203 #  define FMT_BEGIN_NAMESPACE \
204     namespace fmt {           \
205     FMT_INLINE_NAMESPACE v7 {
206 #endif
207 
208 #if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
209 #  define FMT_CLASS_API FMT_SUPPRESS_MSC_WARNING(4275)
210 #  ifdef FMT_EXPORT
211 #    define FMT_API __declspec(dllexport)
212 #    define FMT_EXTERN_TEMPLATE_API FMT_API
213 #    define FMT_EXPORTED
214 #  elif defined(FMT_SHARED)
215 #    define FMT_API __declspec(dllimport)
216 #    define FMT_EXTERN_TEMPLATE_API FMT_API
217 #  endif
218 #else
219 #  define FMT_CLASS_API
220 #endif
221 #ifndef FMT_API
222 #  define FMT_API
223 #endif
224 #ifndef FMT_EXTERN_TEMPLATE_API
225 #  define FMT_EXTERN_TEMPLATE_API
226 #endif
227 #ifndef FMT_INSTANTIATION_DEF_API
228 #  define FMT_INSTANTIATION_DEF_API FMT_API
229 #endif
230 
231 #ifndef FMT_HEADER_ONLY
232 #  define FMT_EXTERN extern
233 #else
234 #  define FMT_EXTERN
235 #endif
236 
237 // libc++ supports string_view in pre-c++17.
238 #if (FMT_HAS_INCLUDE(<string_view>) &&                       \
239      (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \
240     (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910)
241 #  include <string_view>
242 #  define FMT_USE_STRING_VIEW
243 #elif FMT_HAS_INCLUDE("experimental/string_view") && __cplusplus >= 201402L
244 #  include <experimental/string_view>
245 #  define FMT_USE_EXPERIMENTAL_STRING_VIEW
246 #endif
247 
248 #ifndef FMT_UNICODE
249 #  define FMT_UNICODE !FMT_MSC_VER
250 #endif
251 #if FMT_UNICODE && FMT_MSC_VER
252 #  pragma execution_character_set("utf-8")
253 #endif
254 
255 FMT_BEGIN_NAMESPACE
256 
257 // Implementations of enable_if_t and other metafunctions for older systems.
258 template <bool B, class T = void>
259 using enable_if_t = typename std::enable_if<B, T>::type;
260 template <bool B, class T, class F>
261 using conditional_t = typename std::conditional<B, T, F>::type;
262 template <bool B> using bool_constant = std::integral_constant<bool, B>;
263 template <typename T>
264 using remove_reference_t = typename std::remove_reference<T>::type;
265 template <typename T>
266 using remove_const_t = typename std::remove_const<T>::type;
267 template <typename T>
268 using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
269 template <typename T> struct type_identity { using type = T; };
270 template <typename T> using type_identity_t = typename type_identity<T>::type;
271 
272 struct monostate {};
273 
274 // An enable_if helper to be used in template parameters which results in much
275 // shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed
276 // to workaround a bug in MSVC 2019 (see #1140 and #1186).
277 #define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0
278 
279 namespace detail {
280 
281 // A helper function to suppress "conditional expression is constant" warnings.
const_check(T value)282 template <typename T> constexpr T const_check(T value) { return value; }
283 
284 FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
285                                       const char* message);
286 
287 #ifndef FMT_ASSERT
288 #  ifdef NDEBUG
289 // FMT_ASSERT is not empty to avoid -Werror=empty-body.
290 #    define FMT_ASSERT(condition, message) ((void)0)
291 #  else
292 #    define FMT_ASSERT(condition, message)                                    \
293       ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
294            ? (void)0                                                          \
295            : ::fmt::detail::assert_fail(__FILE__, __LINE__, (message)))
296 #  endif
297 #endif
298 
299 #if defined(FMT_USE_STRING_VIEW)
300 template <typename Char> using std_string_view = std::basic_string_view<Char>;
301 #elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW)
302 template <typename Char>
303 using std_string_view = std::experimental::basic_string_view<Char>;
304 #else
305 template <typename T> struct std_string_view {};
306 #endif
307 
308 #ifdef FMT_USE_INT128
309 // Do nothing.
310 #elif defined(__SIZEOF_INT128__) && !FMT_NVCC && \
311     !(FMT_CLANG_VERSION && FMT_MSC_VER)
312 #  define FMT_USE_INT128 1
313 using int128_t = __int128_t;
314 using uint128_t = __uint128_t;
315 #else
316 #  define FMT_USE_INT128 0
317 #endif
318 #if !FMT_USE_INT128
319 struct int128_t {};
320 struct uint128_t {};
321 #endif
322 
323 // Casts a nonnegative integer to unsigned.
324 template <typename Int>
to_unsigned(Int value)325 FMT_CONSTEXPR typename std::make_unsigned<Int>::type to_unsigned(Int value) {
326   FMT_ASSERT(value >= 0, "negative value");
327   return static_cast<typename std::make_unsigned<Int>::type>(value);
328 }
329 
330 FMT_SUPPRESS_MSC_WARNING(4566) constexpr unsigned char micro[] = "\u00B5";
331 
is_unicode()332 template <typename Char> constexpr bool is_unicode() {
333   return FMT_UNICODE || sizeof(Char) != 1 ||
334          (sizeof(micro) == 3 && micro[0] == 0xC2 && micro[1] == 0xB5);
335 }
336 
337 #ifdef __cpp_char8_t
338 using char8_type = char8_t;
339 #else
340 enum char8_type : unsigned char {};
341 #endif
342 }  // namespace detail
343 
344 #ifdef FMT_USE_INTERNAL
345 namespace internal = detail;  // DEPRECATED
346 #endif
347 
348 /**
349   An implementation of ``std::basic_string_view`` for pre-C++17. It provides a
350   subset of the API. ``fmt::basic_string_view`` is used for format strings even
351   if ``std::string_view`` is available to prevent issues when a library is
352   compiled with a different ``-std`` option than the client code (which is not
353   recommended).
354  */
355 template <typename Char> class basic_string_view {
356  private:
357   const Char* data_;
358   size_t size_;
359 
360  public:
361   using value_type = Char;
362   using iterator = const Char*;
363 
basic_string_view()364   constexpr basic_string_view() FMT_NOEXCEPT : data_(nullptr), size_(0) {}
365 
366   /** Constructs a string reference object from a C string and a size. */
basic_string_view(const Char * s,size_t count)367   constexpr basic_string_view(const Char* s, size_t count) FMT_NOEXCEPT
368       : data_(s),
369         size_(count) {}
370 
371   /**
372     \rst
373     Constructs a string reference object from a C string computing
374     the size with ``std::char_traits<Char>::length``.
375     \endrst
376    */
377 #if __cplusplus >= 201703L  // C++17's char_traits::length() is constexpr.
378   FMT_CONSTEXPR
379 #endif
basic_string_view(const Char * s)380   basic_string_view(const Char* s)
381       : data_(s), size_(std::char_traits<Char>::length(s)) {}
382 
383   /** Constructs a string reference from a ``std::basic_string`` object. */
384   template <typename Traits, typename Alloc>
basic_string_view(const std::basic_string<Char,Traits,Alloc> & s)385   FMT_CONSTEXPR basic_string_view(
386       const std::basic_string<Char, Traits, Alloc>& s) FMT_NOEXCEPT
387       : data_(s.data()),
388         size_(s.size()) {}
389 
390   template <typename S, FMT_ENABLE_IF(std::is_same<
391                                       S, detail::std_string_view<Char>>::value)>
basic_string_view(S s)392   FMT_CONSTEXPR basic_string_view(S s) FMT_NOEXCEPT : data_(s.data()),
393                                                       size_(s.size()) {}
394 
395   /** Returns a pointer to the string data. */
data()396   constexpr const Char* data() const { return data_; }
397 
398   /** Returns the string size. */
size()399   constexpr size_t size() const { return size_; }
400 
begin()401   constexpr iterator begin() const { return data_; }
end()402   constexpr iterator end() const { return data_ + size_; }
403 
404   constexpr const Char& operator[](size_t pos) const { return data_[pos]; }
405 
remove_prefix(size_t n)406   FMT_CONSTEXPR void remove_prefix(size_t n) {
407     data_ += n;
408     size_ -= n;
409   }
410 
411   // Lexicographically compare this string reference to other.
compare(basic_string_view other)412   int compare(basic_string_view other) const {
413     size_t str_size = size_ < other.size_ ? size_ : other.size_;
414     int result = std::char_traits<Char>::compare(data_, other.data_, str_size);
415     if (result == 0)
416       result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
417     return result;
418   }
419 
420   friend bool operator==(basic_string_view lhs, basic_string_view rhs) {
421     return lhs.compare(rhs) == 0;
422   }
423   friend bool operator!=(basic_string_view lhs, basic_string_view rhs) {
424     return lhs.compare(rhs) != 0;
425   }
426   friend bool operator<(basic_string_view lhs, basic_string_view rhs) {
427     return lhs.compare(rhs) < 0;
428   }
429   friend bool operator<=(basic_string_view lhs, basic_string_view rhs) {
430     return lhs.compare(rhs) <= 0;
431   }
432   friend bool operator>(basic_string_view lhs, basic_string_view rhs) {
433     return lhs.compare(rhs) > 0;
434   }
435   friend bool operator>=(basic_string_view lhs, basic_string_view rhs) {
436     return lhs.compare(rhs) >= 0;
437   }
438 };
439 
440 using string_view = basic_string_view<char>;
441 using wstring_view = basic_string_view<wchar_t>;
442 
443 /** Specifies if ``T`` is a character type. Can be specialized by users. */
444 template <typename T> struct is_char : std::false_type {};
445 template <> struct is_char<char> : std::true_type {};
446 template <> struct is_char<wchar_t> : std::true_type {};
447 template <> struct is_char<detail::char8_type> : std::true_type {};
448 template <> struct is_char<char16_t> : std::true_type {};
449 template <> struct is_char<char32_t> : std::true_type {};
450 
451 /**
452   \rst
453   Returns a string view of `s`. In order to add custom string type support to
454   {fmt} provide an overload of `to_string_view` for it in the same namespace as
455   the type for the argument-dependent lookup to work.
456 
457   **Example**::
458 
459     namespace my_ns {
460     inline string_view to_string_view(const my_string& s) {
461       return {s.data(), s.length()};
462     }
463     }
464     std::string message = fmt::format(my_string("The answer is {}"), 42);
465   \endrst
466  */
467 template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
468 inline basic_string_view<Char> to_string_view(const Char* s) {
469   return s;
470 }
471 
472 template <typename Char, typename Traits, typename Alloc>
473 inline basic_string_view<Char> to_string_view(
474     const std::basic_string<Char, Traits, Alloc>& s) {
475   return s;
476 }
477 
478 template <typename Char>
479 inline basic_string_view<Char> to_string_view(basic_string_view<Char> s) {
480   return s;
481 }
482 
483 template <typename Char,
484           FMT_ENABLE_IF(!std::is_empty<detail::std_string_view<Char>>::value)>
485 inline basic_string_view<Char> to_string_view(detail::std_string_view<Char> s) {
486   return s;
487 }
488 
489 // A base class for compile-time strings. It is defined in the fmt namespace to
490 // make formatting functions visible via ADL, e.g. format(FMT_STRING("{}"), 42).
491 struct compile_string {};
492 
493 template <typename S>
494 struct is_compile_string : std::is_base_of<compile_string, S> {};
495 
496 template <typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
497 constexpr basic_string_view<typename S::char_type> to_string_view(const S& s) {
498   return s;
499 }
500 
501 namespace detail {
502 void to_string_view(...);
503 using fmt::v7::to_string_view;
504 
505 // Specifies whether S is a string type convertible to fmt::basic_string_view.
506 // It should be a constexpr function but MSVC 2017 fails to compile it in
507 // enable_if and MSVC 2015 fails to compile it as an alias template.
508 template <typename S>
509 struct is_string : std::is_class<decltype(to_string_view(std::declval<S>()))> {
510 };
511 
512 template <typename S, typename = void> struct char_t_impl {};
513 template <typename S> struct char_t_impl<S, enable_if_t<is_string<S>::value>> {
514   using result = decltype(to_string_view(std::declval<S>()));
515   using type = typename result::value_type;
516 };
517 
518 // Reports a compile-time error if S is not a valid format string.
519 template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
520 FMT_INLINE void check_format_string(const S&) {
521 #ifdef FMT_ENFORCE_COMPILE_STRING
522   static_assert(is_compile_string<S>::value,
523                 "FMT_ENFORCE_COMPILE_STRING requires all format strings to use "
524                 "FMT_STRING.");
525 #endif
526 }
527 template <typename..., typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
528 void check_format_string(S);
529 
530 struct error_handler {
531   constexpr error_handler() = default;
532   constexpr error_handler(const error_handler&) = default;
533 
534   // This function is intentionally not constexpr to give a compile-time error.
535   FMT_NORETURN FMT_API void on_error(const char* message);
536 };
537 }  // namespace detail
538 
539 /** String's character type. */
540 template <typename S> using char_t = typename detail::char_t_impl<S>::type;
541 
542 /**
543   \rst
544   Parsing context consisting of a format string range being parsed and an
545   argument counter for automatic indexing.
546 
547   You can use one of the following type aliases for common character types:
548 
549   +-----------------------+-------------------------------------+
550   | Type                  | Definition                          |
551   +=======================+=====================================+
552   | format_parse_context  | basic_format_parse_context<char>    |
553   +-----------------------+-------------------------------------+
554   | wformat_parse_context | basic_format_parse_context<wchar_t> |
555   +-----------------------+-------------------------------------+
556   \endrst
557  */
558 template <typename Char, typename ErrorHandler = detail::error_handler>
559 class basic_format_parse_context : private ErrorHandler {
560  private:
561   basic_string_view<Char> format_str_;
562   int next_arg_id_;
563 
564  public:
565   using char_type = Char;
566   using iterator = typename basic_string_view<Char>::iterator;
567 
568   explicit constexpr basic_format_parse_context(
569       basic_string_view<Char> format_str, ErrorHandler eh = {},
570       int next_arg_id = 0)
571       : ErrorHandler(eh), format_str_(format_str), next_arg_id_(next_arg_id) {}
572 
573   /**
574     Returns an iterator to the beginning of the format string range being
575     parsed.
576    */
577   constexpr iterator begin() const FMT_NOEXCEPT { return format_str_.begin(); }
578 
579   /**
580     Returns an iterator past the end of the format string range being parsed.
581    */
582   constexpr iterator end() const FMT_NOEXCEPT { return format_str_.end(); }
583 
584   /** Advances the begin iterator to ``it``. */
585   FMT_CONSTEXPR void advance_to(iterator it) {
586     format_str_.remove_prefix(detail::to_unsigned(it - begin()));
587   }
588 
589   /**
590     Reports an error if using the manual argument indexing; otherwise returns
591     the next argument index and switches to the automatic indexing.
592    */
593   FMT_CONSTEXPR int next_arg_id() {
594     // Don't check if the argument id is valid to avoid overhead and because it
595     // will be checked during formatting anyway.
596     if (next_arg_id_ >= 0) return next_arg_id_++;
597     on_error("cannot switch from manual to automatic argument indexing");
598     return 0;
599   }
600 
601   /**
602     Reports an error if using the automatic argument indexing; otherwise
603     switches to the manual indexing.
604    */
605   FMT_CONSTEXPR void check_arg_id(int) {
606     if (next_arg_id_ > 0)
607       on_error("cannot switch from automatic to manual argument indexing");
608     else
609       next_arg_id_ = -1;
610   }
611 
612   FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {}
613 
614   FMT_CONSTEXPR void on_error(const char* message) {
615     ErrorHandler::on_error(message);
616   }
617 
618   constexpr ErrorHandler error_handler() const { return *this; }
619 };
620 
621 using format_parse_context = basic_format_parse_context<char>;
622 using wformat_parse_context = basic_format_parse_context<wchar_t>;
623 
624 template <typename Context> class basic_format_arg;
625 template <typename Context> class basic_format_args;
626 template <typename Context> class dynamic_format_arg_store;
627 
628 // A formatter for objects of type T.
629 template <typename T, typename Char = char, typename Enable = void>
630 struct formatter {
631   // A deleted default constructor indicates a disabled formatter.
632   formatter() = delete;
633 };
634 
635 // Specifies if T has an enabled formatter specialization. A type can be
636 // formattable even if it doesn't have a formatter e.g. via a conversion.
637 template <typename T, typename Context>
638 using has_formatter =
639     std::is_constructible<typename Context::template formatter_type<T>>;
640 
641 // Checks whether T is a container with contiguous storage.
642 template <typename T> struct is_contiguous : std::false_type {};
643 template <typename Char>
644 struct is_contiguous<std::basic_string<Char>> : std::true_type {};
645 
646 namespace detail {
647 
648 // Extracts a reference to the container from back_insert_iterator.
649 template <typename Container>
650 inline Container& get_container(std::back_insert_iterator<Container> it) {
651   using bi_iterator = std::back_insert_iterator<Container>;
652   struct accessor : bi_iterator {
653     accessor(bi_iterator iter) : bi_iterator(iter) {}
654     using bi_iterator::container;
655   };
656   return *accessor(it).container;
657 }
658 
659 /**
660   \rst
661   A contiguous memory buffer with an optional growing ability. It is an internal
662   class and shouldn't be used directly, only via `~fmt::basic_memory_buffer`.
663   \endrst
664  */
665 template <typename T> class buffer {
666  private:
667   T* ptr_;
668   size_t size_;
669   size_t capacity_;
670 
671  protected:
672   // Don't initialize ptr_ since it is not accessed to save a few cycles.
673   FMT_SUPPRESS_MSC_WARNING(26495)
674   buffer(size_t sz) FMT_NOEXCEPT : size_(sz), capacity_(sz) {}
675 
676   buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) FMT_NOEXCEPT
677       : ptr_(p),
678         size_(sz),
679         capacity_(cap) {}
680 
681   ~buffer() = default;
682 
683   /** Sets the buffer data and capacity. */
684   void set(T* buf_data, size_t buf_capacity) FMT_NOEXCEPT {
685     ptr_ = buf_data;
686     capacity_ = buf_capacity;
687   }
688 
689   /** Increases the buffer capacity to hold at least *capacity* elements. */
690   virtual void grow(size_t capacity) = 0;
691 
692  public:
693   using value_type = T;
694   using const_reference = const T&;
695 
696   buffer(const buffer&) = delete;
697   void operator=(const buffer&) = delete;
698 
699   T* begin() FMT_NOEXCEPT { return ptr_; }
700   T* end() FMT_NOEXCEPT { return ptr_ + size_; }
701 
702   const T* begin() const FMT_NOEXCEPT { return ptr_; }
703   const T* end() const FMT_NOEXCEPT { return ptr_ + size_; }
704 
705   /** Returns the size of this buffer. */
706   size_t size() const FMT_NOEXCEPT { return size_; }
707 
708   /** Returns the capacity of this buffer. */
709   size_t capacity() const FMT_NOEXCEPT { return capacity_; }
710 
711   /** Returns a pointer to the buffer data. */
712   T* data() FMT_NOEXCEPT { return ptr_; }
713 
714   /** Returns a pointer to the buffer data. */
715   const T* data() const FMT_NOEXCEPT { return ptr_; }
716 
717   /** Clears this buffer. */
718   void clear() { size_ = 0; }
719 
720   // Tries resizing the buffer to contain *count* elements. If T is a POD type
721   // the new elements may not be initialized.
722   void try_resize(size_t count) {
723     try_reserve(count);
724     size_ = count <= capacity_ ? count : capacity_;
725   }
726 
727   // Tries increasing the buffer capacity to *new_capacity*. It can increase the
728   // capacity by a smaller amount than requested but guarantees there is space
729   // for at least one additional element either by increasing the capacity or by
730   // flushing the buffer if it is full.
731   void try_reserve(size_t new_capacity) {
732     if (new_capacity > capacity_) grow(new_capacity);
733   }
734 
735   void push_back(const T& value) {
736     try_reserve(size_ + 1);
737     ptr_[size_++] = value;
738   }
739 
740   /** Appends data to the end of the buffer. */
741   template <typename U> void append(const U* begin, const U* end);
742 
743   template <typename I> T& operator[](I index) { return ptr_[index]; }
744   template <typename I> const T& operator[](I index) const {
745     return ptr_[index];
746   }
747 };
748 
749 struct buffer_traits {
750   explicit buffer_traits(size_t) {}
751   size_t count() const { return 0; }
752   size_t limit(size_t size) { return size; }
753 };
754 
755 class fixed_buffer_traits {
756  private:
757   size_t count_ = 0;
758   size_t limit_;
759 
760  public:
761   explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}
762   size_t count() const { return count_; }
763   size_t limit(size_t size) {
764     size_t n = limit_ > count_ ? limit_ - count_ : 0;
765     count_ += size;
766     return size < n ? size : n;
767   }
768 };
769 
770 // A buffer that writes to an output iterator when flushed.
771 template <typename OutputIt, typename T, typename Traits = buffer_traits>
772 class iterator_buffer final : public Traits, public buffer<T> {
773  private:
774   OutputIt out_;
775   enum { buffer_size = 256 };
776   T data_[buffer_size];
777 
778  protected:
779   void grow(size_t) final FMT_OVERRIDE {
780     if (this->size() == buffer_size) flush();
781   }
782   void flush();
783 
784  public:
785   explicit iterator_buffer(OutputIt out, size_t n = buffer_size)
786       : Traits(n),
787         buffer<T>(data_, 0, buffer_size),
788         out_(out) {}
789   ~iterator_buffer() { flush(); }
790 
791   OutputIt out() {
792     flush();
793     return out_;
794   }
795   size_t count() const { return Traits::count() + this->size(); }
796 };
797 
798 template <typename T> class iterator_buffer<T*, T> final : public buffer<T> {
799  protected:
800   void grow(size_t) final FMT_OVERRIDE {}
801 
802  public:
803   explicit iterator_buffer(T* out, size_t = 0) : buffer<T>(out, 0, ~size_t()) {}
804 
805   T* out() { return &*this->end(); }
806 };
807 
808 // A buffer that writes to a container with the contiguous storage.
809 template <typename Container>
810 class iterator_buffer<std::back_insert_iterator<Container>,
811                       enable_if_t<is_contiguous<Container>::value,
812                                   typename Container::value_type>>
813     final : public buffer<typename Container::value_type> {
814  private:
815   Container& container_;
816 
817  protected:
818   void grow(size_t capacity) final FMT_OVERRIDE {
819     container_.resize(capacity);
820     this->set(&container_[0], capacity);
821   }
822 
823  public:
824   explicit iterator_buffer(Container& c)
825       : buffer<typename Container::value_type>(c.size()), container_(c) {}
826   explicit iterator_buffer(std::back_insert_iterator<Container> out, size_t = 0)
827       : iterator_buffer(get_container(out)) {}
828   std::back_insert_iterator<Container> out() {
829     return std::back_inserter(container_);
830   }
831 };
832 
833 // A buffer that counts the number of code units written discarding the output.
834 template <typename T = char> class counting_buffer final : public buffer<T> {
835  private:
836   enum { buffer_size = 256 };
837   T data_[buffer_size];
838   size_t count_ = 0;
839 
840  protected:
841   void grow(size_t) final FMT_OVERRIDE {
842     if (this->size() != buffer_size) return;
843     count_ += this->size();
844     this->clear();
845   }
846 
847  public:
848   counting_buffer() : buffer<T>(data_, 0, buffer_size) {}
849 
850   size_t count() { return count_ + this->size(); }
851 };
852 
853 // An output iterator that appends to the buffer.
854 // It is used to reduce symbol sizes for the common case.
855 template <typename T>
856 class buffer_appender : public std::back_insert_iterator<buffer<T>> {
857   using base = std::back_insert_iterator<buffer<T>>;
858 
859  public:
860   explicit buffer_appender(buffer<T>& buf) : base(buf) {}
861   buffer_appender(base it) : base(it) {}
862 
863   buffer_appender& operator++() {
864     base::operator++();
865     return *this;
866   }
867 
868   buffer_appender operator++(int) {
869     buffer_appender tmp = *this;
870     ++*this;
871     return tmp;
872   }
873 };
874 
875 // Maps an output iterator into a buffer.
876 template <typename T, typename OutputIt>
877 iterator_buffer<OutputIt, T> get_buffer(OutputIt);
878 template <typename T> buffer<T>& get_buffer(buffer_appender<T>);
879 
880 template <typename OutputIt> OutputIt get_buffer_init(OutputIt out) {
881   return out;
882 }
883 template <typename T> buffer<T>& get_buffer_init(buffer_appender<T> out) {
884   return get_container(out);
885 }
886 
887 template <typename Buffer>
888 auto get_iterator(Buffer& buf) -> decltype(buf.out()) {
889   return buf.out();
890 }
891 template <typename T> buffer_appender<T> get_iterator(buffer<T>& buf) {
892   return buffer_appender<T>(buf);
893 }
894 
895 template <typename T, typename Char = char, typename Enable = void>
896 struct fallback_formatter {
897   fallback_formatter() = delete;
898 };
899 
900 // Specifies if T has an enabled fallback_formatter specialization.
901 template <typename T, typename Context>
902 using has_fallback_formatter =
903     std::is_constructible<fallback_formatter<T, typename Context::char_type>>;
904 
905 struct view {};
906 
907 template <typename Char, typename T> struct named_arg : view {
908   const Char* name;
909   const T& value;
910   named_arg(const Char* n, const T& v) : name(n), value(v) {}
911 };
912 
913 template <typename Char> struct named_arg_info {
914   const Char* name;
915   int id;
916 };
917 
918 template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
919 struct arg_data {
920   // args_[0].named_args points to named_args_ to avoid bloating format_args.
921   // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
922   T args_[1 + (NUM_ARGS != 0 ? NUM_ARGS : +1)];
923   named_arg_info<Char> named_args_[NUM_NAMED_ARGS];
924 
925   template <typename... U>
926   arg_data(const U&... init) : args_{T(named_args_, NUM_NAMED_ARGS), init...} {}
927   arg_data(const arg_data& other) = delete;
928   const T* args() const { return args_ + 1; }
929   named_arg_info<Char>* named_args() { return named_args_; }
930 };
931 
932 template <typename T, typename Char, size_t NUM_ARGS>
933 struct arg_data<T, Char, NUM_ARGS, 0> {
934   // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
935   T args_[NUM_ARGS != 0 ? NUM_ARGS : +1];
936 
937   template <typename... U>
938   FMT_INLINE arg_data(const U&... init) : args_{init...} {}
939   FMT_INLINE const T* args() const { return args_; }
940   FMT_INLINE std::nullptr_t named_args() { return nullptr; }
941 };
942 
943 template <typename Char>
944 inline void init_named_args(named_arg_info<Char>*, int, int) {}
945 
946 template <typename Char, typename T, typename... Tail>
947 void init_named_args(named_arg_info<Char>* named_args, int arg_count,
948                      int named_arg_count, const T&, const Tail&... args) {
949   init_named_args(named_args, arg_count + 1, named_arg_count, args...);
950 }
951 
952 template <typename Char, typename T, typename... Tail>
953 void init_named_args(named_arg_info<Char>* named_args, int arg_count,
954                      int named_arg_count, const named_arg<Char, T>& arg,
955                      const Tail&... args) {
956   named_args[named_arg_count++] = {arg.name, arg_count};
957   init_named_args(named_args, arg_count + 1, named_arg_count, args...);
958 }
959 
960 template <typename... Args>
961 FMT_INLINE void init_named_args(std::nullptr_t, int, int, const Args&...) {}
962 
963 template <typename T> struct is_named_arg : std::false_type {};
964 
965 template <typename T, typename Char>
966 struct is_named_arg<named_arg<Char, T>> : std::true_type {};
967 
968 template <bool B = false> constexpr size_t count() { return B ? 1 : 0; }
969 template <bool B1, bool B2, bool... Tail> constexpr size_t count() {
970   return (B1 ? 1 : 0) + count<B2, Tail...>();
971 }
972 
973 template <typename... Args> constexpr size_t count_named_args() {
974   return count<is_named_arg<Args>::value...>();
975 }
976 
977 enum class type {
978   none_type,
979   // Integer types should go first,
980   int_type,
981   uint_type,
982   long_long_type,
983   ulong_long_type,
984   int128_type,
985   uint128_type,
986   bool_type,
987   char_type,
988   last_integer_type = char_type,
989   // followed by floating-point types.
990   float_type,
991   double_type,
992   long_double_type,
993   last_numeric_type = long_double_type,
994   cstring_type,
995   string_type,
996   pointer_type,
997   custom_type
998 };
999 
1000 // Maps core type T to the corresponding type enum constant.
1001 template <typename T, typename Char>
1002 struct type_constant : std::integral_constant<type, type::custom_type> {};
1003 
1004 #define FMT_TYPE_CONSTANT(Type, constant) \
1005   template <typename Char>                \
1006   struct type_constant<Type, Char>        \
1007       : std::integral_constant<type, type::constant> {}
1008 
1009 FMT_TYPE_CONSTANT(int, int_type);
1010 FMT_TYPE_CONSTANT(unsigned, uint_type);
1011 FMT_TYPE_CONSTANT(long long, long_long_type);
1012 FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
1013 FMT_TYPE_CONSTANT(int128_t, int128_type);
1014 FMT_TYPE_CONSTANT(uint128_t, uint128_type);
1015 FMT_TYPE_CONSTANT(bool, bool_type);
1016 FMT_TYPE_CONSTANT(Char, char_type);
1017 FMT_TYPE_CONSTANT(float, float_type);
1018 FMT_TYPE_CONSTANT(double, double_type);
1019 FMT_TYPE_CONSTANT(long double, long_double_type);
1020 FMT_TYPE_CONSTANT(const Char*, cstring_type);
1021 FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
1022 FMT_TYPE_CONSTANT(const void*, pointer_type);
1023 
1024 constexpr bool is_integral_type(type t) {
1025   return t > type::none_type && t <= type::last_integer_type;
1026 }
1027 
1028 constexpr bool is_arithmetic_type(type t) {
1029   return t > type::none_type && t <= type::last_numeric_type;
1030 }
1031 
1032 template <typename Char> struct string_value {
1033   const Char* data;
1034   size_t size;
1035 };
1036 
1037 template <typename Char> struct named_arg_value {
1038   const named_arg_info<Char>* data;
1039   size_t size;
1040 };
1041 
1042 template <typename Context> struct custom_value {
1043   using parse_context = typename Context::parse_context_type;
1044   const void* value;
1045   void (*format)(const void* arg, parse_context& parse_ctx, Context& ctx);
1046 };
1047 
1048 // A formatting argument value.
1049 template <typename Context> class value {
1050  public:
1051   using char_type = typename Context::char_type;
1052 
1053   union {
1054     int int_value;
1055     unsigned uint_value;
1056     long long long_long_value;
1057     unsigned long long ulong_long_value;
1058     int128_t int128_value;
1059     uint128_t uint128_value;
1060     bool bool_value;
1061     char_type char_value;
1062     float float_value;
1063     double double_value;
1064     long double long_double_value;
1065     const void* pointer;
1066     string_value<char_type> string;
1067     custom_value<Context> custom;
1068     named_arg_value<char_type> named_args;
1069   };
1070 
1071   constexpr FMT_INLINE value(int val = 0) : int_value(val) {}
1072   constexpr FMT_INLINE value(unsigned val) : uint_value(val) {}
1073   FMT_INLINE value(long long val) : long_long_value(val) {}
1074   FMT_INLINE value(unsigned long long val) : ulong_long_value(val) {}
1075   FMT_INLINE value(int128_t val) : int128_value(val) {}
1076   FMT_INLINE value(uint128_t val) : uint128_value(val) {}
1077   FMT_INLINE value(float val) : float_value(val) {}
1078   FMT_INLINE value(double val) : double_value(val) {}
1079   FMT_INLINE value(long double val) : long_double_value(val) {}
1080   FMT_INLINE value(bool val) : bool_value(val) {}
1081   FMT_INLINE value(char_type val) : char_value(val) {}
1082   FMT_INLINE value(const char_type* val) { string.data = val; }
1083   FMT_INLINE value(basic_string_view<char_type> val) {
1084     string.data = val.data();
1085     string.size = val.size();
1086   }
1087   FMT_INLINE value(const void* val) : pointer(val) {}
1088   FMT_INLINE value(const named_arg_info<char_type>* args, size_t size)
1089       : named_args{args, size} {}
1090 
1091   template <typename T> FMT_INLINE value(const T& val) {
1092     custom.value = &val;
1093     // Get the formatter type through the context to allow different contexts
1094     // have different extension points, e.g. `formatter<T>` for `format` and
1095     // `printf_formatter<T>` for `printf`.
1096     custom.format = format_custom_arg<
1097         T, conditional_t<has_formatter<T, Context>::value,
1098                          typename Context::template formatter_type<T>,
1099                          fallback_formatter<T, char_type>>>;
1100   }
1101 
1102  private:
1103   // Formats an argument of a custom type, such as a user-defined class.
1104   template <typename T, typename Formatter>
1105   static void format_custom_arg(const void* arg,
1106                                 typename Context::parse_context_type& parse_ctx,
1107                                 Context& ctx) {
1108     Formatter f;
1109     parse_ctx.advance_to(f.parse(parse_ctx));
1110     ctx.advance_to(f.format(*static_cast<const T*>(arg), ctx));
1111   }
1112 };
1113 
1114 template <typename Context, typename T>
1115 FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value);
1116 
1117 // To minimize the number of types we need to deal with, long is translated
1118 // either to int or to long long depending on its size.
1119 enum { long_short = sizeof(long) == sizeof(int) };
1120 using long_type = conditional_t<long_short, int, long long>;
1121 using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
1122 
1123 struct unformattable {};
1124 
1125 // Maps formatting arguments to core types.
1126 template <typename Context> struct arg_mapper {
1127   using char_type = typename Context::char_type;
1128 
1129   FMT_CONSTEXPR int map(signed char val) { return val; }
1130   FMT_CONSTEXPR unsigned map(unsigned char val) { return val; }
1131   FMT_CONSTEXPR int map(short val) { return val; }
1132   FMT_CONSTEXPR unsigned map(unsigned short val) { return val; }
1133   FMT_CONSTEXPR int map(int val) { return val; }
1134   FMT_CONSTEXPR unsigned map(unsigned val) { return val; }
1135   FMT_CONSTEXPR long_type map(long val) { return val; }
1136   FMT_CONSTEXPR ulong_type map(unsigned long val) { return val; }
1137   FMT_CONSTEXPR long long map(long long val) { return val; }
1138   FMT_CONSTEXPR unsigned long long map(unsigned long long val) { return val; }
1139   FMT_CONSTEXPR int128_t map(int128_t val) { return val; }
1140   FMT_CONSTEXPR uint128_t map(uint128_t val) { return val; }
1141   FMT_CONSTEXPR bool map(bool val) { return val; }
1142 
1143   template <typename T, FMT_ENABLE_IF(is_char<T>::value)>
1144   FMT_CONSTEXPR char_type map(T val) {
1145     static_assert(
1146         std::is_same<T, char>::value || std::is_same<T, char_type>::value,
1147         "mixing character types is disallowed");
1148     return val;
1149   }
1150 
1151   FMT_CONSTEXPR float map(float val) { return val; }
1152   FMT_CONSTEXPR double map(double val) { return val; }
1153   FMT_CONSTEXPR long double map(long double val) { return val; }
1154 
1155   FMT_CONSTEXPR const char_type* map(char_type* val) { return val; }
1156   FMT_CONSTEXPR const char_type* map(const char_type* val) { return val; }
1157   template <typename T, FMT_ENABLE_IF(is_string<T>::value)>
1158   FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
1159     static_assert(std::is_same<char_type, char_t<T>>::value,
1160                   "mixing character types is disallowed");
1161     return to_string_view(val);
1162   }
1163   template <typename T,
1164             FMT_ENABLE_IF(
1165                 std::is_constructible<basic_string_view<char_type>, T>::value &&
1166                 !is_string<T>::value && !has_formatter<T, Context>::value &&
1167                 !has_fallback_formatter<T, Context>::value)>
1168   FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
1169     return basic_string_view<char_type>(val);
1170   }
1171   template <
1172       typename T,
1173       FMT_ENABLE_IF(
1174           std::is_constructible<std_string_view<char_type>, T>::value &&
1175           !std::is_constructible<basic_string_view<char_type>, T>::value &&
1176           !is_string<T>::value && !has_formatter<T, Context>::value &&
1177           !has_fallback_formatter<T, Context>::value)>
1178   FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
1179     return std_string_view<char_type>(val);
1180   }
1181   FMT_CONSTEXPR const char* map(const signed char* val) {
1182     static_assert(std::is_same<char_type, char>::value, "invalid string type");
1183     return reinterpret_cast<const char*>(val);
1184   }
1185   FMT_CONSTEXPR const char* map(const unsigned char* val) {
1186     static_assert(std::is_same<char_type, char>::value, "invalid string type");
1187     return reinterpret_cast<const char*>(val);
1188   }
1189   FMT_CONSTEXPR const char* map(signed char* val) {
1190     const auto* const_val = val;
1191     return map(const_val);
1192   }
1193   FMT_CONSTEXPR const char* map(unsigned char* val) {
1194     const auto* const_val = val;
1195     return map(const_val);
1196   }
1197 
1198   FMT_CONSTEXPR const void* map(void* val) { return val; }
1199   FMT_CONSTEXPR const void* map(const void* val) { return val; }
1200   FMT_CONSTEXPR const void* map(std::nullptr_t val) { return val; }
1201   template <typename T> FMT_CONSTEXPR int map(const T*) {
1202     // Formatting of arbitrary pointers is disallowed. If you want to output
1203     // a pointer cast it to "void *" or "const void *". In particular, this
1204     // forbids formatting of "[const] volatile char *" which is printed as bool
1205     // by iostreams.
1206     static_assert(!sizeof(T), "formatting of non-void pointers is disallowed");
1207     return 0;
1208   }
1209 
1210   template <typename T,
1211             FMT_ENABLE_IF(std::is_enum<T>::value &&
1212                           !has_formatter<T, Context>::value &&
1213                           !has_fallback_formatter<T, Context>::value)>
1214   FMT_CONSTEXPR auto map(const T& val)
1215       -> decltype(std::declval<arg_mapper>().map(
1216           static_cast<typename std::underlying_type<T>::type>(val))) {
1217     return map(static_cast<typename std::underlying_type<T>::type>(val));
1218   }
1219   template <typename T,
1220             FMT_ENABLE_IF(!is_string<T>::value && !is_char<T>::value &&
1221                           (has_formatter<T, Context>::value ||
1222                            has_fallback_formatter<T, Context>::value))>
1223   FMT_CONSTEXPR const T& map(const T& val) {
1224     return val;
1225   }
1226 
1227   template <typename T>
1228   FMT_CONSTEXPR auto map(const named_arg<char_type, T>& val)
1229       -> decltype(std::declval<arg_mapper>().map(val.value)) {
1230     return map(val.value);
1231   }
1232 
1233   unformattable map(...) { return {}; }
1234 };
1235 
1236 // A type constant after applying arg_mapper<Context>.
1237 template <typename T, typename Context>
1238 using mapped_type_constant =
1239     type_constant<decltype(arg_mapper<Context>().map(std::declval<const T&>())),
1240                   typename Context::char_type>;
1241 
1242 enum { packed_arg_bits = 4 };
1243 // Maximum number of arguments with packed types.
1244 enum { max_packed_args = 62 / packed_arg_bits };
1245 enum : unsigned long long { is_unpacked_bit = 1ULL << 63 };
1246 enum : unsigned long long { has_named_args_bit = 1ULL << 62 };
1247 }  // namespace detail
1248 
1249 // A formatting argument. It is a trivially copyable/constructible type to
1250 // allow storage in basic_memory_buffer.
1251 template <typename Context> class basic_format_arg {
1252  private:
1253   detail::value<Context> value_;
1254   detail::type type_;
1255 
1256   template <typename ContextType, typename T>
1257   friend FMT_CONSTEXPR basic_format_arg<ContextType> detail::make_arg(
1258       const T& value);
1259 
1260   template <typename Visitor, typename Ctx>
1261   friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis,
1262                                              const basic_format_arg<Ctx>& arg)
1263       -> decltype(vis(0));
1264 
1265   friend class basic_format_args<Context>;
1266   friend class dynamic_format_arg_store<Context>;
1267 
1268   using char_type = typename Context::char_type;
1269 
1270   template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
1271   friend struct detail::arg_data;
1272 
1273   basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)
1274       : value_(args, size) {}
1275 
1276  public:
1277   class handle {
1278    public:
1279     explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}
1280 
1281     void format(typename Context::parse_context_type& parse_ctx,
1282                 Context& ctx) const {
1283       custom_.format(custom_.value, parse_ctx, ctx);
1284     }
1285 
1286    private:
1287     detail::custom_value<Context> custom_;
1288   };
1289 
1290   constexpr basic_format_arg() : type_(detail::type::none_type) {}
1291 
1292   constexpr explicit operator bool() const FMT_NOEXCEPT {
1293     return type_ != detail::type::none_type;
1294   }
1295 
1296   detail::type type() const { return type_; }
1297 
1298   bool is_integral() const { return detail::is_integral_type(type_); }
1299   bool is_arithmetic() const { return detail::is_arithmetic_type(type_); }
1300 };
1301 
1302 /**
1303   \rst
1304   Visits an argument dispatching to the appropriate visit method based on
1305   the argument type. For example, if the argument type is ``double`` then
1306   ``vis(value)`` will be called with the value of type ``double``.
1307   \endrst
1308  */
1309 template <typename Visitor, typename Context>
1310 FMT_CONSTEXPR_DECL FMT_INLINE auto visit_format_arg(
1311     Visitor&& vis, const basic_format_arg<Context>& arg) -> decltype(vis(0)) {
1312   using char_type = typename Context::char_type;
1313   switch (arg.type_) {
1314   case detail::type::none_type:
1315     break;
1316   case detail::type::int_type:
1317     return vis(arg.value_.int_value);
1318   case detail::type::uint_type:
1319     return vis(arg.value_.uint_value);
1320   case detail::type::long_long_type:
1321     return vis(arg.value_.long_long_value);
1322   case detail::type::ulong_long_type:
1323     return vis(arg.value_.ulong_long_value);
1324 #if FMT_USE_INT128
1325   case detail::type::int128_type:
1326     return vis(arg.value_.int128_value);
1327   case detail::type::uint128_type:
1328     return vis(arg.value_.uint128_value);
1329 #else
1330   case detail::type::int128_type:
1331   case detail::type::uint128_type:
1332     break;
1333 #endif
1334   case detail::type::bool_type:
1335     return vis(arg.value_.bool_value);
1336   case detail::type::char_type:
1337     return vis(arg.value_.char_value);
1338   case detail::type::float_type:
1339     return vis(arg.value_.float_value);
1340   case detail::type::double_type:
1341     return vis(arg.value_.double_value);
1342   case detail::type::long_double_type:
1343     return vis(arg.value_.long_double_value);
1344   case detail::type::cstring_type:
1345     return vis(arg.value_.string.data);
1346   case detail::type::string_type:
1347     return vis(basic_string_view<char_type>(arg.value_.string.data,
1348                                             arg.value_.string.size));
1349   case detail::type::pointer_type:
1350     return vis(arg.value_.pointer);
1351   case detail::type::custom_type:
1352     return vis(typename basic_format_arg<Context>::handle(arg.value_.custom));
1353   }
1354   return vis(monostate());
1355 }
1356 
1357 template <typename T> struct formattable : std::false_type {};
1358 
1359 namespace detail {
1360 
1361 // A workaround for gcc 4.8 to make void_t work in a SFINAE context.
1362 template <typename... Ts> struct void_t_impl { using type = void; };
1363 template <typename... Ts>
1364 using void_t = typename detail::void_t_impl<Ts...>::type;
1365 
1366 template <typename It, typename T, typename Enable = void>
1367 struct is_output_iterator : std::false_type {};
1368 
1369 template <typename It, typename T>
1370 struct is_output_iterator<
1371     It, T,
1372     void_t<typename std::iterator_traits<It>::iterator_category,
1373            decltype(*std::declval<It>() = std::declval<T>())>>
1374     : std::true_type {};
1375 
1376 template <typename OutputIt>
1377 struct is_back_insert_iterator : std::false_type {};
1378 template <typename Container>
1379 struct is_back_insert_iterator<std::back_insert_iterator<Container>>
1380     : std::true_type {};
1381 
1382 template <typename OutputIt>
1383 struct is_contiguous_back_insert_iterator : std::false_type {};
1384 template <typename Container>
1385 struct is_contiguous_back_insert_iterator<std::back_insert_iterator<Container>>
1386     : is_contiguous<Container> {};
1387 template <typename Char>
1388 struct is_contiguous_back_insert_iterator<buffer_appender<Char>>
1389     : std::true_type {};
1390 
1391 // A type-erased reference to an std::locale to avoid heavy <locale> include.
1392 class locale_ref {
1393  private:
1394   const void* locale_;  // A type-erased pointer to std::locale.
1395 
1396  public:
1397   locale_ref() : locale_(nullptr) {}
1398   template <typename Locale> explicit locale_ref(const Locale& loc);
1399 
1400   explicit operator bool() const FMT_NOEXCEPT { return locale_ != nullptr; }
1401 
1402   template <typename Locale> Locale get() const;
1403 };
1404 
1405 template <typename> constexpr unsigned long long encode_types() { return 0; }
1406 
1407 template <typename Context, typename Arg, typename... Args>
1408 constexpr unsigned long long encode_types() {
1409   return static_cast<unsigned>(mapped_type_constant<Arg, Context>::value) |
1410          (encode_types<Context, Args...>() << packed_arg_bits);
1411 }
1412 
1413 template <typename Context, typename T>
1414 FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value) {
1415   basic_format_arg<Context> arg;
1416   arg.type_ = mapped_type_constant<T, Context>::value;
1417   arg.value_ = arg_mapper<Context>().map(value);
1418   return arg;
1419 }
1420 
1421 template <typename T> int check(unformattable) {
1422   static_assert(
1423       formattable<T>(),
1424       "Cannot format an argument. To make type T formattable provide a "
1425       "formatter<T> specialization: https://fmt.dev/latest/api.html#udt");
1426   return 0;
1427 }
1428 template <typename T, typename U> inline const U& check(const U& val) {
1429   return val;
1430 }
1431 
1432 // The type template parameter is there to avoid an ODR violation when using
1433 // a fallback formatter in one translation unit and an implicit conversion in
1434 // another (not recommended).
1435 template <bool IS_PACKED, typename Context, type, typename T,
1436           FMT_ENABLE_IF(IS_PACKED)>
1437 inline value<Context> make_arg(const T& val) {
1438   return check<T>(arg_mapper<Context>().map(val));
1439 }
1440 
1441 template <bool IS_PACKED, typename Context, type, typename T,
1442           FMT_ENABLE_IF(!IS_PACKED)>
1443 inline basic_format_arg<Context> make_arg(const T& value) {
1444   return make_arg<Context>(value);
1445 }
1446 
1447 template <typename T> struct is_reference_wrapper : std::false_type {};
1448 template <typename T>
1449 struct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type {};
1450 
1451 template <typename T> const T& unwrap(const T& v) { return v; }
1452 template <typename T> const T& unwrap(const std::reference_wrapper<T>& v) {
1453   return static_cast<const T&>(v);
1454 }
1455 
1456 class dynamic_arg_list {
1457   // Workaround for clang's -Wweak-vtables. Unlike for regular classes, for
1458   // templates it doesn't complain about inability to deduce single translation
1459   // unit for placing vtable. So storage_node_base is made a fake template.
1460   template <typename = void> struct node {
1461     virtual ~node() = default;
1462     std::unique_ptr<node<>> next;
1463   };
1464 
1465   template <typename T> struct typed_node : node<> {
1466     T value;
1467 
1468     template <typename Arg>
1469     FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {}
1470 
1471     template <typename Char>
1472     FMT_CONSTEXPR typed_node(const basic_string_view<Char>& arg)
1473         : value(arg.data(), arg.size()) {}
1474   };
1475 
1476   std::unique_ptr<node<>> head_;
1477 
1478  public:
1479   template <typename T, typename Arg> const T& push(const Arg& arg) {
1480     auto new_node = std::unique_ptr<typed_node<T>>(new typed_node<T>(arg));
1481     auto& value = new_node->value;
1482     new_node->next = std::move(head_);
1483     head_ = std::move(new_node);
1484     return value;
1485   }
1486 };
1487 }  // namespace detail
1488 
1489 // Formatting context.
1490 template <typename OutputIt, typename Char> class basic_format_context {
1491  public:
1492   /** The character type for the output. */
1493   using char_type = Char;
1494 
1495  private:
1496   OutputIt out_;
1497   basic_format_args<basic_format_context> args_;
1498   detail::locale_ref loc_;
1499 
1500  public:
1501   using iterator = OutputIt;
1502   using format_arg = basic_format_arg<basic_format_context>;
1503   using parse_context_type = basic_format_parse_context<Char>;
1504   template <typename T> using formatter_type = formatter<T, char_type>;
1505 
1506   basic_format_context(const basic_format_context&) = delete;
1507   void operator=(const basic_format_context&) = delete;
1508   /**
1509    Constructs a ``basic_format_context`` object. References to the arguments are
1510    stored in the object so make sure they have appropriate lifetimes.
1511    */
1512   basic_format_context(OutputIt out,
1513                        basic_format_args<basic_format_context> ctx_args,
1514                        detail::locale_ref loc = detail::locale_ref())
1515       : out_(out), args_(ctx_args), loc_(loc) {}
1516 
1517   format_arg arg(int id) const { return args_.get(id); }
1518   format_arg arg(basic_string_view<char_type> name) { return args_.get(name); }
1519   int arg_id(basic_string_view<char_type> name) { return args_.get_id(name); }
1520   const basic_format_args<basic_format_context>& args() const { return args_; }
1521 
1522   detail::error_handler error_handler() { return {}; }
1523   void on_error(const char* message) { error_handler().on_error(message); }
1524 
1525   // Returns an iterator to the beginning of the output range.
1526   iterator out() { return out_; }
1527 
1528   // Advances the begin iterator to ``it``.
1529   void advance_to(iterator it) {
1530     if (!detail::is_back_insert_iterator<iterator>()) out_ = it;
1531   }
1532 
1533   detail::locale_ref locale() { return loc_; }
1534 };
1535 
1536 template <typename Char>
1537 using buffer_context =
1538     basic_format_context<detail::buffer_appender<Char>, Char>;
1539 using format_context = buffer_context<char>;
1540 using wformat_context = buffer_context<wchar_t>;
1541 
1542 // Workaround an alias issue: https://stackoverflow.com/q/62767544/471164.
1543 #define FMT_BUFFER_CONTEXT(Char) \
1544   basic_format_context<detail::buffer_appender<Char>, Char>
1545 
1546 /**
1547   \rst
1548   An array of references to arguments. It can be implicitly converted into
1549   `~fmt::basic_format_args` for passing into type-erased formatting functions
1550   such as `~fmt::vformat`.
1551   \endrst
1552  */
1553 template <typename Context, typename... Args>
1554 class format_arg_store
1555 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
1556     // Workaround a GCC template argument substitution bug.
1557     : public basic_format_args<Context>
1558 #endif
1559 {
1560  private:
1561   static const size_t num_args = sizeof...(Args);
1562   static const size_t num_named_args = detail::count_named_args<Args...>();
1563   static const bool is_packed = num_args <= detail::max_packed_args;
1564 
1565   using value_type = conditional_t<is_packed, detail::value<Context>,
1566                                    basic_format_arg<Context>>;
1567 
1568   detail::arg_data<value_type, typename Context::char_type, num_args,
1569                    num_named_args>
1570       data_;
1571 
1572   friend class basic_format_args<Context>;
1573 
1574   static constexpr unsigned long long desc =
1575       (is_packed ? detail::encode_types<Context, Args...>()
1576                  : detail::is_unpacked_bit | num_args) |
1577       (num_named_args != 0
1578            ? static_cast<unsigned long long>(detail::has_named_args_bit)
1579            : 0);
1580 
1581  public:
1582   format_arg_store(const Args&... args)
1583       :
1584 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
1585         basic_format_args<Context>(*this),
1586 #endif
1587         data_{detail::make_arg<
1588             is_packed, Context,
1589             detail::mapped_type_constant<Args, Context>::value>(args)...} {
1590     detail::init_named_args(data_.named_args(), 0, 0, args...);
1591   }
1592 };
1593 
1594 /**
1595   \rst
1596   Constructs a `~fmt::format_arg_store` object that contains references to
1597   arguments and can be implicitly converted to `~fmt::format_args`. `Context`
1598   can be omitted in which case it defaults to `~fmt::context`.
1599   See `~fmt::arg` for lifetime considerations.
1600   \endrst
1601  */
1602 template <typename Context = format_context, typename... Args>
1603 inline format_arg_store<Context, Args...> make_format_args(
1604     const Args&... args) {
1605   return {args...};
1606 }
1607 
1608 /**
1609   \rst
1610   Constructs a `~fmt::format_arg_store` object that contains references
1611   to arguments and can be implicitly converted to `~fmt::format_args`.
1612   If ``format_str`` is a compile-time string then `make_args_checked` checks
1613   its validity at compile time.
1614   \endrst
1615  */
1616 template <typename... Args, typename S, typename Char = char_t<S>>
1617 inline auto make_args_checked(const S& format_str,
1618                               const remove_reference_t<Args>&... args)
1619     -> format_arg_store<buffer_context<Char>, remove_reference_t<Args>...> {
1620   static_assert(
1621       detail::count<(
1622               std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
1623               std::is_reference<Args>::value)...>() == 0,
1624       "passing views as lvalues is disallowed");
1625   detail::check_format_string<Args...>(format_str);
1626   return {args...};
1627 }
1628 
1629 /**
1630   \rst
1631   Returns a named argument to be used in a formatting function. It should only
1632   be used in a call to a formatting function.
1633 
1634   **Example**::
1635 
1636     fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23));
1637   \endrst
1638  */
1639 template <typename Char, typename T>
1640 inline detail::named_arg<Char, T> arg(const Char* name, const T& arg) {
1641   static_assert(!detail::is_named_arg<T>(), "nested named arguments");
1642   return {name, arg};
1643 }
1644 
1645 /**
1646   \rst
1647   A dynamic version of `fmt::format_arg_store`.
1648   It's equipped with a storage to potentially temporary objects which lifetimes
1649   could be shorter than the format arguments object.
1650 
1651   It can be implicitly converted into `~fmt::basic_format_args` for passing
1652   into type-erased formatting functions such as `~fmt::vformat`.
1653   \endrst
1654  */
1655 template <typename Context>
1656 class dynamic_format_arg_store
1657 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
1658     // Workaround a GCC template argument substitution bug.
1659     : public basic_format_args<Context>
1660 #endif
1661 {
1662  private:
1663   using char_type = typename Context::char_type;
1664 
1665   template <typename T> struct need_copy {
1666     static constexpr detail::type mapped_type =
1667         detail::mapped_type_constant<T, Context>::value;
1668 
1669     enum {
1670       value = !(detail::is_reference_wrapper<T>::value ||
1671                 std::is_same<T, basic_string_view<char_type>>::value ||
1672                 std::is_same<T, detail::std_string_view<char_type>>::value ||
1673                 (mapped_type != detail::type::cstring_type &&
1674                  mapped_type != detail::type::string_type &&
1675                  mapped_type != detail::type::custom_type))
1676     };
1677   };
1678 
1679   template <typename T>
1680   using stored_type = conditional_t<detail::is_string<T>::value,
1681                                     std::basic_string<char_type>, T>;
1682 
1683   // Storage of basic_format_arg must be contiguous.
1684   std::vector<basic_format_arg<Context>> data_;
1685   std::vector<detail::named_arg_info<char_type>> named_info_;
1686 
1687   // Storage of arguments not fitting into basic_format_arg must grow
1688   // without relocation because items in data_ refer to it.
1689   detail::dynamic_arg_list dynamic_args_;
1690 
1691   friend class basic_format_args<Context>;
1692 
1693   unsigned long long get_types() const {
1694     return detail::is_unpacked_bit | data_.size() |
1695            (named_info_.empty()
1696                 ? 0ULL
1697                 : static_cast<unsigned long long>(detail::has_named_args_bit));
1698   }
1699 
1700   const basic_format_arg<Context>* data() const {
1701     return named_info_.empty() ? data_.data() : data_.data() + 1;
1702   }
1703 
1704   template <typename T> void emplace_arg(const T& arg) {
1705     data_.emplace_back(detail::make_arg<Context>(arg));
1706   }
1707 
1708   template <typename T>
1709   void emplace_arg(const detail::named_arg<char_type, T>& arg) {
1710     if (named_info_.empty()) {
1711       constexpr const detail::named_arg_info<char_type>* zero_ptr{nullptr};
1712       data_.insert(data_.begin(), {zero_ptr, 0});
1713     }
1714     data_.emplace_back(detail::make_arg<Context>(detail::unwrap(arg.value)));
1715     auto pop_one = [](std::vector<basic_format_arg<Context>>* data) {
1716       data->pop_back();
1717     };
1718     std::unique_ptr<std::vector<basic_format_arg<Context>>, decltype(pop_one)>
1719         guard{&data_, pop_one};
1720     named_info_.push_back({arg.name, static_cast<int>(data_.size() - 2u)});
1721     data_[0].value_.named_args = {named_info_.data(), named_info_.size()};
1722     guard.release();
1723   }
1724 
1725  public:
1726   /**
1727     \rst
1728     Adds an argument into the dynamic store for later passing to a formatting
1729     function.
1730 
1731     Note that custom types and string types (but not string views) are copied
1732     into the store dynamically allocating memory if necessary.
1733 
1734     **Example**::
1735 
1736       fmt::dynamic_format_arg_store<fmt::format_context> store;
1737       store.push_back(42);
1738       store.push_back("abc");
1739       store.push_back(1.5f);
1740       std::string result = fmt::vformat("{} and {} and {}", store);
1741     \endrst
1742   */
1743   template <typename T> void push_back(const T& arg) {
1744     if (detail::const_check(need_copy<T>::value))
1745       emplace_arg(dynamic_args_.push<stored_type<T>>(arg));
1746     else
1747       emplace_arg(detail::unwrap(arg));
1748   }
1749 
1750   /**
1751     \rst
1752     Adds a reference to the argument into the dynamic store for later passing to
1753     a formatting function. Supports named arguments wrapped in
1754     ``std::reference_wrapper`` via ``std::ref()``/``std::cref()``.
1755 
1756     **Example**::
1757 
1758       fmt::dynamic_format_arg_store<fmt::format_context> store;
1759       char str[] = "1234567890";
1760       store.push_back(std::cref(str));
1761       int a1_val{42};
1762       auto a1 = fmt::arg("a1_", a1_val);
1763       store.push_back(std::cref(a1));
1764 
1765       // Changing str affects the output but only for string and custom types.
1766       str[0] = 'X';
1767 
1768       std::string result = fmt::vformat("{} and {a1_}");
1769       assert(result == "X234567890 and 42");
1770     \endrst
1771   */
1772   template <typename T> void push_back(std::reference_wrapper<T> arg) {
1773     static_assert(
1774         detail::is_named_arg<typename std::remove_cv<T>::type>::value ||
1775             need_copy<T>::value,
1776         "objects of built-in types and string views are always copied");
1777     emplace_arg(arg.get());
1778   }
1779 
1780   /**
1781     Adds named argument into the dynamic store for later passing to a formatting
1782     function. ``std::reference_wrapper`` is supported to avoid copying of the
1783     argument.
1784   */
1785   template <typename T>
1786   void push_back(const detail::named_arg<char_type, T>& arg) {
1787     const char_type* arg_name =
1788         dynamic_args_.push<std::basic_string<char_type>>(arg.name).c_str();
1789     if (detail::const_check(need_copy<T>::value)) {
1790       emplace_arg(
1791           fmt::arg(arg_name, dynamic_args_.push<stored_type<T>>(arg.value)));
1792     } else {
1793       emplace_arg(fmt::arg(arg_name, arg.value));
1794     }
1795   }
1796 
1797   /** Erase all elements from the store */
1798   void clear() {
1799     data_.clear();
1800     named_info_.clear();
1801     dynamic_args_ = detail::dynamic_arg_list();
1802   }
1803 
1804   /**
1805     \rst
1806     Reserves space to store at least *new_cap* arguments including
1807     *new_cap_named* named arguments.
1808     \endrst
1809   */
1810   void reserve(size_t new_cap, size_t new_cap_named) {
1811     FMT_ASSERT(new_cap >= new_cap_named,
1812                "Set of arguments includes set of named arguments");
1813     data_.reserve(new_cap);
1814     named_info_.reserve(new_cap_named);
1815   }
1816 };
1817 
1818 /**
1819   \rst
1820   A view of a collection of formatting arguments. To avoid lifetime issues it
1821   should only be used as a parameter type in type-erased functions such as
1822   ``vformat``::
1823 
1824     void vlog(string_view format_str, format_args args);  // OK
1825     format_args args = make_format_args(42);  // Error: dangling reference
1826   \endrst
1827  */
1828 template <typename Context> class basic_format_args {
1829  public:
1830   using size_type = int;
1831   using format_arg = basic_format_arg<Context>;
1832 
1833  private:
1834   // A descriptor that contains information about formatting arguments.
1835   // If the number of arguments is less or equal to max_packed_args then
1836   // argument types are passed in the descriptor. This reduces binary code size
1837   // per formatting function call.
1838   unsigned long long desc_;
1839   union {
1840     // If is_packed() returns true then argument values are stored in values_;
1841     // otherwise they are stored in args_. This is done to improve cache
1842     // locality and reduce compiled code size since storing larger objects
1843     // may require more code (at least on x86-64) even if the same amount of
1844     // data is actually copied to stack. It saves ~10% on the bloat test.
1845     const detail::value<Context>* values_;
1846     const format_arg* args_;
1847   };
1848 
1849   bool is_packed() const { return (desc_ & detail::is_unpacked_bit) == 0; }
1850   bool has_named_args() const {
1851     return (desc_ & detail::has_named_args_bit) != 0;
1852   }
1853 
1854   detail::type type(int index) const {
1855     int shift = index * detail::packed_arg_bits;
1856     unsigned int mask = (1 << detail::packed_arg_bits) - 1;
1857     return static_cast<detail::type>((desc_ >> shift) & mask);
1858   }
1859 
1860   basic_format_args(unsigned long long desc,
1861                     const detail::value<Context>* values)
1862       : desc_(desc), values_(values) {}
1863   basic_format_args(unsigned long long desc, const format_arg* args)
1864       : desc_(desc), args_(args) {}
1865 
1866  public:
1867   basic_format_args() : desc_(0) {}
1868 
1869   /**
1870    \rst
1871    Constructs a `basic_format_args` object from `~fmt::format_arg_store`.
1872    \endrst
1873    */
1874   template <typename... Args>
1875   FMT_INLINE basic_format_args(const format_arg_store<Context, Args...>& store)
1876       : basic_format_args(store.desc, store.data_.args()) {}
1877 
1878   /**
1879    \rst
1880    Constructs a `basic_format_args` object from
1881    `~fmt::dynamic_format_arg_store`.
1882    \endrst
1883    */
1884   FMT_INLINE basic_format_args(const dynamic_format_arg_store<Context>& store)
1885       : basic_format_args(store.get_types(), store.data()) {}
1886 
1887   /**
1888    \rst
1889    Constructs a `basic_format_args` object from a dynamic set of arguments.
1890    \endrst
1891    */
1892   basic_format_args(const format_arg* args, int count)
1893       : basic_format_args(detail::is_unpacked_bit | detail::to_unsigned(count),
1894                           args) {}
1895 
1896   /** Returns the argument with the specified id. */
1897   format_arg get(int id) const {
1898     format_arg arg;
1899     if (!is_packed()) {
1900       if (id < max_size()) arg = args_[id];
1901       return arg;
1902     }
1903     if (id >= detail::max_packed_args) return arg;
1904     arg.type_ = type(id);
1905     if (arg.type_ == detail::type::none_type) return arg;
1906     arg.value_ = values_[id];
1907     return arg;
1908   }
1909 
1910   template <typename Char> format_arg get(basic_string_view<Char> name) const {
1911     int id = get_id(name);
1912     return id >= 0 ? get(id) : format_arg();
1913   }
1914 
1915   template <typename Char> int get_id(basic_string_view<Char> name) const {
1916     if (!has_named_args()) return -1;
1917     const auto& named_args =
1918         (is_packed() ? values_[-1] : args_[-1].value_).named_args;
1919     for (size_t i = 0; i < named_args.size; ++i) {
1920       if (named_args.data[i].name == name) return named_args.data[i].id;
1921     }
1922     return -1;
1923   }
1924 
1925   int max_size() const {
1926     unsigned long long max_packed = detail::max_packed_args;
1927     return static_cast<int>(is_packed() ? max_packed
1928                                         : desc_ & ~detail::is_unpacked_bit);
1929   }
1930 };
1931 
1932 #ifdef FMT_ARM_ABI_COMPATIBILITY
1933 /** An alias to ``basic_format_args<format_context>``. */
1934 // Separate types would result in shorter symbols but break ABI compatibility
1935 // between clang and gcc on ARM (#1919).
1936 using format_args = basic_format_args<format_context>;
1937 using wformat_args = basic_format_args<wformat_context>;
1938 #else
1939 // DEPRECATED! These are kept for ABI compatibility.
1940 // It is a separate type rather than an alias to make symbols readable.
1941 struct format_args : basic_format_args<format_context> {
1942   template <typename... Args>
1943   FMT_INLINE format_args(const Args&... args) : basic_format_args(args...) {}
1944 };
1945 struct wformat_args : basic_format_args<wformat_context> {
1946   using basic_format_args::basic_format_args;
1947 };
1948 #endif
1949 
1950 namespace detail {
1951 
1952 template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
1953 std::basic_string<Char> vformat(
1954     basic_string_view<Char> format_str,
1955     basic_format_args<buffer_context<type_identity_t<Char>>> args);
1956 
1957 FMT_API std::string vformat(string_view format_str, format_args args);
1958 
1959 template <typename Char>
1960 void vformat_to(
1961     buffer<Char>& buf, basic_string_view<Char> format_str,
1962     basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args,
1963     detail::locale_ref loc = {});
1964 
1965 template <typename Char, typename Args,
1966           FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
1967 inline void vprint_mojibake(std::FILE*, basic_string_view<Char>, const Args&) {}
1968 
1969 FMT_API void vprint_mojibake(std::FILE*, string_view, format_args);
1970 #ifndef _WIN32
1971 inline void vprint_mojibake(std::FILE*, string_view, format_args) {}
1972 #endif
1973 }  // namespace detail
1974 
1975 /** Formats a string and writes the output to ``out``. */
1976 // GCC 8 and earlier cannot handle std::back_insert_iterator<Container> with
1977 // vformat_to<ArgFormatter>(...) overload, so SFINAE on iterator type instead.
1978 template <typename OutputIt, typename S, typename Char = char_t<S>,
1979           bool enable = detail::is_output_iterator<OutputIt, Char>::value>
1980 auto vformat_to(OutputIt out, const S& format_str,
1981                 basic_format_args<buffer_context<type_identity_t<Char>>> args)
1982     -> typename std::enable_if<enable, OutputIt>::type {
1983   decltype(detail::get_buffer<Char>(out)) buf(detail::get_buffer_init(out));
1984   detail::vformat_to(buf, to_string_view(format_str), args);
1985   return detail::get_iterator(buf);
1986 }
1987 
1988 /**
1989  \rst
1990  Formats arguments, writes the result to the output iterator ``out`` and returns
1991  the iterator past the end of the output range.
1992 
1993  **Example**::
1994 
1995    std::vector<char> out;
1996    fmt::format_to(std::back_inserter(out), "{}", 42);
1997  \endrst
1998  */
1999 // We cannot use FMT_ENABLE_IF because of a bug in gcc 8.3.
2000 template <typename OutputIt, typename S, typename... Args,
2001           bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value>
2002 inline auto format_to(OutputIt out, const S& format_str, Args&&... args) ->
2003     typename std::enable_if<enable, OutputIt>::type {
2004   const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
2005   return vformat_to(out, to_string_view(format_str), vargs);
2006 }
2007 
2008 template <typename OutputIt> struct format_to_n_result {
2009   /** Iterator past the end of the output range. */
2010   OutputIt out;
2011   /** Total (not truncated) output size. */
2012   size_t size;
2013 };
2014 
2015 template <typename OutputIt, typename Char, typename... Args,
2016           FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value)>
2017 inline format_to_n_result<OutputIt> vformat_to_n(
2018     OutputIt out, size_t n, basic_string_view<Char> format_str,
2019     basic_format_args<buffer_context<type_identity_t<Char>>> args) {
2020   detail::iterator_buffer<OutputIt, Char, detail::fixed_buffer_traits> buf(out,
2021                                                                            n);
2022   detail::vformat_to(buf, format_str, args);
2023   return {buf.out(), buf.count()};
2024 }
2025 
2026 /**
2027  \rst
2028  Formats arguments, writes up to ``n`` characters of the result to the output
2029  iterator ``out`` and returns the total output size and the iterator past the
2030  end of the output range.
2031  \endrst
2032  */
2033 template <typename OutputIt, typename S, typename... Args,
2034           bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value>
2035 inline auto format_to_n(OutputIt out, size_t n, const S& format_str,
2036                         const Args&... args) ->
2037     typename std::enable_if<enable, format_to_n_result<OutputIt>>::type {
2038   const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
2039   return vformat_to_n(out, n, to_string_view(format_str), vargs);
2040 }
2041 
2042 /**
2043   Returns the number of characters in the output of
2044   ``format(format_str, args...)``.
2045  */
2046 template <typename... Args>
2047 inline size_t formatted_size(string_view format_str, Args&&... args) {
2048   const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
2049   detail::counting_buffer<> buf;
2050   detail::vformat_to(buf, format_str, vargs);
2051   return buf.count();
2052 }
2053 
2054 template <typename S, typename Char = char_t<S>>
2055 FMT_INLINE std::basic_string<Char> vformat(
2056     const S& format_str,
2057     basic_format_args<buffer_context<type_identity_t<Char>>> args) {
2058   return detail::vformat(to_string_view(format_str), args);
2059 }
2060 
2061 /**
2062   \rst
2063   Formats arguments and returns the result as a string.
2064 
2065   **Example**::
2066 
2067     #include <fmt/core.h>
2068     std::string message = fmt::format("The answer is {}", 42);
2069   \endrst
2070 */
2071 // Pass char_t as a default template parameter instead of using
2072 // std::basic_string<char_t<S>> to reduce the symbol size.
2073 template <typename S, typename... Args, typename Char = char_t<S>>
2074 FMT_INLINE std::basic_string<Char> format(const S& format_str, Args&&... args) {
2075   const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
2076   return detail::vformat(to_string_view(format_str), vargs);
2077 }
2078 
2079 FMT_API void vprint(string_view, format_args);
2080 FMT_API void vprint(std::FILE*, string_view, format_args);
2081 
2082 /**
2083   \rst
2084   Formats ``args`` according to specifications in ``format_str`` and writes the
2085   output to the file ``f``. Strings are assumed to be Unicode-encoded unless the
2086   ``FMT_UNICODE`` macro is set to 0.
2087 
2088   **Example**::
2089 
2090     fmt::print(stderr, "Don't {}!", "panic");
2091   \endrst
2092  */
2093 template <typename S, typename... Args, typename Char = char_t<S>>
2094 inline void print(std::FILE* f, const S& format_str, Args&&... args) {
2095   const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
2096   return detail::is_unicode<Char>()
2097              ? vprint(f, to_string_view(format_str), vargs)
2098              : detail::vprint_mojibake(f, to_string_view(format_str), vargs);
2099 }
2100 
2101 /**
2102   \rst
2103   Formats ``args`` according to specifications in ``format_str`` and writes
2104   the output to ``stdout``. Strings are assumed to be Unicode-encoded unless
2105   the ``FMT_UNICODE`` macro is set to 0.
2106 
2107   **Example**::
2108 
2109     fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
2110   \endrst
2111  */
2112 template <typename S, typename... Args, typename Char = char_t<S>>
2113 inline void print(const S& format_str, Args&&... args) {
2114   const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
2115   return detail::is_unicode<Char>()
2116              ? vprint(to_string_view(format_str), vargs)
2117              : detail::vprint_mojibake(stdout, to_string_view(format_str),
2118                                        vargs);
2119 }
2120 FMT_END_NAMESPACE
2121 
2122 #endif  // FMT_CORE_H_
2123