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