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