Debian Codegraph @

src/common/format.h

raw symbols SCIP
1 /*
2 Formatting library for C++
3
4 Copyright (c) 2012 - 2016, Victor Zverovich
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9
10 1. Redistributions of source code must retain the above copyright notice, this
11 list of conditions and the following disclaimer.
12 2. Redistributions in binary form must reproduce the above copyright notice,
13 this list of conditions and the following disclaimer in the documentation
14 and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
20 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #ifndef FMT_FORMAT_H_
29 #define FMT_FORMAT_H_
30
31 #include <cassert>
32 #include <clocale>
33 #include <cmath>
34 #include <cstdio>
35 #include <cstring>
36 #include <limits>
37 #include <memory>
38 #include <stdexcept>
39 #include <string>
40 #include <vector>
41 #include <utility>
42
43 #ifdef _SECURE_SCL
44 # define FMT_SECURE_SCL _SECURE_SCL
45 #else
46 # define FMT_SECURE_SCL 0
47 #endif
48
49 #if FMT_SECURE_SCL
50 # include <iterator>
51 #endif
52
53 #ifdef _MSC_VER
54 # define FMT_MSC_VER _MSC_VER
55 #else
56 # define FMT_MSC_VER 0
57 #endif
58
59 #if FMT_MSC_VER && FMT_MSC_VER <= 1500
60 typedef unsigned __int32 uint32_t;
61 typedef unsigned __int64 uint64_t;
62 typedef __int64 intmax_t;
63 #else
64 #include <stdint.h>
65 #endif
66
67 #if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
68 # ifdef FMT_EXPORT
69 # define FMT_API __declspec(dllexport)
70 # elif defined(FMT_SHARED)
71 # define FMT_API __declspec(dllimport)
72 # endif
73 #endif
74 #ifndef FMT_API
75 # define FMT_API
76 #endif
77
78 #ifdef __GNUC__
79 # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
80 # define FMT_GCC_EXTENSION __extension__
81 # if FMT_GCC_VERSION >= 406
82 # pragma GCC diagnostic push
83 // Disable the warning about "long long" which is sometimes reported even
84 // when using __extension__.
85 # pragma GCC diagnostic ignored "-Wlong-long"
86 // Disable the warning about declaration shadowing because it affects too
87 // many valid cases.
88 # pragma GCC diagnostic ignored "-Wshadow"
89 // Disable the warning about implicit conversions that may change the sign of
90 // an integer; silencing it otherwise would require many explicit casts.
91 # pragma GCC diagnostic ignored "-Wsign-conversion"
92 # endif
93 # if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__
94 # define FMT_HAS_GXX_CXX11 1
95 # endif
96 #else
97 # define FMT_GCC_EXTENSION
98 #endif
99
100 #if defined(__INTEL_COMPILER)
101 # define FMT_ICC_VERSION __INTEL_COMPILER
102 #elif defined(__ICL)
103 # define FMT_ICC_VERSION __ICL
104 #endif
105
106 #if defined(__clang__) && !defined(FMT_ICC_VERSION)
107 # pragma clang diagnostic push
108 # pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
109 # pragma clang diagnostic ignored "-Wpadded"
110 #endif
111
112 #ifdef __GNUC_LIBSTD__
113 # define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__)
114 #endif
115
116 #ifdef __has_feature
117 # define FMT_HAS_FEATURE(x) __has_feature(x)
118 #else
119 # define FMT_HAS_FEATURE(x) 0
120 #endif
121
122 #ifdef __has_builtin
123 # define FMT_HAS_BUILTIN(x) __has_builtin(x)
124 #else
125 # define FMT_HAS_BUILTIN(x) 0
126 #endif
127
128 #ifdef __has_cpp_attribute
129 # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
130 #else
131 # define FMT_HAS_CPP_ATTRIBUTE(x) 0
132 #endif
133
134 #ifndef FMT_USE_VARIADIC_TEMPLATES
135 // Variadic templates are available in GCC since version 4.4
136 // (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++
137 // since version 2013.
138 # define FMT_USE_VARIADIC_TEMPLATES \
139 (FMT_HAS_FEATURE(cxx_variadic_templates) || \
140 (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800)
141 #endif
142
143 #ifndef FMT_USE_RVALUE_REFERENCES
144 // Don't use rvalue references when compiling with clang and an old libstdc++
145 // as the latter doesn't provide std::move.
146 # if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402
147 # define FMT_USE_RVALUE_REFERENCES 0
148 # else
149 # define FMT_USE_RVALUE_REFERENCES \
150 (FMT_HAS_FEATURE(cxx_rvalue_references) || \
151 (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600)
152 # endif
153 #endif
154
155 #if FMT_USE_RVALUE_REFERENCES
156 # include <utility> // for std::move
157 #endif
158
159 // Check if exceptions are disabled.
160 #if defined(__GNUC__) && !defined(__EXCEPTIONS)
161 # define FMT_EXCEPTIONS 0
162 #endif
163 #if FMT_MSC_VER && !_HAS_EXCEPTIONS
164 # define FMT_EXCEPTIONS 0
165 #endif
166 #ifndef FMT_EXCEPTIONS
167 # define FMT_EXCEPTIONS 1
168 #endif
169
170 #ifndef FMT_THROW
171 # if FMT_EXCEPTIONS
172 # define FMT_THROW(x) throw x
173 # else
174 # define FMT_THROW(x) assert(false)
175 # endif
176 #endif
177
178 // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature).
179 #ifndef FMT_USE_NOEXCEPT
180 # define FMT_USE_NOEXCEPT 0
181 #endif
182
183 #ifndef FMT_NOEXCEPT
184 # if FMT_EXCEPTIONS
185 # if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
186 (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \
187 FMT_MSC_VER >= 1900
188 # define FMT_NOEXCEPT noexcept
189 # else
190 # define FMT_NOEXCEPT throw()
191 # endif
192 # else
193 # define FMT_NOEXCEPT
194 # endif
195 #endif
196
197 #ifndef FMT_OVERRIDE
198 # if FMT_USE_OVERRIDE || FMT_HAS_FEATURE(cxx_override) || \
199 (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \
200 FMT_MSC_VER >= 1900
201 # define FMT_OVERRIDE override
202 # else
203 # define FMT_OVERRIDE
204 # endif
205 #endif
206
207
208 // A macro to disallow the copy constructor and operator= functions
209 // This should be used in the private: declarations for a class
210 #ifndef FMT_USE_DELETED_FUNCTIONS
211 # define FMT_USE_DELETED_FUNCTIONS 0
212 #endif
213
214 #if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || \
215 (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800
216 # define FMT_DELETED_OR_UNDEFINED = delete
217 # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \
218 TypeName(const TypeName&) = delete; \
219 TypeName& operator=(const TypeName&) = delete
220 #else
221 # define FMT_DELETED_OR_UNDEFINED
222 # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \
223 TypeName(const TypeName&); \
224 TypeName& operator=(const TypeName&)
225 #endif
226
227 #ifndef FMT_USE_USER_DEFINED_LITERALS
228 // All compilers which support UDLs also support variadic templates. This
229 // makes the fmt::literals implementation easier. However, an explicit check
230 // for variadic templates is added here just in case.
231 // For Intel's compiler both it and the system gcc/msc must support UDLs.
232 # define FMT_USE_USER_DEFINED_LITERALS \
233 FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES && \
234 (FMT_HAS_FEATURE(cxx_user_literals) || \
235 (FMT_GCC_VERSION >= 407 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900) && \
236 (!defined(FMT_ICC_VERSION) || FMT_ICC_VERSION >= 1500)
237 #endif
238
239 #ifndef FMT_ASSERT
240 # define FMT_ASSERT(condition, message) assert((condition) && message)
241 #endif
242
243 #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz)
244 # define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
245 #endif
246
247 #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll)
248 # define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
249 #endif
250
251 // Some compilers masquerade as both MSVC and GCC-likes or
252 // otherwise support __builtin_clz and __builtin_clzll, so
253 // only define FMT_BUILTIN_CLZ using the MSVC intrinsics
254 // if the clz and clzll builtins are not available.
255 #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL)
256 # include <intrin.h> // _BitScanReverse, _BitScanReverse64
257
258 namespace fmt {
259 namespace internal {
260 # pragma intrinsic(_BitScanReverse)
261 inline uint32_t clz(uint32_t x) {
262 unsigned long r = 0;
263 _BitScanReverse(&r, x);
264
265 assert(x != 0);
266 // Static analysis complains about using uninitialized data
267 // "r", but the only way that can happen is if "x" is 0,
268 // which the callers guarantee to not happen.
269 # pragma warning(suppress: 6102)
270 return 31 - r;
271 }
272 # define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n)
273
274 # ifdef _WIN64
275 # pragma intrinsic(_BitScanReverse64)
276 # endif
277
278 inline uint32_t clzll(uint64_t x) {
279 unsigned long r = 0;
280 # ifdef _WIN64
281 _BitScanReverse64(&r, x);
282 # else
283 // Scan the high 32 bits.
284 if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32)))
285 return 63 - (r + 32);
286
287 // Scan the low 32 bits.
288 _BitScanReverse(&r, static_cast<uint32_t>(x));
289 # endif
290
291 assert(x != 0);
292 // Static analysis complains about using uninitialized data
293 // "r", but the only way that can happen is if "x" is 0,
294 // which the callers guarantee to not happen.
295 # pragma warning(suppress: 6102)
296 return 63 - r;
297 }
298 # define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n)
299 }
300 }
301 #endif
302
303 namespace fmt {
304 namespace internal {
305 struct DummyInt {
306 int data[2];
307 operator int() const { return 0; }
308 };
309 typedef std::numeric_limits<fmt::internal::DummyInt> FPUtil;
310
311 // Dummy implementations of system functions such as signbit and ecvt called
312 // if the latter are not available.
313 inline DummyInt signbit(...) { return DummyInt(); }
314 inline DummyInt _ecvt_s(...) { return DummyInt(); }
315 inline DummyInt isinf(...) { return DummyInt(); }
316 inline DummyInt _finite(...) { return DummyInt(); }
317 inline DummyInt isnan(...) { return DummyInt(); }
318 inline DummyInt _isnan(...) { return DummyInt(); }
319
320 // A helper function to suppress bogus "conditional expression is constant"
321 // warnings.
322 template <typename T>
323 inline T const_check(T value) { return value; }
324 }
325 } // namespace fmt
326
327 namespace std {
328 // Standard permits specialization of std::numeric_limits. This specialization
329 // is used to resolve ambiguity between isinf and std::isinf in glibc:
330 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891
331 // and the same for isnan and signbit.
332 template <>
333 class numeric_limits<fmt::internal::DummyInt> :
334 public std::numeric_limits<int> {
335 public:
336 // Portable version of isinf.
337 template <typename T>
338 static bool isinfinity(T x) {
339 using namespace fmt::internal;
340 // The resolution "priority" is:
341 // isinf macro > std::isinf > ::isinf > fmt::internal::isinf
342 if (const_check(sizeof(isinf(x)) == sizeof(bool) ||
343 sizeof(isinf(x)) == sizeof(int))) {
344 return isinf(x) != 0;
345 }
346 return !_finite(static_cast<double>(x));
347 }
348
349 // Portable version of isnan.
350 template <typename T>
351 static bool isnotanumber(T x) {
352 using namespace fmt::internal;
353 if (const_check(sizeof(isnan(x)) == sizeof(bool) ||
354 sizeof(isnan(x)) == sizeof(int))) {
355 return isnan(x) != 0;
356 }
357 return _isnan(static_cast<double>(x)) != 0;
358 }
359
360 // Portable version of signbit.
361 static bool isnegative(double x) {
362 using namespace fmt::internal;
363 if (const_check(sizeof(signbit(x)) == sizeof(int)))
364 return signbit(x) != 0;
365 if (x < 0) return true;
366 if (!isnotanumber(x)) return false;
367 int dec = 0, sign = 0;
368 char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail.
369 _ecvt_s(buffer, sizeof(buffer), x, 0, &dec, &sign);
370 return sign != 0;
371 }
372 };
373 } // namespace std
374
375 namespace fmt {
376
377 // Fix the warning about long long on older versions of GCC
378 // that don't support the diagnostic pragma.
379 FMT_GCC_EXTENSION typedef long long LongLong;
380 FMT_GCC_EXTENSION typedef unsigned long long ULongLong;
381
382 #if FMT_USE_RVALUE_REFERENCES
383 using std::move;
384 #endif
385
386 template <typename Char>
387 class BasicWriter;
388
389 typedef BasicWriter<char> Writer;
390 typedef BasicWriter<wchar_t> WWriter;
391
392 template <typename Char>
393 class ArgFormatter;
394
395 template <typename CharType,
396 typename ArgFormatter = fmt::ArgFormatter<CharType> >
397 class BasicFormatter;
398
399 /**
400 \rst
401 A string reference. It can be constructed from a C string or ``std::string``.
402
403 You can use one of the following typedefs for common character types:
404
405 +------------+-------------------------+
406 | Type | Definition |
407 +============+=========================+
408 | StringRef | BasicStringRef<char> |
409 +------------+-------------------------+
410 | WStringRef | BasicStringRef<wchar_t> |
411 +------------+-------------------------+
412
413 This class is most useful as a parameter type to allow passing
414 different types of strings to a function, for example::
415
416 template <typename... Args>
417 std::string format(StringRef format_str, const Args & ... args);
418
419 format("{}", 42);
420 format(std::string("{}"), 42);
421 \endrst
422 */
423 template <typename Char>
424 class BasicStringRef {
425 private:
426 const Char *data_;
427 std::size_t size_;
428
429 public:
430 /** Constructs a string reference object from a C string and a size. */
431 BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {}
432
433 /**
434 \rst
435 Constructs a string reference object from a C string computing
436 the size with ``std::char_traits<Char>::length``.
437 \endrst
438 */
439 BasicStringRef(const Char *s)
440 : data_(s), size_(std::char_traits<Char>::length(s)) {}
441
442 /**
443 \rst
444 Constructs a string reference from an ``std::string`` object.
445 \endrst
446 */
447 BasicStringRef(const std::basic_string<Char> &s)
448 : data_(s.c_str()), size_(s.size()) {}
449
450 /**
451 \rst
452 Converts a string reference to an ``std::string`` object.
453 \endrst
454 */
455 std::basic_string<Char> to_string() const {
456 return std::basic_string<Char>(data_, size_);
457 }
458
459 /** Returns a pointer to the string data. */
460 const Char *data() const { return data_; }
461
462 /** Returns the string size. */
463 std::size_t size() const { return size_; }
464
465 // Lexicographically compare this string reference to other.
466 int compare(BasicStringRef other) const {
467 std::size_t size = size_ < other.size_ ? size_ : other.size_;
468 int result = std::char_traits<Char>::compare(data_, other.data_, size);
469 if (result == 0)
470 result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
471 return result;
472 }
473
474 friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) {
475 return lhs.compare(rhs) == 0;
476 }
477 friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) {
478 return lhs.compare(rhs) != 0;
479 }
480 friend bool operator<(BasicStringRef lhs, BasicStringRef rhs) {
481 return lhs.compare(rhs) < 0;
482 }
483 friend bool operator<=(BasicStringRef lhs, BasicStringRef rhs) {
484 return lhs.compare(rhs) <= 0;
485 }
486 friend bool operator>(BasicStringRef lhs, BasicStringRef rhs) {
487 return lhs.compare(rhs) > 0;
488 }
489 friend bool operator>=(BasicStringRef lhs, BasicStringRef rhs) {
490 return lhs.compare(rhs) >= 0;
491 }
492 };
493
494 typedef BasicStringRef<char> StringRef;
495 typedef BasicStringRef<wchar_t> WStringRef;
496
497 /**
498 \rst
499 A reference to a null terminated string. It can be constructed from a C
500 string or ``std::string``.
501
502 You can use one of the following typedefs for common character types:
503
504 +-------------+--------------------------+
505 | Type | Definition |
506 +=============+==========================+
507 | CStringRef | BasicCStringRef<char> |
508 +-------------+--------------------------+
509 | WCStringRef | BasicCStringRef<wchar_t> |
510 +-------------+--------------------------+
511
512 This class is most useful as a parameter type to allow passing
513 different types of strings to a function, for example::
514
515 template <typename... Args>
516 std::string format(CStringRef format_str, const Args & ... args);
517
518 format("{}", 42);
519 format(std::string("{}"), 42);
520 \endrst
521 */
522 template <typename Char>
523 class BasicCStringRef {
524 private:
525 const Char *data_;
526
527 public:
528 /** Constructs a string reference object from a C string. */
529 BasicCStringRef(const Char *s) : data_(s) {}
530
531 /**
532 \rst
533 Constructs a string reference from an ``std::string`` object.
534 \endrst
535 */
536 BasicCStringRef(const std::basic_string<Char> &s) : data_(s.c_str()) {}
537
538 /** Returns the pointer to a C string. */
539 const Char *c_str() const { return data_; }
540 };
541
542 typedef BasicCStringRef<char> CStringRef;
543 typedef BasicCStringRef<wchar_t> WCStringRef;
544
545 /** A formatting error such as invalid format string. */
546 class FormatError : public std::runtime_error {
547 public:
548 explicit FormatError(CStringRef message)
549 : std::runtime_error(message.c_str()) {}
550 ~FormatError() throw();
551 };
552
553 namespace internal {
554
555 // MakeUnsigned<T>::Type gives an unsigned type corresponding to integer type T.
556 template <typename T>
557 struct MakeUnsigned { typedef T Type; };
558
559 #define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \
560 template <> \
561 struct MakeUnsigned<T> { typedef U Type; }
562
563 FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char);
564 FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char);
565 FMT_SPECIALIZE_MAKE_UNSIGNED(short, unsigned short);
566 FMT_SPECIALIZE_MAKE_UNSIGNED(int, unsigned);
567 FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long);
568 FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong);
569
570 // Casts nonnegative integer to unsigned.
571 template <typename Int>
572 inline typename MakeUnsigned<Int>::Type to_unsigned(Int value) {
573 FMT_ASSERT(value >= 0, "negative value");
574 return static_cast<typename MakeUnsigned<Int>::Type>(value);
575 }
576
577 // The number of characters to store in the MemoryBuffer object itself
578 // to avoid dynamic memory allocation.
579 enum { INLINE_BUFFER_SIZE = 500 };
580
581 #if FMT_SECURE_SCL
582 // Use checked iterator to avoid warnings on MSVC.
583 template <typename T>
584 inline stdext::checked_array_iterator<T*> make_ptr(T *ptr, std::size_t size) {
585 return stdext::checked_array_iterator<T*>(ptr, size);
586 }
587 #else
588 template <typename T>
589 inline T *make_ptr(T *ptr, std::size_t) { return ptr; }
590 #endif
591 } // namespace internal
592
593 /**
594 \rst
595 A buffer supporting a subset of ``std::vector``'s operations.
596 \endrst
597 */
598 template <typename T>
599 class Buffer {
600 private:
601 FMT_DISALLOW_COPY_AND_ASSIGN(Buffer);
602
603 protected:
604 T *ptr_;
605 std::size_t size_;
606 std::size_t capacity_;
607
608 Buffer(T *ptr = 0, std::size_t capacity = 0)
609 : ptr_(ptr), size_(0), capacity_(capacity) {}
610
611 /**
612 \rst
613 Increases the buffer capacity to hold at least *size* elements updating
614 ``ptr_`` and ``capacity_``.
615 \endrst
616 */
617 virtual void grow(std::size_t size) = 0;
618
619 public:
620 virtual ~Buffer() {}
621
622 /** Returns the size of this buffer. */
623 std::size_t size() const { return size_; }
624
625 /** Returns the capacity of this buffer. */
626 std::size_t capacity() const { return capacity_; }
627
628 /**
629 Resizes the buffer. If T is a POD type new elements may not be initialized.
630 */
631 void resize(std::size_t new_size) {
632 if (new_size > capacity_)
633 grow(new_size);
634 size_ = new_size;
635 }
636
637 /**
638 \rst
639 Reserves space to store at least *capacity* elements.
640 \endrst
641 */
642 void reserve(std::size_t capacity) {
643 if (capacity > capacity_)
644 grow(capacity);
645 }
646
647 void clear() FMT_NOEXCEPT { size_ = 0; }
648
649 void push_back(const T &value) {
650 if (size_ == capacity_)
651 grow(size_ + 1);
652 ptr_[size_++] = value;
653 }
654
655 /** Appends data to the end of the buffer. */
656 template <typename U>
657 void append(const U *begin, const U *end);
658
659 T &operator[](std::size_t index) { return ptr_[index]; }
660 const T &operator[](std::size_t index) const { return ptr_[index]; }
661 };
662
663 template <typename T>
664 template <typename U>
665 void Buffer<T>::append(const U *begin, const U *end) {
666 std::size_t new_size = size_ + internal::to_unsigned(end - begin);
667 if (new_size > capacity_)
668 grow(new_size);
669 std::uninitialized_copy(begin, end,
670 internal::make_ptr(ptr_, capacity_) + size_);
671 size_ = new_size;
672 }
673
674 namespace internal {
675
676 // A memory buffer for trivially copyable/constructible types with the first
677 // SIZE elements stored in the object itself.
678 template <typename T, std::size_t SIZE, typename Allocator = std::allocator<T> >
679 class MemoryBuffer : private Allocator, public Buffer<T> {
680 private:
681 T data_[SIZE];
682
683 // Deallocate memory allocated by the buffer.
684 void deallocate() {
685 if (this->ptr_ != data_) Allocator::deallocate(this->ptr_, this->capacity_);
686 }
687
688 protected:
689 void grow(std::size_t size) FMT_OVERRIDE;
690
691 public:
692 explicit MemoryBuffer(const Allocator &alloc = Allocator())
693 : Allocator(alloc), Buffer<T>(data_, SIZE) {}
694 ~MemoryBuffer() { deallocate(); }
695
696 #if FMT_USE_RVALUE_REFERENCES
697 private:
698 // Move data from other to this buffer.
699 void move(MemoryBuffer &other) {
700 Allocator &this_alloc = *this, &other_alloc = other;
701 this_alloc = std::move(other_alloc);
702 this->size_ = other.size_;
703 this->capacity_ = other.capacity_;
704 if (other.ptr_ == other.data_) {
705 this->ptr_ = data_;
706 std::uninitialized_copy(other.data_, other.data_ + this->size_,
707 make_ptr(data_, this->capacity_));
708 }
709 else {
710 this->ptr_ = other.ptr_;
711 // Set pointer to the inline array so that delete is not called
712 // when deallocating.
713 other.ptr_ = other.data_;
714 }
715 }
716
717 public:
718 MemoryBuffer(MemoryBuffer &&other) {
719 move(other);
720 }
721
722 MemoryBuffer &operator=(MemoryBuffer &&other) {
723 assert(this != &other);
724 deallocate();
725 move(other);
726 return *this;
727 }
728 #endif
729
730 // Returns a copy of the allocator associated with this buffer.
731 Allocator get_allocator() const { return *this; }
732 };
733
734 template <typename T, std::size_t SIZE, typename Allocator>
735 void MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t size) {
736 std::size_t new_capacity = this->capacity_ + this->capacity_ / 2;
737 if (size > new_capacity)
738 new_capacity = size;
739 T *new_ptr = this->allocate(new_capacity);
740 // The following code doesn't throw, so the raw pointer above doesn't leak.
741 std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_,
742 make_ptr(new_ptr, new_capacity));
743 std::size_t old_capacity = this->capacity_;
744 T *old_ptr = this->ptr_;
745 this->capacity_ = new_capacity;
746 this->ptr_ = new_ptr;
747 // deallocate may throw (at least in principle), but it doesn't matter since
748 // the buffer already uses the new storage and will deallocate it in case
749 // of exception.
750 if (old_ptr != data_)
751 Allocator::deallocate(old_ptr, old_capacity);
752 }
753
754 // A fixed-size buffer.
755 template <typename Char>
756 class FixedBuffer : public fmt::Buffer<Char> {
757 public:
758 FixedBuffer(Char *array, std::size_t size) : fmt::Buffer<Char>(array, size) {}
759
760 protected:
761 FMT_API void grow(std::size_t size);
762 };
763
764 template <typename Char>
765 class BasicCharTraits {
766 public:
767 #if FMT_SECURE_SCL
768 typedef stdext::checked_array_iterator<Char*> CharPtr;
769 #else
770 typedef Char *CharPtr;
771 #endif
772 static Char cast(int value) { return static_cast<Char>(value); }
773 };
774
775 template <typename Char>
776 class CharTraits;
777
778 template <>
779 class CharTraits<char> : public BasicCharTraits<char> {
780 private:
781 // Conversion from wchar_t to char is not allowed.
782 static char convert(wchar_t);
783
784 public:
785 static char convert(char value) { return value; }
786
787 // Formats a floating-point number.
788 template <typename T>
789 FMT_API static int format_float(char *buffer, std::size_t size,
790 const char *format, unsigned width, int precision, T value);
791 };
792
793 template <>
794 class CharTraits<wchar_t> : public BasicCharTraits<wchar_t> {
795 public:
796 static wchar_t convert(char value) { return value; }
797 static wchar_t convert(wchar_t value) { return value; }
798
799 template <typename T>
800 FMT_API static int format_float(wchar_t *buffer, std::size_t size,
801 const wchar_t *format, unsigned width, int precision, T value);
802 };
803
804 // Checks if a number is negative - used to avoid warnings.
805 template <bool IsSigned>
806 struct SignChecker {
807 template <typename T>
808 static bool is_negative(T value) { return value < 0; }
809 };
810
811 template <>
812 struct SignChecker<false> {
813 template <typename T>
814 static bool is_negative(T) { return false; }
815 };
816
817 // Returns true if value is negative, false otherwise.
818 // Same as (value < 0) but doesn't produce warnings if T is an unsigned type.
819 template <typename T>
820 inline bool is_negative(T value) {
821 return SignChecker<std::numeric_limits<T>::is_signed>::is_negative(value);
822 }
823
824 // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise.
825 template <bool FitsIn32Bits>
826 struct TypeSelector { typedef uint32_t Type; };
827
828 template <>
829 struct TypeSelector<false> { typedef uint64_t Type; };
830
831 template <typename T>
832 struct IntTraits {
833 // Smallest of uint32_t and uint64_t that is large enough to represent
834 // all values of T.
835 typedef typename
836 TypeSelector<std::numeric_limits<T>::digits <= 32>::Type MainType;
837 };
838
839 FMT_API void report_unknown_type(char code, const char *type);
840
841 // Static data is placed in this class template to allow header-only
842 // configuration.
843 template <typename T = void>
844 struct FMT_API BasicData {
845 static const uint32_t POWERS_OF_10_32[];
846 static const uint64_t POWERS_OF_10_64[];
847 static const char DIGITS[];
848 };
849
850 #ifndef FMT_USE_EXTERN_TEMPLATES
851 // Clang doesn't have a feature check for extern templates so we check
852 // for variadic templates which were introduced in the same version.
853 # define FMT_USE_EXTERN_TEMPLATES (__clang__ && FMT_USE_VARIADIC_TEMPLATES)
854 #endif
855
856 #if FMT_USE_EXTERN_TEMPLATES && !defined(FMT_HEADER_ONLY)
857 extern template struct BasicData<void>;
858 #endif
859
860 typedef BasicData<> Data;
861
862 #ifdef FMT_BUILTIN_CLZLL
863 // Returns the number of decimal digits in n. Leading zeros are not counted
864 // except for n == 0 in which case count_digits returns 1.
865 inline unsigned count_digits(uint64_t n) {
866 // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
867 // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits.
868 int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12;
869 return to_unsigned(t) - (n < Data::POWERS_OF_10_64[t]) + 1;
870 }
871 #else
872 // Fallback version of count_digits used when __builtin_clz is not available.
873 inline unsigned count_digits(uint64_t n) {
874 unsigned count = 1;
875 for (;;) {
876 // Integer division is slow so do it for a group of four digits instead
877 // of for every digit. The idea comes from the talk by Alexandrescu
878 // "Three Optimization Tips for C++". See speed-test for a comparison.
879 if (n < 10) return count;
880 if (n < 100) return count + 1;
881 if (n < 1000) return count + 2;
882 if (n < 10000) return count + 3;
883 n /= 10000u;
884 count += 4;
885 }
886 }
887 #endif
888
889 #ifdef FMT_BUILTIN_CLZ
890 // Optional version of count_digits for better performance on 32-bit platforms.
891 inline unsigned count_digits(uint32_t n) {
892 int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12;
893 return to_unsigned(t) - (n < Data::POWERS_OF_10_32[t]) + 1;
894 }
895 #endif
896
897 // A functor that doesn't add a thousands separator.
898 struct NoThousandsSep {
899 template <typename Char>
900 void operator()(Char *) {}
901 };
902
903 // A functor that adds a thousands separator.
904 class ThousandsSep {
905 private:
906 fmt::StringRef sep_;
907
908 // Index of a decimal digit with the least significant digit having index 0.
909 unsigned digit_index_;
910
911 public:
912 explicit ThousandsSep(fmt::StringRef sep) : sep_(sep), digit_index_(0) {}
913
914 template <typename Char>
915 void operator()(Char *&buffer) {
916 if (++digit_index_ % 3 != 0)
917 return;
918 buffer -= sep_.size();
919 std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(),
920 internal::make_ptr(buffer, sep_.size()));
921 }
922 };
923
924 // Formats a decimal unsigned integer value writing into buffer.
925 // thousands_sep is a functor that is called after writing each char to
926 // add a thousands separator if necessary.
927 template <typename UInt, typename Char, typename ThousandsSep>
928 inline void format_decimal(Char *buffer, UInt value, unsigned num_digits,
929 ThousandsSep thousands_sep) {
930 buffer += num_digits;
931 while (value >= 100) {
932 // Integer division is slow so do it for a group of two digits instead
933 // of for every digit. The idea comes from the talk by Alexandrescu
934 // "Three Optimization Tips for C++". See speed-test for a comparison.
935 unsigned index = static_cast<unsigned>((value % 100) * 2);
936 value /= 100;
937 *--buffer = Data::DIGITS[index + 1];
938 thousands_sep(buffer);
939 *--buffer = Data::DIGITS[index];
940 thousands_sep(buffer);
941 }
942 if (value < 10) {
943 *--buffer = static_cast<char>('0' + value);
944 return;
945 }
946 unsigned index = static_cast<unsigned>(value * 2);
947 *--buffer = Data::DIGITS[index + 1];
948 thousands_sep(buffer);
949 *--buffer = Data::DIGITS[index];
950 }
951
952 template <typename UInt, typename Char>
953 inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) {
954 return format_decimal(buffer, value, num_digits, NoThousandsSep());
955 }
956
957 #ifndef _WIN32
958 # define FMT_USE_WINDOWS_H 0
959 #elif !defined(FMT_USE_WINDOWS_H)
960 # define FMT_USE_WINDOWS_H 1
961 #endif
962
963 // Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h.
964 // All the functionality that relies on it will be disabled too.
965 #if FMT_USE_WINDOWS_H
966 // A converter from UTF-8 to UTF-16.
967 // It is only provided for Windows since other systems support UTF-8 natively.
968 class UTF8ToUTF16 {
969 private:
970 MemoryBuffer<wchar_t, INLINE_BUFFER_SIZE> buffer_;
971
972 public:
973 FMT_API explicit UTF8ToUTF16(StringRef s);
974 operator WStringRef() const { return WStringRef(&buffer_[0], size()); }
975 size_t size() const { return buffer_.size() - 1; }
976 const wchar_t *c_str() const { return &buffer_[0]; }
977 std::wstring str() const { return std::wstring(&buffer_[0], size()); }
978 };
979
980 // A converter from UTF-16 to UTF-8.
981 // It is only provided for Windows since other systems support UTF-8 natively.
982 class UTF16ToUTF8 {
983 private:
984 MemoryBuffer<char, INLINE_BUFFER_SIZE> buffer_;
985
986 public:
987 UTF16ToUTF8() {}
988 FMT_API explicit UTF16ToUTF8(WStringRef s);
989 operator StringRef() const { return StringRef(&buffer_[0], size()); }
990 size_t size() const { return buffer_.size() - 1; }
991 const char *c_str() const { return &buffer_[0]; }
992 std::string str() const { return std::string(&buffer_[0], size()); }
993
994 // Performs conversion returning a system error code instead of
995 // throwing exception on conversion error. This method may still throw
996 // in case of memory allocation error.
997 FMT_API int convert(WStringRef s);
998 };
999
1000 FMT_API void format_windows_error(fmt::Writer &out, int error_code,
1001 fmt::StringRef message) FMT_NOEXCEPT;
1002 #endif
1003
1004 FMT_API void format_system_error(fmt::Writer &out, int error_code,
1005 fmt::StringRef message) FMT_NOEXCEPT;
1006
1007 // A formatting argument value.
1008 struct Value {
1009 template <typename Char>
1010 struct StringValue {
1011 const Char *value;
1012 std::size_t size;
1013 };
1014
1015 typedef void(*FormatFunc)(
1016 void *formatter, const void *arg, void *format_str_ptr);
1017
1018 struct CustomValue {
1019 const void *value;
1020 FormatFunc format;
1021 };
1022
1023 union {
1024 int int_value;
1025 unsigned uint_value;
1026 LongLong long_long_value;
1027 ULongLong ulong_long_value;
1028 double double_value;
1029 long double long_double_value;
1030 const void *pointer;
1031 StringValue<char> string;
1032 StringValue<signed char> sstring;
1033 StringValue<unsigned char> ustring;
1034 StringValue<wchar_t> wstring;
1035 CustomValue custom;
1036 };
1037
1038 enum Type {
1039 NONE, NAMED_ARG,
1040 // Integer types should go first,
1041 INT, UINT, LONG_LONG, ULONG_LONG, BOOL, CHAR, LAST_INTEGER_TYPE = CHAR,
1042 // followed by floating-point types.
1043 DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE,
1044 CSTRING, STRING, WSTRING, POINTER, CUSTOM
1045 };
1046 };
1047
1048 // A formatting argument. It is a trivially copyable/constructible type to
1049 // allow storage in internal::MemoryBuffer.
1050 struct Arg : Value {
1051 Type type;
1052 };
1053
1054 template <typename Char>
1055 struct NamedArg;
1056
1057 template <typename T = void>
1058 struct Null {};
1059
1060 // A helper class template to enable or disable overloads taking wide
1061 // characters and strings in MakeValue.
1062 template <typename T, typename Char>
1063 struct WCharHelper {
1064 typedef Null<T> Supported;
1065 typedef T Unsupported;
1066 };
1067
1068 template <typename T>
1069 struct WCharHelper<T, wchar_t> {
1070 typedef T Supported;
1071 typedef Null<T> Unsupported;
1072 };
1073
1074 typedef char Yes[1];
1075 typedef char No[2];
1076
1077 template <typename T>
1078 T &get();
1079
1080 // These are non-members to workaround an overload resolution bug in bcc32.
1081 Yes &convert(fmt::ULongLong);
1082 No &convert(...);
1083
1084 template<typename T, bool ENABLE_CONVERSION>
1085 struct ConvertToIntImpl {
1086 enum { value = ENABLE_CONVERSION };
1087 };
1088
1089 template<typename T, bool ENABLE_CONVERSION>
1090 struct ConvertToIntImpl2 {
1091 enum { value = false };
1092 };
1093
1094 template<typename T>
1095 struct ConvertToIntImpl2<T, true> {
1096 enum {
1097 // Don't convert numeric types.
1098 value = ConvertToIntImpl<T, !std::numeric_limits<T>::is_specialized>::value
1099 };
1100 };
1101
1102 template<typename T>
1103 struct ConvertToInt {
1104 enum { enable_conversion = sizeof(convert(get<T>())) == sizeof(Yes) };
1105 enum { value = ConvertToIntImpl2<T, enable_conversion>::value };
1106 };
1107
1108 #define FMT_DISABLE_CONVERSION_TO_INT(Type) \
1109 template <> \
1110 struct ConvertToInt<Type> { enum { value = 0 }; }
1111
1112 // Silence warnings about convering float to int.
1113 FMT_DISABLE_CONVERSION_TO_INT(float);
1114 FMT_DISABLE_CONVERSION_TO_INT(double);
1115 FMT_DISABLE_CONVERSION_TO_INT(long double);
1116
1117 template<bool B, class T = void>
1118 struct EnableIf {};
1119
1120 template<class T>
1121 struct EnableIf<true, T> { typedef T type; };
1122
1123 template<bool B, class T, class F>
1124 struct Conditional { typedef T type; };
1125
1126 template<class T, class F>
1127 struct Conditional<false, T, F> { typedef F type; };
1128
1129 // For bcc32 which doesn't understand ! in template arguments.
1130 template<bool>
1131 struct Not { enum { value = 0 }; };
1132
1133 template<>
1134 struct Not<false> { enum { value = 1 }; };
1135
1136 template<typename T, T> struct LConvCheck {
1137 LConvCheck(int) {}
1138 };
1139
1140 // Returns the thousands separator for the current locale.
1141 // We check if ``lconv`` contains ``thousands_sep`` because on Android
1142 // ``lconv`` is stubbed as an empty struct.
1143 template <typename LConv>
1144 inline StringRef thousands_sep(
1145 LConv *lc, LConvCheck<char *LConv::*, &LConv::thousands_sep> = 0) {
1146 return lc->thousands_sep;
1147 }
1148
1149 inline fmt::StringRef thousands_sep(...) { return ""; }
1150
1151 // Makes an Arg object from any type.
1152 template <typename Formatter>
1153 class MakeValue : public Arg {
1154 public:
1155 typedef typename Formatter::Char Char;
1156
1157 private:
1158 // The following two methods are private to disallow formatting of
1159 // arbitrary pointers. If you want to output a pointer cast it to
1160 // "void *" or "const void *". In particular, this forbids formatting
1161 // of "[const] volatile char *" which is printed as bool by iostreams.
1162 // Do not implement!
1163 template <typename T>
1164 MakeValue(const T *value);
1165 template <typename T>
1166 MakeValue(T *value);
1167
1168 // The following methods are private to disallow formatting of wide
1169 // characters and strings into narrow strings as in
1170 // fmt::format("{}", L"test");
1171 // To fix this, use a wide format string: fmt::format(L"{}", L"test").
1172 #if !FMT_MSC_VER || defined(_NATIVE_WCHAR_T_DEFINED)
1173 MakeValue(typename WCharHelper<wchar_t, Char>::Unsupported);
1174 #endif
1175 MakeValue(typename WCharHelper<wchar_t *, Char>::Unsupported);
1176 MakeValue(typename WCharHelper<const wchar_t *, Char>::Unsupported);
1177 MakeValue(typename WCharHelper<const std::wstring &, Char>::Unsupported);
1178 MakeValue(typename WCharHelper<WStringRef, Char>::Unsupported);
1179
1180 void set_string(StringRef str) {
1181 string.value = str.data();
1182 string.size = str.size();
1183 }
1184
1185 void set_string(WStringRef str) {
1186 wstring.value = str.data();
1187 wstring.size = str.size();
1188 }
1189
1190 // Formats an argument of a custom type, such as a user-defined class.
1191 template <typename T>
1192 static void format_custom_arg(
1193 void *formatter, const void *arg, void *format_str_ptr) {
1194 format(*static_cast<Formatter*>(formatter),
1195 *static_cast<const Char**>(format_str_ptr),
1196 *static_cast<const T*>(arg));
1197 }
1198
1199 public:
1200 MakeValue() {}
1201
1202 #define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \
1203 MakeValue(Type value) { field = rhs; } \
1204 static uint64_t type(Type) { return Arg::TYPE; }
1205
1206 #define FMT_MAKE_VALUE(Type, field, TYPE) \
1207 FMT_MAKE_VALUE_(Type, field, TYPE, value)
1208
1209 FMT_MAKE_VALUE(bool, int_value, BOOL)
1210 FMT_MAKE_VALUE(short, int_value, INT)
1211 FMT_MAKE_VALUE(unsigned short, uint_value, UINT)
1212 FMT_MAKE_VALUE(int, int_value, INT)
1213 FMT_MAKE_VALUE(unsigned, uint_value, UINT)
1214
1215 MakeValue(long value) {
1216 // To minimize the number of types we need to deal with, long is
1217 // translated either to int or to long long depending on its size.
1218 if (const_check(sizeof(long) == sizeof(int)))
1219 int_value = static_cast<int>(value);
1220 else
1221 long_long_value = value;
1222 }
1223 static uint64_t type(long) {
1224 return sizeof(long) == sizeof(int) ? Arg::INT : Arg::LONG_LONG;
1225 }
1226
1227 MakeValue(unsigned long value) {
1228 if (const_check(sizeof(unsigned long) == sizeof(unsigned)))
1229 uint_value = static_cast<unsigned>(value);
1230 else
1231 ulong_long_value = value;
1232 }
1233 static uint64_t type(unsigned long) {
1234 return sizeof(unsigned long) == sizeof(unsigned) ?
1235 Arg::UINT : Arg::ULONG_LONG;
1236 }
1237
1238 FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG)
1239 FMT_MAKE_VALUE(ULongLong, ulong_long_value, ULONG_LONG)
1240 FMT_MAKE_VALUE(float, double_value, DOUBLE)
1241 FMT_MAKE_VALUE(double, double_value, DOUBLE)
1242 FMT_MAKE_VALUE(long double, long_double_value, LONG_DOUBLE)
1243 FMT_MAKE_VALUE(signed char, int_value, INT)
1244 FMT_MAKE_VALUE(unsigned char, uint_value, UINT)
1245 FMT_MAKE_VALUE(char, int_value, CHAR)
1246
1247 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
1248 MakeValue(typename WCharHelper<wchar_t, Char>::Supported value) {
1249 int_value = value;
1250 }
1251 static uint64_t type(wchar_t) { return Arg::CHAR; }
1252 #endif
1253
1254 #define FMT_MAKE_STR_VALUE(Type, TYPE) \
1255 MakeValue(Type value) { set_string(value); } \
1256 static uint64_t type(Type) { return Arg::TYPE; }
1257
1258 FMT_MAKE_VALUE(char *, string.value, CSTRING)
1259 FMT_MAKE_VALUE(const char *, string.value, CSTRING)
1260 FMT_MAKE_VALUE(signed char *, sstring.value, CSTRING)
1261 FMT_MAKE_VALUE(const signed char *, sstring.value, CSTRING)
1262 FMT_MAKE_VALUE(unsigned char *, ustring.value, CSTRING)
1263 FMT_MAKE_VALUE(const unsigned char *, ustring.value, CSTRING)
1264 FMT_MAKE_STR_VALUE(const std::string &, STRING)
1265 FMT_MAKE_STR_VALUE(StringRef, STRING)
1266 FMT_MAKE_VALUE_(CStringRef, string.value, CSTRING, value.c_str())
1267
1268 #define FMT_MAKE_WSTR_VALUE(Type, TYPE) \
1269 MakeValue(typename WCharHelper<Type, Char>::Supported value) { \
1270 set_string(value); \
1271 } \
1272 static uint64_t type(Type) { return Arg::TYPE; }
1273
1274 FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING)
1275 FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING)
1276 FMT_MAKE_WSTR_VALUE(const std::wstring &, WSTRING)
1277 FMT_MAKE_WSTR_VALUE(WStringRef, WSTRING)
1278
1279 FMT_MAKE_VALUE(void *, pointer, POINTER)
1280 FMT_MAKE_VALUE(const void *, pointer, POINTER)
1281
1282 template <typename T>
1283 MakeValue(const T &value,
1284 typename EnableIf<Not<
1285 ConvertToInt<T>::value>::value, int>::type = 0) {
1286 custom.value = &value;
1287 custom.format = &format_custom_arg<T>;
1288 }
1289
1290 template <typename T>
1291 MakeValue(const T &value,
1292 typename EnableIf<ConvertToInt<T>::value, int>::type = 0) {
1293 int_value = value;
1294 }
1295
1296 template <typename T>
1297 static uint64_t type(const T &) {
1298 return ConvertToInt<T>::value ? Arg::INT : Arg::CUSTOM;
1299 }
1300
1301 // Additional template param `Char_` is needed here because make_type always
1302 // uses char.
1303 template <typename Char_>
1304 MakeValue(const NamedArg<Char_> &value) { pointer = &value; }
1305
1306 template <typename Char_>
1307 static uint64_t type(const NamedArg<Char_> &) { return Arg::NAMED_ARG; }
1308 };
1309
1310 template <typename Formatter>
1311 class MakeArg : public Arg {
1312 public:
1313 MakeArg() {
1314 type = Arg::NONE;
1315 }
1316
1317 template <typename T>
1318 MakeArg(const T &value)
1319 : Arg(MakeValue<Formatter>(value)) {
1320 type = static_cast<Arg::Type>(MakeValue<Formatter>::type(value));
1321 }
1322 };
1323
1324 template <typename Char>
1325 struct NamedArg : Arg {
1326 BasicStringRef<Char> name;
1327
1328 template <typename T>
1329 NamedArg(BasicStringRef<Char> argname, const T &value)
1330 : Arg(MakeArg< BasicFormatter<Char> >(value)), name(argname) {}
1331 };
1332
1333 class RuntimeError : public std::runtime_error {
1334 protected:
1335 RuntimeError() : std::runtime_error("") {}
1336 ~RuntimeError() throw();
1337 };
1338
1339 template <typename Char>
1340 class PrintfArgFormatter;
1341
1342 template <typename Char>
1343 class ArgMap;
1344 } // namespace internal
1345
1346 /** An argument list. */
1347 class ArgList {
1348 private:
1349 // To reduce compiled code size per formatting function call, types of first
1350 // MAX_PACKED_ARGS arguments are passed in the types_ field.
1351 uint64_t types_;
1352 union {
1353 // If the number of arguments is less than MAX_PACKED_ARGS, the argument
1354 // values are stored in values_, otherwise they are stored in args_.
1355 // This is done to reduce compiled code size as storing larger objects
1356 // may require more code (at least on x86-64) even if the same amount of
1357 // data is actually copied to stack. It saves ~10% on the bloat test.
1358 const internal::Value *values_;
1359 const internal::Arg *args_;
1360 };
1361
1362 internal::Arg::Type type(unsigned index) const {
1363 unsigned shift = index * 4;
1364 uint64_t mask = 0xf;
1365 return static_cast<internal::Arg::Type>(
1366 (types_ & (mask << shift)) >> shift);
1367 }
1368
1369 template <typename Char>
1370 friend class internal::ArgMap;
1371
1372 public:
1373 // Maximum number of arguments with packed types.
1374 enum { MAX_PACKED_ARGS = 16 };
1375
1376 ArgList() : types_(0) {}
1377
1378 ArgList(ULongLong types, const internal::Value *values)
1379 : types_(types), values_(values) {}
1380 ArgList(ULongLong types, const internal::Arg *args)
1381 : types_(types), args_(args) {}
1382
1383 /** Returns the argument at specified index. */
1384 internal::Arg operator[](unsigned index) const {
1385 using internal::Arg;
1386 Arg arg;
1387 bool use_values = type(MAX_PACKED_ARGS - 1) == Arg::NONE;
1388 if (index < MAX_PACKED_ARGS) {
1389 Arg::Type arg_type = type(index);
1390 internal::Value &val = arg;
1391 if (arg_type != Arg::NONE)
1392 val = use_values ? values_[index] : args_[index];
1393 arg.type = arg_type;
1394 return arg;
1395 }
1396 if (use_values) {
1397 // The index is greater than the number of arguments that can be stored
1398 // in values, so return a "none" argument.
1399 arg.type = Arg::NONE;
1400 return arg;
1401 }
1402 for (unsigned i = MAX_PACKED_ARGS; i <= index; ++i) {
1403 if (args_[i].type == Arg::NONE)
1404 return args_[i];
1405 }
1406 return args_[index];
1407 }
1408 };
1409
1410 #define FMT_DISPATCH(call) static_cast<Impl*>(this)->call
1411
1412 /**
1413 \rst
1414 An argument visitor based on the `curiously recurring template pattern
1415 <http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_.
1416
1417 To use `~fmt::ArgVisitor` define a subclass that implements some or all of the
1418 visit methods with the same signatures as the methods in `~fmt::ArgVisitor`,
1419 for example, `~fmt::ArgVisitor::visit_int()`.
1420 Pass the subclass as the *Impl* template parameter. Then calling
1421 `~fmt::ArgVisitor::visit` for some argument will dispatch to a visit method
1422 specific to the argument type. For example, if the argument type is
1423 ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass
1424 will be called. If the subclass doesn't contain a method with this signature,
1425 then a corresponding method of `~fmt::ArgVisitor` will be called.
1426
1427 **Example**::
1428
1429 class MyArgVisitor : public fmt::ArgVisitor<MyArgVisitor, void> {
1430 public:
1431 void visit_int(int value) { fmt::print("{}", value); }
1432 void visit_double(double value) { fmt::print("{}", value ); }
1433 };
1434 \endrst
1435 */
1436 template <typename Impl, typename Result>
1437 class ArgVisitor {
1438 private:
1439 typedef internal::Arg Arg;
1440
1441 public:
1442 void report_unhandled_arg() {}
1443
1444 Result visit_unhandled_arg() {
1445 FMT_DISPATCH(report_unhandled_arg());
1446 return Result();
1447 }
1448
1449 /** Visits an ``int`` argument. **/
1450 Result visit_int(int value) {
1451 return FMT_DISPATCH(visit_any_int(value));
1452 }
1453
1454 /** Visits a ``long long`` argument. **/
1455 Result visit_long_long(LongLong value) {
1456 return FMT_DISPATCH(visit_any_int(value));
1457 }
1458
1459 /** Visits an ``unsigned`` argument. **/
1460 Result visit_uint(unsigned value) {
1461 return FMT_DISPATCH(visit_any_int(value));
1462 }
1463
1464 /** Visits an ``unsigned long long`` argument. **/
1465 Result visit_ulong_long(ULongLong value) {
1466 return FMT_DISPATCH(visit_any_int(value));
1467 }
1468
1469 /** Visits a ``bool`` argument. **/
1470 Result visit_bool(bool value) {
1471 return FMT_DISPATCH(visit_any_int(value));
1472 }
1473
1474 /** Visits a ``char`` or ``wchar_t`` argument. **/
1475 Result visit_char(int value) {
1476 return FMT_DISPATCH(visit_any_int(value));
1477 }
1478
1479 /** Visits an argument of any integral type. **/
1480 template <typename T>
1481 Result visit_any_int(T) {
1482 return FMT_DISPATCH(visit_unhandled_arg());
1483 }
1484
1485 /** Visits a ``double`` argument. **/
1486 Result visit_double(double value) {
1487 return FMT_DISPATCH(visit_any_double(value));
1488 }
1489
1490 /** Visits a ``long double`` argument. **/
1491 Result visit_long_double(long double value) {
1492 return FMT_DISPATCH(visit_any_double(value));
1493 }
1494
1495 /** Visits a ``double`` or ``long double`` argument. **/
1496 template <typename T>
1497 Result visit_any_double(T) {
1498 return FMT_DISPATCH(visit_unhandled_arg());
1499 }
1500
1501 /** Visits a null-terminated C string (``const char *``) argument. **/
1502 Result visit_cstring(const char *) {
1503 return FMT_DISPATCH(visit_unhandled_arg());
1504 }
1505
1506 /** Visits a string argument. **/
1507 Result visit_string(Arg::StringValue<char>) {
1508 return FMT_DISPATCH(visit_unhandled_arg());
1509 }
1510
1511 /** Visits a wide string argument. **/
1512 Result visit_wstring(Arg::StringValue<wchar_t>) {
1513 return FMT_DISPATCH(visit_unhandled_arg());
1514 }
1515
1516 /** Visits a pointer argument. **/
1517 Result visit_pointer(const void *) {
1518 return FMT_DISPATCH(visit_unhandled_arg());
1519 }
1520
1521 /** Visits an argument of a custom (user-defined) type. **/
1522 Result visit_custom(Arg::CustomValue) {
1523 return FMT_DISPATCH(visit_unhandled_arg());
1524 }
1525
1526 /**
1527 \rst
1528 Visits an argument dispatching to the appropriate visit method based on
1529 the argument type. For example, if the argument type is ``double`` then
1530 the `~fmt::ArgVisitor::visit_double()` method of the *Impl* class will be
1531 called.
1532 \endrst
1533 */
1534 Result visit(const Arg &arg) {
1535 switch (arg.type) {
1536 case Arg::NONE:
1537 case Arg::NAMED_ARG:
1538 FMT_ASSERT(false, "invalid argument type");
1539 break;
1540 case Arg::INT:
1541 return FMT_DISPATCH(visit_int(arg.int_value));
1542 case Arg::UINT:
1543 return FMT_DISPATCH(visit_uint(arg.uint_value));
1544 case Arg::LONG_LONG:
1545 return FMT_DISPATCH(visit_long_long(arg.long_long_value));
1546 case Arg::ULONG_LONG:
1547 return FMT_DISPATCH(visit_ulong_long(arg.ulong_long_value));
1548 case Arg::BOOL:
1549 return FMT_DISPATCH(visit_bool(arg.int_value != 0));
1550 case Arg::CHAR:
1551 return FMT_DISPATCH(visit_char(arg.int_value));
1552 case Arg::DOUBLE:
1553 return FMT_DISPATCH(visit_double(arg.double_value));
1554 case Arg::LONG_DOUBLE:
1555 return FMT_DISPATCH(visit_long_double(arg.long_double_value));
1556 case Arg::CSTRING:
1557 return FMT_DISPATCH(visit_cstring(arg.string.value));
1558 case Arg::STRING:
1559 return FMT_DISPATCH(visit_string(arg.string));
1560 case Arg::WSTRING:
1561 return FMT_DISPATCH(visit_wstring(arg.wstring));
1562 case Arg::POINTER:
1563 return FMT_DISPATCH(visit_pointer(arg.pointer));
1564 case Arg::CUSTOM:
1565 return FMT_DISPATCH(visit_custom(arg.custom));
1566 }
1567 return Result();
1568 }
1569 };
1570
1571 enum Alignment {
1572 ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC
1573 };
1574
1575 // Flags.
1576 enum {
1577 SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8,
1578 CHAR_FLAG = 0x10 // Argument has char type - used in error reporting.
1579 };
1580
1581 // An empty format specifier.
1582 struct EmptySpec {};
1583
1584 // A type specifier.
1585 template <char TYPE>
1586 struct TypeSpec : EmptySpec {
1587 Alignment align() const { return ALIGN_DEFAULT; }
1588 unsigned width() const { return 0; }
1589 int precision() const { return -1; }
1590 bool flag(unsigned) const { return false; }
1591 char type() const { return TYPE; }
1592 char fill() const { return ' '; }
1593 };
1594
1595 // A width specifier.
1596 struct WidthSpec {
1597 unsigned width_;
1598 // Fill is always wchar_t and cast to char if necessary to avoid having
1599 // two specialization of WidthSpec and its subclasses.
1600 wchar_t fill_;
1601
1602 WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {}
1603
1604 unsigned width() const { return width_; }
1605 wchar_t fill() const { return fill_; }
1606 };
1607
1608 // An alignment specifier.
1609 struct AlignSpec : WidthSpec {
1610 Alignment align_;
1611
1612 AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT)
1613 : WidthSpec(width, fill), align_(align) {}
1614
1615 Alignment align() const { return align_; }
1616
1617 int precision() const { return -1; }
1618 };
1619
1620 // An alignment and type specifier.
1621 template <char TYPE>
1622 struct AlignTypeSpec : AlignSpec {
1623 AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {}
1624
1625 bool flag(unsigned) const { return false; }
1626 char type() const { return TYPE; }
1627 };
1628
1629 // A full format specifier.
1630 struct FormatSpec : AlignSpec {
1631 unsigned flags_;
1632 int precision_;
1633 char type_;
1634
1635 FormatSpec(
1636 unsigned width = 0, char type = 0, wchar_t fill = ' ')
1637 : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {}
1638
1639 bool flag(unsigned f) const { return (flags_ & f) != 0; }
1640 int precision() const { return precision_; }
1641 char type() const { return type_; }
1642 };
1643
1644 // An integer format specifier.
1645 template <typename T, typename SpecT = TypeSpec<0>, typename Char = char>
1646 class IntFormatSpec : public SpecT {
1647 private:
1648 T value_;
1649
1650 public:
1651 IntFormatSpec(T val, const SpecT &spec = SpecT())
1652 : SpecT(spec), value_(val) {}
1653
1654 T value() const { return value_; }
1655 };
1656
1657 // A string format specifier.
1658 template <typename Char>
1659 class StrFormatSpec : public AlignSpec {
1660 private:
1661 const Char *str_;
1662
1663 public:
1664 template <typename FillChar>
1665 StrFormatSpec(const Char *str, unsigned width, FillChar fill)
1666 : AlignSpec(width, fill), str_(str) {
1667 internal::CharTraits<Char>::convert(FillChar());
1668 }
1669
1670 const Char *str() const { return str_; }
1671 };
1672
1673 /**
1674 Returns an integer format specifier to format the value in base 2.
1675 */
1676 IntFormatSpec<int, TypeSpec<'b'> > bin(int value);
1677
1678 /**
1679 Returns an integer format specifier to format the value in base 8.
1680 */
1681 IntFormatSpec<int, TypeSpec<'o'> > oct(int value);
1682
1683 /**
1684 Returns an integer format specifier to format the value in base 16 using
1685 lower-case letters for the digits above 9.
1686 */
1687 IntFormatSpec<int, TypeSpec<'x'> > hex(int value);
1688
1689 /**
1690 Returns an integer formatter format specifier to format in base 16 using
1691 upper-case letters for the digits above 9.
1692 */
1693 IntFormatSpec<int, TypeSpec<'X'> > hexu(int value);
1694
1695 /**
1696 \rst
1697 Returns an integer format specifier to pad the formatted argument with the
1698 fill character to the specified width using the default (right) numeric
1699 alignment.
1700
1701 **Example**::
1702
1703 MemoryWriter out;
1704 out << pad(hex(0xcafe), 8, '0');
1705 // out.str() == "0000cafe"
1706
1707 \endrst
1708 */
1709 template <char TYPE_CODE, typename Char>
1710 IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char> pad(
1711 int value, unsigned width, Char fill = ' ');
1712
1713 #define FMT_DEFINE_INT_FORMATTERS(TYPE) \
1714 inline IntFormatSpec<TYPE, TypeSpec<'b'> > bin(TYPE value) { \
1715 return IntFormatSpec<TYPE, TypeSpec<'b'> >(value, TypeSpec<'b'>()); \
1716 } \
1717 \
1718 inline IntFormatSpec<TYPE, TypeSpec<'o'> > oct(TYPE value) { \
1719 return IntFormatSpec<TYPE, TypeSpec<'o'> >(value, TypeSpec<'o'>()); \
1720 } \
1721 \
1722 inline IntFormatSpec<TYPE, TypeSpec<'x'> > hex(TYPE value) { \
1723 return IntFormatSpec<TYPE, TypeSpec<'x'> >(value, TypeSpec<'x'>()); \
1724 } \
1725 \
1726 inline IntFormatSpec<TYPE, TypeSpec<'X'> > hexu(TYPE value) { \
1727 return IntFormatSpec<TYPE, TypeSpec<'X'> >(value, TypeSpec<'X'>()); \
1728 } \
1729 \
1730 template <char TYPE_CODE> \
1731 inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> > pad( \
1732 IntFormatSpec<TYPE, TypeSpec<TYPE_CODE> > f, unsigned width) { \
1733 return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> >( \
1734 f.value(), AlignTypeSpec<TYPE_CODE>(width, ' ')); \
1735 } \
1736 \
1737 /* For compatibility with older compilers we provide two overloads for pad, */ \
1738 /* one that takes a fill character and one that doesn't. In the future this */ \
1739 /* can be replaced with one overload making the template argument Char */ \
1740 /* default to char (C++11). */ \
1741 template <char TYPE_CODE, typename Char> \
1742 inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char> pad( \
1743 IntFormatSpec<TYPE, TypeSpec<TYPE_CODE>, Char> f, \
1744 unsigned width, Char fill) { \
1745 return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char>( \
1746 f.value(), AlignTypeSpec<TYPE_CODE>(width, fill)); \
1747 } \
1748 \
1749 inline IntFormatSpec<TYPE, AlignTypeSpec<0> > pad( \
1750 TYPE value, unsigned width) { \
1751 return IntFormatSpec<TYPE, AlignTypeSpec<0> >( \
1752 value, AlignTypeSpec<0>(width, ' ')); \
1753 } \
1754 \
1755 template <typename Char> \
1756 inline IntFormatSpec<TYPE, AlignTypeSpec<0>, Char> pad( \
1757 TYPE value, unsigned width, Char fill) { \
1758 return IntFormatSpec<TYPE, AlignTypeSpec<0>, Char>( \
1759 value, AlignTypeSpec<0>(width, fill)); \
1760 }
1761
1762 FMT_DEFINE_INT_FORMATTERS(int)
1763 FMT_DEFINE_INT_FORMATTERS(long)
1764 FMT_DEFINE_INT_FORMATTERS(unsigned)
1765 FMT_DEFINE_INT_FORMATTERS(unsigned long)
1766 FMT_DEFINE_INT_FORMATTERS(LongLong)
1767 FMT_DEFINE_INT_FORMATTERS(ULongLong)
1768
1769 /**
1770 \rst
1771 Returns a string formatter that pads the formatted argument with the fill
1772 character to the specified width using the default (left) string alignment.
1773
1774 **Example**::
1775
1776 std::string s = str(MemoryWriter() << pad("abc", 8));
1777 // s == "abc "
1778
1779 \endrst
1780 */
1781 template <typename Char>
1782 inline StrFormatSpec<Char> pad(
1783 const Char *str, unsigned width, Char fill = ' ') {
1784 return StrFormatSpec<Char>(str, width, fill);
1785 }
1786
1787 inline StrFormatSpec<wchar_t> pad(
1788 const wchar_t *str, unsigned width, char fill = ' ') {
1789 return StrFormatSpec<wchar_t>(str, width, fill);
1790 }
1791
1792 namespace internal {
1793
1794 template <typename Char>
1795 class ArgMap {
1796 private:
1797 typedef std::vector<
1798 std::pair<fmt::BasicStringRef<Char>, internal::Arg> > MapType;
1799 typedef typename MapType::value_type Pair;
1800
1801 MapType map_;
1802
1803 public:
1804 FMT_API void init(const ArgList &args);
1805
1806 const internal::Arg* find(const fmt::BasicStringRef<Char> &name) const {
1807 // The list is unsorted, so just return the first matching name.
1808 for (typename MapType::const_iterator it = map_.begin(), end = map_.end();
1809 it != end; ++it) {
1810 if (it->first == name)
1811 return &it->second;
1812 }
1813 return 0;
1814 }
1815 };
1816
1817 template <typename Impl, typename Char>
1818 class ArgFormatterBase : public ArgVisitor<Impl, void> {
1819 private:
1820 BasicWriter<Char> &writer_;
1821 FormatSpec &spec_;
1822
1823 FMT_DISALLOW_COPY_AND_ASSIGN(ArgFormatterBase);
1824
1825 void write_pointer(const void *p) {
1826 spec_.flags_ = HASH_FLAG;
1827 spec_.type_ = 'x';
1828 writer_.write_int(reinterpret_cast<uintptr_t>(p), spec_);
1829 }
1830
1831 protected:
1832 BasicWriter<Char> &writer() { return writer_; }
1833 FormatSpec &spec() { return spec_; }
1834
1835 void write(bool value) {
1836 const char *str_value = value ? "true" : "false";
1837 Arg::StringValue<char> str = { str_value, std::strlen(str_value) };
1838 writer_.write_str(str, spec_);
1839 }
1840
1841 void write(const char *value) {
1842 Arg::StringValue<char> str = { value, value != 0 ? std::strlen(value) : 0 };
1843 writer_.write_str(str, spec_);
1844 }
1845
1846 public:
1847 ArgFormatterBase(BasicWriter<Char> &w, FormatSpec &s)
1848 : writer_(w), spec_(s) {}
1849
1850 template <typename T>
1851 void visit_any_int(T value) { writer_.write_int(value, spec_); }
1852
1853 template <typename T>
1854 void visit_any_double(T value) { writer_.write_double(value, spec_); }
1855
1856 void visit_bool(bool value) {
1857 if (spec_.type_)
1858 return visit_any_int(value);
1859 write(value);
1860 }
1861
1862 void visit_char(int value) {
1863 if (spec_.type_ && spec_.type_ != 'c') {
1864 spec_.flags_ |= CHAR_FLAG;
1865 writer_.write_int(value, spec_);
1866 return;
1867 }
1868 if (spec_.align_ == ALIGN_NUMERIC || spec_.flags_ != 0)
1869 FMT_THROW(FormatError("invalid format specifier for char"));
1870 typedef typename BasicWriter<Char>::CharPtr CharPtr;
1871 Char fill = internal::CharTraits<Char>::cast(spec_.fill());
1872 CharPtr out = CharPtr();
1873 const unsigned CHAR_SIZE = 1;
1874 if (spec_.width_ > CHAR_SIZE) {
1875 out = writer_.grow_buffer(spec_.width_);
1876 if (spec_.align_ == ALIGN_RIGHT) {
1877 std::uninitialized_fill_n(out, spec_.width_ - CHAR_SIZE, fill);
1878 out += spec_.width_ - CHAR_SIZE;
1879 }
1880 else if (spec_.align_ == ALIGN_CENTER) {
1881 out = writer_.fill_padding(out, spec_.width_,
1882 internal::const_check(CHAR_SIZE), fill);
1883 }
1884 else {
1885 std::uninitialized_fill_n(out + CHAR_SIZE,
1886 spec_.width_ - CHAR_SIZE, fill);
1887 }
1888 }
1889 else {
1890 out = writer_.grow_buffer(CHAR_SIZE);
1891 }
1892 *out = internal::CharTraits<Char>::cast(value);
1893 }
1894
1895 void visit_cstring(const char *value) {
1896 if (spec_.type_ == 'p')
1897 return write_pointer(value);
1898 write(value);
1899 }
1900
1901 void visit_string(Arg::StringValue<char> value) {
1902 writer_.write_str(value, spec_);
1903 }
1904
1905 using ArgVisitor<Impl, void>::visit_wstring;
1906
1907 void visit_wstring(Arg::StringValue<Char> value) {
1908 writer_.write_str(value, spec_);
1909 }
1910
1911 void visit_pointer(const void *value) {
1912 if (spec_.type_ && spec_.type_ != 'p')
1913 report_unknown_type(spec_.type_, "pointer");
1914 write_pointer(value);
1915 }
1916 };
1917
1918 class FormatterBase {
1919 private:
1920 ArgList args_;
1921 int next_arg_index_;
1922
1923 // Returns the argument with specified index.
1924 FMT_API Arg do_get_arg(unsigned arg_index, const char *&error);
1925
1926 protected:
1927 const ArgList &args() const { return args_; }
1928
1929 explicit FormatterBase(const ArgList &args) {
1930 args_ = args;
1931 next_arg_index_ = 0;
1932 }
1933
1934 // Returns the next argument.
1935 Arg next_arg(const char *&error) {
1936 if (next_arg_index_ >= 0)
1937 return do_get_arg(internal::to_unsigned(next_arg_index_++), error);
1938 error = "cannot switch from manual to automatic argument indexing";
1939 return Arg();
1940 }
1941
1942 // Checks if manual indexing is used and returns the argument with
1943 // specified index.
1944 Arg get_arg(unsigned arg_index, const char *&error) {
1945 return check_no_auto_index(error) ? do_get_arg(arg_index, error) : Arg();
1946 }
1947
1948 bool check_no_auto_index(const char *&error) {
1949 if (next_arg_index_ > 0) {
1950 error = "cannot switch from automatic to manual argument indexing";
1951 return false;
1952 }
1953 next_arg_index_ = -1;
1954 return true;
1955 }
1956
1957 template <typename Char>
1958 void write(BasicWriter<Char> &w, const Char *start, const Char *end) {
1959 if (start != end)
1960 w << BasicStringRef<Char>(start, internal::to_unsigned(end - start));
1961 }
1962 };
1963
1964 // A printf formatter.
1965 template <typename Char>
1966 class PrintfFormatter : private FormatterBase {
1967 private:
1968 void parse_flags(FormatSpec &spec, const Char *&s);
1969
1970 // Returns the argument with specified index or, if arg_index is equal
1971 // to the maximum unsigned value, the next argument.
1972 Arg get_arg(const Char *s,
1973 unsigned arg_index = (std::numeric_limits<unsigned>::max)());
1974
1975 // Parses argument index, flags and width and returns the argument index.
1976 unsigned parse_header(const Char *&s, FormatSpec &spec);
1977
1978 public:
1979 explicit PrintfFormatter(const ArgList &args) : FormatterBase(args) {}
1980 FMT_API void format(BasicWriter<Char> &writer,
1981 BasicCStringRef<Char> format_str);
1982 };
1983 } // namespace internal
1984
1985 /**
1986 \rst
1987 An argument formatter based on the `curiously recurring template pattern
1988 <http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_.
1989
1990 To use `~fmt::BasicArgFormatter` define a subclass that implements some or
1991 all of the visit methods with the same signatures as the methods in
1992 `~fmt::ArgVisitor`, for example, `~fmt::ArgVisitor::visit_int()`.
1993 Pass the subclass as the *Impl* template parameter. When a formatting
1994 function processes an argument, it will dispatch to a visit method
1995 specific to the argument type. For example, if the argument type is
1996 ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass
1997 will be called. If the subclass doesn't contain a method with this signature,
1998 then a corresponding method of `~fmt::BasicArgFormatter` or its superclass
1999 will be called.
2000 \endrst
2001 */
2002 template <typename Impl, typename Char>
2003 class BasicArgFormatter : public internal::ArgFormatterBase<Impl, Char> {
2004 private:
2005 BasicFormatter<Char, Impl> &formatter_;
2006 const Char *format_;
2007
2008 public:
2009 /**
2010 \rst
2011 Constructs an argument formatter object.
2012 *formatter* is a reference to the main formatter object, *spec* contains
2013 format specifier information for standard argument types, and *fmt* points
2014 to the part of the format string being parsed for custom argument types.
2015 \endrst
2016 */
2017 BasicArgFormatter(BasicFormatter<Char, Impl> &formatter,
2018 FormatSpec &spec, const Char *fmt)
2019 : internal::ArgFormatterBase<Impl, Char>(formatter.writer(), spec),
2020 formatter_(formatter), format_(fmt) {}
2021
2022 /** Formats argument of a custom (user-defined) type. */
2023 void visit_custom(internal::Arg::CustomValue c) {
2024 c.format(&formatter_, c.value, &format_);
2025 }
2026 };
2027
2028 /** The default argument formatter. */
2029 template <typename Char>
2030 class ArgFormatter : public BasicArgFormatter<ArgFormatter<Char>, Char> {
2031 public:
2032 /** Constructs an argument formatter object. */
2033 ArgFormatter(BasicFormatter<Char> &formatter,
2034 FormatSpec &spec, const Char *fmt)
2035 : BasicArgFormatter<ArgFormatter<Char>, Char>(formatter, spec, fmt) {}
2036 };
2037
2038 /** This template formats data and writes the output to a writer. */
2039 template <typename CharType, typename ArgFormatter>
2040 class BasicFormatter : private internal::FormatterBase {
2041 public:
2042 /** The character type for the output. */
2043 typedef CharType Char;
2044
2045 private:
2046 BasicWriter<Char> &writer_;
2047 internal::ArgMap<Char> map_;
2048
2049 FMT_DISALLOW_COPY_AND_ASSIGN(BasicFormatter);
2050
2051 using internal::FormatterBase::get_arg;
2052
2053 // Checks if manual indexing is used and returns the argument with
2054 // specified name.
2055 internal::Arg get_arg(BasicStringRef<Char> arg_name, const char *&error);
2056
2057 // Parses argument index and returns corresponding argument.
2058 internal::Arg parse_arg_index(const Char *&s);
2059
2060 // Parses argument name and returns corresponding argument.
2061 internal::Arg parse_arg_name(const Char *&s);
2062
2063 public:
2064 /**
2065 \rst
2066 Constructs a ``BasicFormatter`` object. References to the arguments and
2067 the writer are stored in the formatter object so make sure they have
2068 appropriate lifetimes.
2069 \endrst
2070 */
2071 BasicFormatter(const ArgList &args, BasicWriter<Char> &w)
2072 : internal::FormatterBase(args), writer_(w) {}
2073
2074 /** Returns a reference to the writer associated with this formatter. */
2075 BasicWriter<Char> &writer() { return writer_; }
2076
2077 /** Formats stored arguments and writes the output to the writer. */
2078 void format(BasicCStringRef<Char> format_str);
2079
2080 // Formats a single argument and advances format_str, a format string pointer.
2081 const Char *format(const Char *&format_str, const internal::Arg &arg);
2082 };
2083
2084 // Generates a comma-separated list with results of applying f to
2085 // numbers 0..n-1.
2086 # define FMT_GEN(n, f) FMT_GEN##n(f)
2087 # define FMT_GEN1(f) f(0)
2088 # define FMT_GEN2(f) FMT_GEN1(f), f(1)
2089 # define FMT_GEN3(f) FMT_GEN2(f), f(2)
2090 # define FMT_GEN4(f) FMT_GEN3(f), f(3)
2091 # define FMT_GEN5(f) FMT_GEN4(f), f(4)
2092 # define FMT_GEN6(f) FMT_GEN5(f), f(5)
2093 # define FMT_GEN7(f) FMT_GEN6(f), f(6)
2094 # define FMT_GEN8(f) FMT_GEN7(f), f(7)
2095 # define FMT_GEN9(f) FMT_GEN8(f), f(8)
2096 # define FMT_GEN10(f) FMT_GEN9(f), f(9)
2097 # define FMT_GEN11(f) FMT_GEN10(f), f(10)
2098 # define FMT_GEN12(f) FMT_GEN11(f), f(11)
2099 # define FMT_GEN13(f) FMT_GEN12(f), f(12)
2100 # define FMT_GEN14(f) FMT_GEN13(f), f(13)
2101 # define FMT_GEN15(f) FMT_GEN14(f), f(14)
2102
2103 namespace internal {
2104 inline uint64_t make_type() { return 0; }
2105
2106 template <typename T>
2107 inline uint64_t make_type(const T &arg) {
2108 return MakeValue< BasicFormatter<char> >::type(arg);
2109 }
2110
2111 template <unsigned N, bool/*IsPacked*/ = (N < ArgList::MAX_PACKED_ARGS)>
2112 struct ArgArray;
2113
2114 template <unsigned N>
2115 struct ArgArray<N, true/*IsPacked*/> {
2116 typedef Value Type[N > 0 ? N : 1];
2117
2118 template <typename Formatter, typename T>
2119 static Value make(const T &value) {
2120 #ifdef __clang__
2121 Value result = MakeValue<Formatter>(value);
2122 // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang:
2123 // https://github.com/fmtlib/fmt/issues/276
2124 (void)result.custom.format;
2125 return result;
2126 #else
2127 return MakeValue<Formatter>(value);
2128 #endif
2129 }
2130 };
2131
2132 template <unsigned N>
2133 struct ArgArray<N, false/*IsPacked*/> {
2134 typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE
2135
2136 template <typename Formatter, typename T>
2137 static Arg make(const T &value) { return MakeArg<Formatter>(value); }
2138 };
2139
2140 #if FMT_USE_VARIADIC_TEMPLATES
2141 template <typename Arg, typename... Args>
2142 inline uint64_t make_type(const Arg &first, const Args & ... tail) {
2143 return make_type(first) | (make_type(tail...) << 4);
2144 }
2145
2146 #else
2147
2148 struct ArgType {
2149 uint64_t type;
2150
2151 ArgType() : type(0) {}
2152
2153 template <typename T>
2154 ArgType(const T &arg) : type(make_type(arg)) {}
2155 };
2156
2157 # define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType()
2158
2159 inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) {
2160 return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) |
2161 (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) |
2162 (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) |
2163 (t12.type << 48) | (t13.type << 52) | (t14.type << 56);
2164 }
2165 #endif
2166 } // namespace internal
2167
2168 # define FMT_MAKE_TEMPLATE_ARG(n) typename T##n
2169 # define FMT_MAKE_ARG_TYPE(n) T##n
2170 # define FMT_MAKE_ARG(n) const T##n &v##n
2171 # define FMT_ASSIGN_char(n) \
2172 arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter<char> >(v##n)
2173 # define FMT_ASSIGN_wchar_t(n) \
2174 arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter<wchar_t> >(v##n)
2175
2176 #if FMT_USE_VARIADIC_TEMPLATES
2177 // Defines a variadic function returning void.
2178 # define FMT_VARIADIC_VOID(func, arg_type) \
2179 template <typename... Args> \
2180 void func(arg_type arg0, const Args & ... args) { \
2181 typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \
2182 typename ArgArray::Type array{ \
2183 ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \
2184 func(arg0, fmt::ArgList(fmt::internal::make_type(args...), array)); \
2185 }
2186
2187 // Defines a variadic constructor.
2188 # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \
2189 template <typename... Args> \
2190 ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \
2191 typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \
2192 typename ArgArray::Type array{ \
2193 ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \
2194 func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(args...), array)); \
2195 }
2196
2197 #else
2198
2199 # define FMT_MAKE_REF(n) \
2200 fmt::internal::MakeValue< fmt::BasicFormatter<Char> >(v##n)
2201 # define FMT_MAKE_REF2(n) v##n
2202
2203 // Defines a wrapper for a function taking one argument of type arg_type
2204 // and n additional arguments of arbitrary types.
2205 # define FMT_WRAP1(func, arg_type, n) \
2206 template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
2207 inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \
2208 const fmt::internal::ArgArray<n>::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \
2209 func(arg1, fmt::ArgList( \
2210 fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \
2211 }
2212
2213 // Emulates a variadic function returning void on a pre-C++11 compiler.
2214 # define FMT_VARIADIC_VOID(func, arg_type) \
2215 inline void func(arg_type arg) { func(arg, fmt::ArgList()); } \
2216 FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \
2217 FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \
2218 FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \
2219 FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \
2220 FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10)
2221
2222 # define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \
2223 template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
2224 ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \
2225 const fmt::internal::ArgArray<n>::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \
2226 func(arg0, arg1, fmt::ArgList( \
2227 fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \
2228 }
2229
2230 // Emulates a variadic constructor on a pre-C++11 compiler.
2231 # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \
2232 FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \
2233 FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \
2234 FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \
2235 FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \
2236 FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \
2237 FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \
2238 FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \
2239 FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \
2240 FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \
2241 FMT_CTOR(ctor, func, arg0_type, arg1_type, 10)
2242 #endif
2243
2244 // Generates a comma-separated list with results of applying f to pairs
2245 // (argument, index).
2246 #define FMT_FOR_EACH1(f, x0) f(x0, 0)
2247 #define FMT_FOR_EACH2(f, x0, x1) \
2248 FMT_FOR_EACH1(f, x0), f(x1, 1)
2249 #define FMT_FOR_EACH3(f, x0, x1, x2) \
2250 FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2)
2251 #define FMT_FOR_EACH4(f, x0, x1, x2, x3) \
2252 FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3)
2253 #define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \
2254 FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4)
2255 #define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \
2256 FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5)
2257 #define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \
2258 FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6)
2259 #define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \
2260 FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7)
2261 #define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \
2262 FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8)
2263 #define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \
2264 FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9)
2265
2266 /**
2267 An error returned by an operating system or a language runtime,
2268 for example a file opening error.
2269 */
2270 class SystemError : public internal::RuntimeError {
2271 private:
2272 void init(int err_code, CStringRef format_str, ArgList args);
2273
2274 protected:
2275 int error_code_;
2276
2277 typedef char Char; // For FMT_VARIADIC_CTOR.
2278
2279 SystemError() {}
2280
2281 public:
2282 /**
2283 \rst
2284 Constructs a :class:`fmt::SystemError` object with the description
2285 of the form
2286
2287 .. parsed-literal::
2288 *<message>*: *<system-message>*
2289
2290 where *<message>* is the formatted message and *<system-message>* is
2291 the system message corresponding to the error code.
2292 *error_code* is a system error code as given by ``errno``.
2293 If *error_code* is not a valid error code such as -1, the system message
2294 may look like "Unknown error -1" and is platform-dependent.
2295
2296 **Example**::
2297
2298 // This throws a SystemError with the description
2299 // cannot open file 'madeup': No such file or directory
2300 // or similar (system message may vary).
2301 const char *filename = "madeup";
2302 std::FILE *file = std::fopen(filename, "r");
2303 if (!file)
2304 throw fmt::SystemError(errno, "cannot open file '{}'", filename);
2305 \endrst
2306 */
2307 SystemError(int error_code, CStringRef message) {
2308 init(error_code, message, ArgList());
2309 }
2310 FMT_VARIADIC_CTOR(SystemError, init, int, CStringRef)
2311
2312 ~SystemError() throw();
2313
2314 int error_code() const { return error_code_; }
2315 };
2316
2317 /**
2318 \rst
2319 This template provides operations for formatting and writing data into
2320 a character stream. The output is stored in a buffer provided by a subclass
2321 such as :class:`fmt::BasicMemoryWriter`.
2322
2323 You can use one of the following typedefs for common character types:
2324
2325 +---------+----------------------+
2326 | Type | Definition |
2327 +=========+======================+
2328 | Writer | BasicWriter<char> |
2329 +---------+----------------------+
2330 | WWriter | BasicWriter<wchar_t> |
2331 +---------+----------------------+
2332
2333 \endrst
2334 */
2335 template <typename Char>
2336 class BasicWriter {
2337 private:
2338 // Output buffer.
2339 Buffer<Char> &buffer_;
2340
2341 FMT_DISALLOW_COPY_AND_ASSIGN(BasicWriter);
2342
2343 typedef typename internal::CharTraits<Char>::CharPtr CharPtr;
2344
2345 #if FMT_SECURE_SCL
2346 // Returns pointer value.
2347 static Char *get(CharPtr p) { return p.base(); }
2348 #else
2349 static Char *get(Char *p) { return p; }
2350 #endif
2351
2352 // Fills the padding around the content and returns the pointer to the
2353 // content area.
2354 static CharPtr fill_padding(CharPtr buffer,
2355 unsigned total_size, std::size_t content_size, wchar_t fill);
2356
2357 // Grows the buffer by n characters and returns a pointer to the newly
2358 // allocated area.
2359 CharPtr grow_buffer(std::size_t n) {
2360 std::size_t size = buffer_.size();
2361 buffer_.resize(size + n);
2362 return internal::make_ptr(&buffer_[size], n);
2363 }
2364
2365 // Writes an unsigned decimal integer.
2366 template <typename UInt>
2367 Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) {
2368 unsigned num_digits = internal::count_digits(value);
2369 Char *ptr = get(grow_buffer(prefix_size + num_digits));
2370 internal::format_decimal(ptr + prefix_size, value, num_digits);
2371 return ptr;
2372 }
2373
2374 // Writes a decimal integer.
2375 template <typename Int>
2376 void write_decimal(Int value) {
2377 typedef typename internal::IntTraits<Int>::MainType MainType;
2378 MainType abs_value = static_cast<MainType>(value);
2379 if (internal::is_negative(value)) {
2380 abs_value = 0 - abs_value;
2381 *write_unsigned_decimal(abs_value, 1) = '-';
2382 }
2383 else {
2384 write_unsigned_decimal(abs_value, 0);
2385 }
2386 }
2387
2388 // Prepare a buffer for integer formatting.
2389 CharPtr prepare_int_buffer(unsigned num_digits,
2390 const EmptySpec &, const char *prefix, unsigned prefix_size) {
2391 unsigned size = prefix_size + num_digits;
2392 CharPtr p = grow_buffer(size);
2393 std::uninitialized_copy(prefix, prefix + prefix_size, p);
2394 return p + size - 1;
2395 }
2396
2397 template <typename Spec>
2398 CharPtr prepare_int_buffer(unsigned num_digits,
2399 const Spec &spec, const char *prefix, unsigned prefix_size);
2400
2401 // Formats an integer.
2402 template <typename T, typename Spec>
2403 void write_int(T value, Spec spec);
2404
2405 // Formats a floating-point number (double or long double).
2406 template <typename T>
2407 void write_double(T value, const FormatSpec &spec);
2408
2409 // Writes a formatted string.
2410 template <typename StrChar>
2411 CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec);
2412
2413 template <typename StrChar>
2414 void write_str(const internal::Arg::StringValue<StrChar> &str,
2415 const FormatSpec &spec);
2416
2417 // This following methods are private to disallow writing wide characters
2418 // and strings to a char stream. If you want to print a wide string as a
2419 // pointer as std::ostream does, cast it to const void*.
2420 // Do not implement!
2421 void operator<<(typename internal::WCharHelper<wchar_t, Char>::Unsupported);
2422 void operator<<(
2423 typename internal::WCharHelper<const wchar_t *, Char>::Unsupported);
2424
2425 // Appends floating-point length specifier to the format string.
2426 // The second argument is only used for overload resolution.
2427 void append_float_length(Char *&format_ptr, long double) {
2428 *format_ptr++ = 'L';
2429 }
2430
2431 template<typename T>
2432 void append_float_length(Char *&, T) {}
2433
2434 template <typename Impl, typename Char_>
2435 friend class internal::ArgFormatterBase;
2436
2437 friend class internal::PrintfArgFormatter<Char>;
2438
2439 protected:
2440 /**
2441 Constructs a ``BasicWriter`` object.
2442 */
2443 explicit BasicWriter(Buffer<Char> &b) : buffer_(b) {}
2444
2445 public:
2446 /**
2447 \rst
2448 Destroys a ``BasicWriter`` object.
2449 \endrst
2450 */
2451 virtual ~BasicWriter() {}
2452
2453 /**
2454 Returns the total number of characters written.
2455 */
2456 std::size_t size() const { return buffer_.size(); }
2457
2458 /**
2459 Returns a pointer to the output buffer content. No terminating null
2460 character is appended.
2461 */
2462 const Char *data() const FMT_NOEXCEPT { return &buffer_[0]; }
2463
2464 /**
2465 Returns a pointer to the output buffer content with terminating null
2466 character appended.
2467 */
2468 const Char *c_str() const {
2469 std::size_t size = buffer_.size();
2470 buffer_.reserve(size + 1);
2471 buffer_[size] = '\0';
2472 return &buffer_[0];
2473 }
2474
2475 /**
2476 \rst
2477 Returns the content of the output buffer as an `std::string`.
2478 \endrst
2479 */
2480 std::basic_string<Char> str() const {
2481 return std::basic_string<Char>(&buffer_[0], buffer_.size());
2482 }
2483
2484 /**
2485 \rst
2486 Writes formatted data.
2487
2488 *args* is an argument list representing arbitrary arguments.
2489
2490 **Example**::
2491
2492 MemoryWriter out;
2493 out.write("Current point:\n");
2494 out.write("({:+f}, {:+f})", -3.14, 3.14);
2495
2496 This will write the following output to the ``out`` object:
2497
2498 .. code-block:: none
2499
2500 Current point:
2501 (-3.140000, +3.140000)
2502
2503 The output can be accessed using :func:`data()`, :func:`c_str` or
2504 :func:`str` methods.
2505
2506 See also :ref:`syntax`.
2507 \endrst
2508 */
2509 void write(BasicCStringRef<Char> format, ArgList args) {
2510 BasicFormatter<Char>(args, *this).format(format);
2511 }
2512 FMT_VARIADIC_VOID(write, BasicCStringRef<Char>)
2513
2514 BasicWriter &operator<<(int value) {
2515 write_decimal(value);
2516 return *this;
2517 }
2518 BasicWriter &operator<<(unsigned value) {
2519 return *this << IntFormatSpec<unsigned>(value);
2520 }
2521 BasicWriter &operator<<(long value) {
2522 write_decimal(value);
2523 return *this;
2524 }
2525 BasicWriter &operator<<(unsigned long value) {
2526 return *this << IntFormatSpec<unsigned long>(value);
2527 }
2528 BasicWriter &operator<<(LongLong value) {
2529 write_decimal(value);
2530 return *this;
2531 }
2532
2533 /**
2534 \rst
2535 Formats *value* and writes it to the stream.
2536 \endrst
2537 */
2538 BasicWriter &operator<<(ULongLong value) {
2539 return *this << IntFormatSpec<ULongLong>(value);
2540 }
2541
2542 BasicWriter &operator<<(double value) {
2543 write_double(value, FormatSpec());
2544 return *this;
2545 }
2546
2547 /**
2548 \rst
2549 Formats *value* using the general format for floating-point numbers
2550 (``'g'``) and writes it to the stream.
2551 \endrst
2552 */
2553 BasicWriter &operator<<(long double value) {
2554 write_double(value, FormatSpec());
2555 return *this;
2556 }
2557
2558 /**
2559 Writes a character to the stream.
2560 */
2561 BasicWriter &operator<<(char value) {
2562 buffer_.push_back(value);
2563 return *this;
2564 }
2565
2566 BasicWriter &operator<<(
2567 typename internal::WCharHelper<wchar_t, Char>::Supported value) {
2568 buffer_.push_back(value);
2569 return *this;
2570 }
2571
2572 /**
2573 \rst
2574 Writes *value* to the stream.
2575 \endrst
2576 */
2577 BasicWriter &operator<<(fmt::BasicStringRef<Char> value) {
2578 const Char *str = value.data();
2579 buffer_.append(str, str + value.size());
2580 return *this;
2581 }
2582
2583 BasicWriter &operator<<(
2584 typename internal::WCharHelper<StringRef, Char>::Supported value) {
2585 const char *str = value.data();
2586 buffer_.append(str, str + value.size());
2587 return *this;
2588 }
2589
2590 template <typename T, typename Spec, typename FillChar>
2591 BasicWriter &operator<<(IntFormatSpec<T, Spec, FillChar> spec) {
2592 internal::CharTraits<Char>::convert(FillChar());
2593 write_int(spec.value(), spec);
2594 return *this;
2595 }
2596
2597 template <typename StrChar>
2598 BasicWriter &operator<<(const StrFormatSpec<StrChar> &spec) {
2599 const StrChar *s = spec.str();
2600 write_str(s, std::char_traits<Char>::length(s), spec);
2601 return *this;
2602 }
2603
2604 void clear() FMT_NOEXCEPT { buffer_.clear(); }
2605
2606 Buffer<Char> &buffer() FMT_NOEXCEPT { return buffer_; }
2607 };
2608
2609 template <typename Char>
2610 template <typename StrChar>
2611 typename BasicWriter<Char>::CharPtr BasicWriter<Char>::write_str(
2612 const StrChar *s, std::size_t size, const AlignSpec &spec) {
2613 CharPtr out = CharPtr();
2614 if (spec.width() > size) {
2615 out = grow_buffer(spec.width());
2616 Char fill = internal::CharTraits<Char>::cast(spec.fill());
2617 if (spec.align() == ALIGN_RIGHT) {
2618 std::uninitialized_fill_n(out, spec.width() - size, fill);
2619 out += spec.width() - size;
2620 }
2621 else if (spec.align() == ALIGN_CENTER) {
2622 out = fill_padding(out, spec.width(), size, fill);
2623 }
2624 else {
2625 std::uninitialized_fill_n(out + size, spec.width() - size, fill);
2626 }
2627 }
2628 else {
2629 out = grow_buffer(size);
2630 }
2631 std::uninitialized_copy(s, s + size, out);
2632 return out;
2633 }
2634
2635 template <typename Char>
2636 template <typename StrChar>
2637 void BasicWriter<Char>::write_str(
2638 const internal::Arg::StringValue<StrChar> &s, const FormatSpec &spec) {
2639 // Check if StrChar is convertible to Char.
2640 internal::CharTraits<Char>::convert(StrChar());
2641 if (spec.type_ && spec.type_ != 's')
2642 internal::report_unknown_type(spec.type_, "string");
2643 const StrChar *str_value = s.value;
2644 std::size_t str_size = s.size;
2645 if (str_size == 0) {
2646 if (!str_value) {
2647 FMT_THROW(FormatError("string pointer is null"));
2648 }
2649 }
2650 std::size_t precision = static_cast<std::size_t>(spec.precision_);
2651 if (spec.precision_ >= 0 && precision < str_size)
2652 str_size = precision;
2653 write_str(str_value, str_size, spec);
2654 }
2655
2656 template <typename Char>
2657 typename BasicWriter<Char>::CharPtr
2658 BasicWriter<Char>::fill_padding(
2659 CharPtr buffer, unsigned total_size,
2660 std::size_t content_size, wchar_t fill) {
2661 std::size_t padding = total_size - content_size;
2662 std::size_t left_padding = padding / 2;
2663 Char fill_char = internal::CharTraits<Char>::cast(fill);
2664 std::uninitialized_fill_n(buffer, left_padding, fill_char);
2665 buffer += left_padding;
2666 CharPtr content = buffer;
2667 std::uninitialized_fill_n(buffer + content_size,
2668 padding - left_padding, fill_char);
2669 return content;
2670 }
2671
2672 template <typename Char>
2673 template <typename Spec>
2674 typename BasicWriter<Char>::CharPtr
2675 BasicWriter<Char>::prepare_int_buffer(
2676 unsigned num_digits, const Spec &spec,
2677 const char *prefix, unsigned prefix_size) {
2678 unsigned width = spec.width();
2679 Alignment align = spec.align();
2680 Char fill = internal::CharTraits<Char>::cast(spec.fill());
2681 if (spec.precision() > static_cast<int>(num_digits)) {
2682 // Octal prefix '0' is counted as a digit, so ignore it if precision
2683 // is specified.
2684 if (prefix_size > 0 && prefix[prefix_size - 1] == '0')
2685 --prefix_size;
2686 unsigned number_size =
2687 prefix_size + internal::to_unsigned(spec.precision());
2688 AlignSpec subspec(number_size, '0', ALIGN_NUMERIC);
2689 if (number_size >= width)
2690 return prepare_int_buffer(num_digits, subspec, prefix, prefix_size);
2691 buffer_.reserve(width);
2692 unsigned fill_size = width - number_size;
2693 if (align != ALIGN_LEFT) {
2694 CharPtr p = grow_buffer(fill_size);
2695 std::uninitialized_fill(p, p + fill_size, fill);
2696 }
2697 CharPtr result = prepare_int_buffer(
2698 num_digits, subspec, prefix, prefix_size);
2699 if (align == ALIGN_LEFT) {
2700 CharPtr p = grow_buffer(fill_size);
2701 std::uninitialized_fill(p, p + fill_size, fill);
2702 }
2703 return result;
2704 }
2705 unsigned size = prefix_size + num_digits;
2706 if (width <= size) {
2707 CharPtr p = grow_buffer(size);
2708 std::uninitialized_copy(prefix, prefix + prefix_size, p);
2709 return p + size - 1;
2710 }
2711 CharPtr p = grow_buffer(width);
2712 CharPtr end = p + width;
2713 if (align == ALIGN_LEFT) {
2714 std::uninitialized_copy(prefix, prefix + prefix_size, p);
2715 p += size;
2716 std::uninitialized_fill(p, end, fill);
2717 }
2718 else if (align == ALIGN_CENTER) {
2719 p = fill_padding(p, width, size, fill);
2720 std::uninitialized_copy(prefix, prefix + prefix_size, p);
2721 p += size;
2722 }
2723 else {
2724 if (align == ALIGN_NUMERIC) {
2725 if (prefix_size != 0) {
2726 p = std::uninitialized_copy(prefix, prefix + prefix_size, p);
2727 size -= prefix_size;
2728 }
2729 }
2730 else {
2731 std::uninitialized_copy(prefix, prefix + prefix_size, end - size);
2732 }
2733 std::uninitialized_fill(p, end - size, fill);
2734 p = end;
2735 }
2736 return p - 1;
2737 }
2738
2739 template <typename Char>
2740 template <typename T, typename Spec>
2741 void BasicWriter<Char>::write_int(T value, Spec spec) {
2742 unsigned prefix_size = 0;
2743 typedef typename internal::IntTraits<T>::MainType UnsignedType;
2744 UnsignedType abs_value = static_cast<UnsignedType>(value);
2745 char prefix[4] = "";
2746 if (internal::is_negative(value)) {
2747 prefix[0] = '-';
2748 ++prefix_size;
2749 abs_value = 0 - abs_value;
2750 }
2751 else if (spec.flag(SIGN_FLAG)) {
2752 prefix[0] = spec.flag(PLUS_FLAG) ? '+' : ' ';
2753 ++prefix_size;
2754 }
2755 switch (spec.type()) {
2756 case 0: case 'd': {
2757 unsigned num_digits = internal::count_digits(abs_value);
2758 CharPtr p = prepare_int_buffer(num_digits, spec, prefix, prefix_size) + 1;
2759 internal::format_decimal(get(p), abs_value, 0);
2760 break;
2761 }
2762 case 'x': case 'X': {
2763 UnsignedType n = abs_value;
2764 if (spec.flag(HASH_FLAG)) {
2765 prefix[prefix_size++] = '0';
2766 prefix[prefix_size++] = spec.type();
2767 }
2768 unsigned num_digits = 0;
2769 do {
2770 ++num_digits;
2771 } while ((n >>= 4) != 0);
2772 Char *p = get(prepare_int_buffer(
2773 num_digits, spec, prefix, prefix_size));
2774 n = abs_value;
2775 const char *digits = spec.type() == 'x' ?
2776 "0123456789abcdef" : "0123456789ABCDEF";
2777 do {
2778 *p-- = digits[n & 0xf];
2779 } while ((n >>= 4) != 0);
2780 break;
2781 }
2782 case 'b': case 'B': {
2783 UnsignedType n = abs_value;
2784 if (spec.flag(HASH_FLAG)) {
2785 prefix[prefix_size++] = '0';
2786 prefix[prefix_size++] = spec.type();
2787 }
2788 unsigned num_digits = 0;
2789 do {
2790 ++num_digits;
2791 } while ((n >>= 1) != 0);
2792 Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size));
2793 n = abs_value;
2794 do {
2795 *p-- = static_cast<Char>('0' + (n & 1));
2796 } while ((n >>= 1) != 0);
2797 break;
2798 }
2799 case 'o': {
2800 UnsignedType n = abs_value;
2801 if (spec.flag(HASH_FLAG))
2802 prefix[prefix_size++] = '0';
2803 unsigned num_digits = 0;
2804 do {
2805 ++num_digits;
2806 } while ((n >>= 3) != 0);
2807 Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size));
2808 n = abs_value;
2809 do {
2810 *p-- = static_cast<Char>('0' + (n & 7));
2811 } while ((n >>= 3) != 0);
2812 break;
2813 }
2814 case 'n': {
2815 unsigned num_digits = internal::count_digits(abs_value);
2816 fmt::StringRef sep = "";
2817 #ifndef ANDROID
2818 sep = internal::thousands_sep(std::localeconv());
2819 #endif
2820 unsigned size = static_cast<unsigned>(
2821 num_digits + sep.size() * ((num_digits - 1) / 3));
2822 CharPtr p = prepare_int_buffer(size, spec, prefix, prefix_size) + 1;
2823 internal::format_decimal(get(p), abs_value, 0, internal::ThousandsSep(sep));
2824 break;
2825 }
2826 default:
2827 internal::report_unknown_type(
2828 spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer");
2829 break;
2830 }
2831 }
2832
2833 template <typename Char>
2834 template <typename T>
2835 void BasicWriter<Char>::write_double(T value, const FormatSpec &spec) {
2836 // Check type.
2837 char type = spec.type();
2838 bool upper = false;
2839 switch (type) {
2840 case 0:
2841 type = 'g';
2842 break;
2843 case 'e': case 'f': case 'g': case 'a':
2844 break;
2845 case 'F':
2846 #if FMT_MSC_VER
2847 // MSVC's printf doesn't support 'F'.
2848 type = 'f';
2849 #endif
2850 // Fall through.
2851 case 'E': case 'G': case 'A':
2852 upper = true;
2853 break;
2854 default:
2855 internal::report_unknown_type(type, "double");
2856 break;
2857 }
2858
2859 char sign = 0;
2860 // Use isnegative instead of value < 0 because the latter is always
2861 // false for NaN.
2862 if (internal::FPUtil::isnegative(static_cast<double>(value))) {
2863 sign = '-';
2864 value = -value;
2865 }
2866 else if (spec.flag(SIGN_FLAG)) {
2867 sign = spec.flag(PLUS_FLAG) ? '+' : ' ';
2868 }
2869
2870 if (internal::FPUtil::isnotanumber(value)) {
2871 // Format NaN ourselves because sprintf's output is not consistent
2872 // across platforms.
2873 std::size_t nan_size = 4;
2874 const char *nan = upper ? " NAN" : " nan";
2875 if (!sign) {
2876 --nan_size;
2877 ++nan;
2878 }
2879 CharPtr out = write_str(nan, nan_size, spec);
2880 if (sign)
2881 *out = sign;
2882 return;
2883 }
2884
2885 if (internal::FPUtil::isinfinity(value)) {
2886 // Format infinity ourselves because sprintf's output is not consistent
2887 // across platforms.
2888 std::size_t inf_size = 4;
2889 const char *inf = upper ? " INF" : " inf";
2890 if (!sign) {
2891 --inf_size;
2892 ++inf;
2893 }
2894 CharPtr out = write_str(inf, inf_size, spec);
2895 if (sign)
2896 *out = sign;
2897 return;
2898 }
2899
2900 std::size_t offset = buffer_.size();
2901 unsigned width = spec.width();
2902 if (sign) {
2903 buffer_.reserve(buffer_.size() + (width > 1u ? width : 1u));
2904 if (width > 0)
2905 --width;
2906 ++offset;
2907 }
2908
2909 // Build format string.
2910 enum { MAX_FORMAT_SIZE = 10 }; // longest format: %#-*.*Lg
2911 Char format[MAX_FORMAT_SIZE];
2912 Char *format_ptr = format;
2913 *format_ptr++ = '%';
2914 unsigned width_for_sprintf = width;
2915 if (spec.flag(HASH_FLAG))
2916 *format_ptr++ = '#';
2917 if (spec.align() == ALIGN_CENTER) {
2918 width_for_sprintf = 0;
2919 }
2920 else {
2921 if (spec.align() == ALIGN_LEFT)
2922 *format_ptr++ = '-';
2923 if (width != 0)
2924 *format_ptr++ = '*';
2925 }
2926 if (spec.precision() >= 0) {
2927 *format_ptr++ = '.';
2928 *format_ptr++ = '*';
2929 }
2930
2931 append_float_length(format_ptr, value);
2932 *format_ptr++ = type;
2933 *format_ptr = '\0';
2934
2935 // Format using snprintf.
2936 Char fill = internal::CharTraits<Char>::cast(spec.fill());
2937 unsigned n = 0;
2938 Char *start = 0;
2939 for (;;) {
2940 std::size_t buffer_size = buffer_.capacity() - offset;
2941 #if FMT_MSC_VER
2942 // MSVC's vsnprintf_s doesn't work with zero size, so reserve
2943 // space for at least one extra character to make the size non-zero.
2944 // Note that the buffer's capacity will increase by more than 1.
2945 if (buffer_size == 0) {
2946 buffer_.reserve(offset + 1);
2947 buffer_size = buffer_.capacity() - offset;
2948 }
2949 #endif
2950 start = &buffer_[offset];
2951 int result = internal::CharTraits<Char>::format_float(
2952 start, buffer_size, format, width_for_sprintf, spec.precision(), value);
2953 if (result >= 0) {
2954 n = internal::to_unsigned(result);
2955 if (offset + n < buffer_.capacity())
2956 break; // The buffer is large enough - continue with formatting.
2957 buffer_.reserve(offset + n + 1);
2958 }
2959 else {
2960 // If result is negative we ask to increase the capacity by at least 1,
2961 // but as std::vector, the buffer grows exponentially.
2962 buffer_.reserve(buffer_.capacity() + 1);
2963 }
2964 }
2965 if (sign) {
2966 if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) ||
2967 *start != ' ') {
2968 *(start - 1) = sign;
2969 sign = 0;
2970 }
2971 else {
2972 *(start - 1) = fill;
2973 }
2974 ++n;
2975 }
2976 if (spec.align() == ALIGN_CENTER && spec.width() > n) {
2977 width = spec.width();
2978 CharPtr p = grow_buffer(width);
2979 std::memmove(get(p) + (width - n) / 2, get(p), n * sizeof(Char));
2980 fill_padding(p, spec.width(), n, fill);
2981 return;
2982 }
2983 if (spec.fill() != ' ' || sign) {
2984 while (*start == ' ')
2985 *start++ = fill;
2986 if (sign)
2987 *(start - 1) = sign;
2988 }
2989 grow_buffer(n);
2990 }
2991
2992 /**
2993 \rst
2994 This class template provides operations for formatting and writing data
2995 into a character stream. The output is stored in a memory buffer that grows
2996 dynamically.
2997
2998 You can use one of the following typedefs for common character types
2999 and the standard allocator:
3000
3001 +---------------+-----------------------------------------------------+
3002 | Type | Definition |
3003 +===============+=====================================================+
3004 | MemoryWriter | BasicMemoryWriter<char, std::allocator<char>> |
3005 +---------------+-----------------------------------------------------+
3006 | WMemoryWriter | BasicMemoryWriter<wchar_t, std::allocator<wchar_t>> |
3007 +---------------+-----------------------------------------------------+
3008
3009 **Example**::
3010
3011 MemoryWriter out;
3012 out << "The answer is " << 42 << "\n";
3013 out.write("({:+f}, {:+f})", -3.14, 3.14);
3014
3015 This will write the following output to the ``out`` object:
3016
3017 .. code-block:: none
3018
3019 The answer is 42
3020 (-3.140000, +3.140000)
3021
3022 The output can be converted to an ``std::string`` with ``out.str()`` or
3023 accessed as a C string with ``out.c_str()``.
3024 \endrst
3025 */
3026 template <typename Char, typename Allocator = std::allocator<Char> >
3027 class BasicMemoryWriter : public BasicWriter<Char> {
3028 private:
3029 internal::MemoryBuffer<Char, internal::INLINE_BUFFER_SIZE, Allocator> buffer_;
3030
3031 public:
3032 explicit BasicMemoryWriter(const Allocator& alloc = Allocator())
3033 : BasicWriter<Char>(buffer_), buffer_(alloc) {}
3034
3035 #if FMT_USE_RVALUE_REFERENCES
3036 /**
3037 \rst
3038 Constructs a :class:`fmt::BasicMemoryWriter` object moving the content
3039 of the other object to it.
3040 \endrst
3041 */
3042 BasicMemoryWriter(BasicMemoryWriter &&other)
3043 : BasicWriter<Char>(buffer_), buffer_(std::move(other.buffer_)) {
3044 }
3045
3046 /**
3047 \rst
3048 Moves the content of the other ``BasicMemoryWriter`` object to this one.
3049 \endrst
3050 */
3051 BasicMemoryWriter &operator=(BasicMemoryWriter &&other) {
3052 buffer_ = std::move(other.buffer_);
3053 return *this;
3054 }
3055 #endif
3056 };
3057
3058 typedef BasicMemoryWriter<char> MemoryWriter;
3059 typedef BasicMemoryWriter<wchar_t> WMemoryWriter;
3060
3061 /**
3062 \rst
3063 This class template provides operations for formatting and writing data
3064 into a fixed-size array. For writing into a dynamically growing buffer
3065 use :class:`fmt::BasicMemoryWriter`.
3066
3067 Any write method will throw ``std::runtime_error`` if the output doesn't fit
3068 into the array.
3069
3070 You can use one of the following typedefs for common character types:
3071
3072 +--------------+---------------------------+
3073 | Type | Definition |
3074 +==============+===========================+
3075 | ArrayWriter | BasicArrayWriter<char> |
3076 +--------------+---------------------------+
3077 | WArrayWriter | BasicArrayWriter<wchar_t> |
3078 +--------------+---------------------------+
3079 \endrst
3080 */
3081 template <typename Char>
3082 class BasicArrayWriter : public BasicWriter<Char> {
3083 private:
3084 internal::FixedBuffer<Char> buffer_;
3085
3086 public:
3087 /**
3088 \rst
3089 Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the
3090 given size.
3091 \endrst
3092 */
3093 BasicArrayWriter(Char *array, std::size_t size)
3094 : BasicWriter<Char>(buffer_), buffer_(array, size) {}
3095
3096 /**
3097 \rst
3098 Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the
3099 size known at compile time.
3100 \endrst
3101 */
3102 template <std::size_t SIZE>
3103 explicit BasicArrayWriter(Char(&array)[SIZE])
3104 : BasicWriter<Char>(buffer_), buffer_(array, SIZE) {}
3105 };
3106
3107 typedef BasicArrayWriter<char> ArrayWriter;
3108 typedef BasicArrayWriter<wchar_t> WArrayWriter;
3109
3110 // Reports a system error without throwing an exception.
3111 // Can be used to report errors from destructors.
3112 FMT_API void report_system_error(int error_code,
3113 StringRef message) FMT_NOEXCEPT;
3114
3115 #if FMT_USE_WINDOWS_H
3116
3117 /** A Windows error. */
3118 class WindowsError : public SystemError {
3119 private:
3120 FMT_API void init(int error_code, CStringRef format_str, ArgList args);
3121
3122 public:
3123 /**
3124 \rst
3125 Constructs a :class:`fmt::WindowsError` object with the description
3126 of the form
3127
3128 .. parsed-literal::
3129 *<message>*: *<system-message>*
3130
3131 where *<message>* is the formatted message and *<system-message>* is the
3132 system message corresponding to the error code.
3133 *error_code* is a Windows error code as given by ``GetLastError``.
3134 If *error_code* is not a valid error code such as -1, the system message
3135 will look like "error -1".
3136
3137 **Example**::
3138
3139 // This throws a WindowsError with the description
3140 // cannot open file 'madeup': The system cannot find the file specified.
3141 // or similar (system message may vary).
3142 const char *filename = "madeup";
3143 LPOFSTRUCT of = LPOFSTRUCT();
3144 HFILE file = OpenFile(filename, &of, OF_READ);
3145 if (file == HFILE_ERROR) {
3146 throw fmt::WindowsError(GetLastError(),
3147 "cannot open file '{}'", filename);
3148 }
3149 \endrst
3150 */
3151 WindowsError(int error_code, CStringRef message) {
3152 init(error_code, message, ArgList());
3153 }
3154 FMT_VARIADIC_CTOR(WindowsError, init, int, CStringRef)
3155 };
3156
3157 // Reports a Windows error without throwing an exception.
3158 // Can be used to report errors from destructors.
3159 FMT_API void report_windows_error(int error_code,
3160 StringRef message) FMT_NOEXCEPT;
3161
3162 #endif
3163
3164 enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE };
3165
3166 /**
3167 Formats a string and prints it to stdout using ANSI escape sequences
3168 to specify color (experimental).
3169 Example:
3170 print_colored(fmt::RED, "Elapsed time: {0:.2f} seconds", 1.23);
3171 */
3172 FMT_API void print_colored(Color c, CStringRef format, ArgList args);
3173
3174 /**
3175 \rst
3176 Formats arguments and returns the result as a string.
3177
3178 **Example**::
3179
3180 std::string message = format("The answer is {}", 42);
3181 \endrst
3182 */
3183 inline std::string format(CStringRef format_str, ArgList args) {
3184 MemoryWriter w;
3185 w.write(format_str, args);
3186 return w.str();
3187 }
3188
3189 inline std::wstring format(WCStringRef format_str, ArgList args) {
3190 WMemoryWriter w;
3191 w.write(format_str, args);
3192 return w.str();
3193 }
3194
3195 /**
3196 \rst
3197 Prints formatted data to the file *f*.
3198
3199 **Example**::
3200
3201 print(stderr, "Don't {}!", "panic");
3202 \endrst
3203 */
3204 FMT_API void print(std::FILE *f, CStringRef format_str, ArgList args);
3205
3206 /**
3207 \rst
3208 Prints formatted data to ``stdout``.
3209
3210 **Example**::
3211
3212 print("Elapsed time: {0:.2f} seconds", 1.23);
3213 \endrst
3214 */
3215 FMT_API void print(CStringRef format_str, ArgList args);
3216
3217 template <typename Char>
3218 void printf(BasicWriter<Char> &w, BasicCStringRef<Char> format, ArgList args) {
3219 internal::PrintfFormatter<Char>(args).format(w, format);
3220 }
3221
3222 /**
3223 \rst
3224 Formats arguments and returns the result as a string.
3225
3226 **Example**::
3227
3228 std::string message = fmt::sprintf("The answer is %d", 42);
3229 \endrst
3230 */
3231 inline std::string sprintf(CStringRef format, ArgList args) {
3232 MemoryWriter w;
3233 printf(w, format, args);
3234 return w.str();
3235 }
3236
3237 inline std::wstring sprintf(WCStringRef format, ArgList args) {
3238 WMemoryWriter w;
3239 printf(w, format, args);
3240 return w.str();
3241 }
3242
3243 /**
3244 \rst
3245 Prints formatted data to the file *f*.
3246
3247 **Example**::
3248
3249 fmt::fprintf(stderr, "Don't %s!", "panic");
3250 \endrst
3251 */
3252 FMT_API int fprintf(std::FILE *f, CStringRef format, ArgList args);
3253
3254 /**
3255 \rst
3256 Prints formatted data to ``stdout``.
3257
3258 **Example**::
3259
3260 fmt::printf("Elapsed time: %.2f seconds", 1.23);
3261 \endrst
3262 */
3263 inline int printf(CStringRef format, ArgList args) {
3264 return fprintf(stdout, format, args);
3265 }
3266
3267 /**
3268 Fast integer formatter.
3269 */
3270 class FormatInt {
3271 private:
3272 // Buffer should be large enough to hold all digits (digits10 + 1),
3273 // a sign and a null character.
3274 enum { BUFFER_SIZE = std::numeric_limits<ULongLong>::digits10 + 3 };
3275 mutable char buffer_[BUFFER_SIZE];
3276 char *str_;
3277
3278 // Formats value in reverse and returns the number of digits.
3279 char *format_decimal(ULongLong value) {
3280 char *buffer_end = buffer_ + BUFFER_SIZE - 1;
3281 while (value >= 100) {
3282 // Integer division is slow so do it for a group of two digits instead
3283 // of for every digit. The idea comes from the talk by Alexandrescu
3284 // "Three Optimization Tips for C++". See speed-test for a comparison.
3285 unsigned index = static_cast<unsigned>((value % 100) * 2);
3286 value /= 100;
3287 *--buffer_end = internal::Data::DIGITS[index + 1];
3288 *--buffer_end = internal::Data::DIGITS[index];
3289 }
3290 if (value < 10) {
3291 *--buffer_end = static_cast<char>('0' + value);
3292 return buffer_end;
3293 }
3294 unsigned index = static_cast<unsigned>(value * 2);
3295 *--buffer_end = internal::Data::DIGITS[index + 1];
3296 *--buffer_end = internal::Data::DIGITS[index];
3297 return buffer_end;
3298 }
3299
3300 void FormatSigned(LongLong value) {
3301 ULongLong abs_value = static_cast<ULongLong>(value);
3302 bool negative = value < 0;
3303 if (negative)
3304 abs_value = 0 - abs_value;
3305 str_ = format_decimal(abs_value);
3306 if (negative)
3307 *--str_ = '-';
3308 }
3309
3310 public:
3311 explicit FormatInt(int value) { FormatSigned(value); }
3312 explicit FormatInt(long value) { FormatSigned(value); }
3313 explicit FormatInt(LongLong value) { FormatSigned(value); }
3314 explicit FormatInt(unsigned value) : str_(format_decimal(value)) {}
3315 explicit FormatInt(unsigned long value) : str_(format_decimal(value)) {}
3316 explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {}
3317
3318 /** Returns the number of characters written to the output buffer. */
3319 std::size_t size() const {
3320 return internal::to_unsigned(buffer_ - str_ + BUFFER_SIZE - 1);
3321 }
3322
3323 /**
3324 Returns a pointer to the output buffer content. No terminating null
3325 character is appended.
3326 */
3327 const char *data() const { return str_; }
3328
3329 /**
3330 Returns a pointer to the output buffer content with terminating null
3331 character appended.
3332 */
3333 const char *c_str() const {
3334 buffer_[BUFFER_SIZE - 1] = '\0';
3335 return str_;
3336 }
3337
3338 /**
3339 \rst
3340 Returns the content of the output buffer as an ``std::string``.
3341 \endrst
3342 */
3343 std::string str() const { return std::string(str_, size()); }
3344 };
3345
3346 // Formats a decimal integer value writing into buffer and returns
3347 // a pointer to the end of the formatted string. This function doesn't
3348 // write a terminating null character.
3349 template <typename T>
3350 inline void format_decimal(char *&buffer, T value) {
3351 typedef typename internal::IntTraits<T>::MainType MainType;
3352 MainType abs_value = static_cast<MainType>(value);
3353 if (internal::is_negative(value)) {
3354 *buffer++ = '-';
3355 abs_value = 0 - abs_value;
3356 }
3357 if (abs_value < 100) {
3358 if (abs_value < 10) {
3359 *buffer++ = static_cast<char>('0' + abs_value);
3360 return;
3361 }
3362 unsigned index = static_cast<unsigned>(abs_value * 2);
3363 *buffer++ = internal::Data::DIGITS[index];
3364 *buffer++ = internal::Data::DIGITS[index + 1];
3365 return;
3366 }
3367 unsigned num_digits = internal::count_digits(abs_value);
3368 internal::format_decimal(buffer, abs_value, num_digits);
3369 buffer += num_digits;
3370 }
3371
3372 /**
3373 \rst
3374 Returns a named argument for formatting functions.
3375
3376 **Example**::
3377
3378 print("Elapsed time: {s:.2f} seconds", arg("s", 1.23));
3379
3380 \endrst
3381 */
3382 template <typename T>
3383 inline internal::NamedArg<char> arg(StringRef name, const T &arg) {
3384 return internal::NamedArg<char>(name, arg);
3385 }
3386
3387 template <typename T>
3388 inline internal::NamedArg<wchar_t> arg(WStringRef name, const T &arg) {
3389 return internal::NamedArg<wchar_t>(name, arg);
3390 }
3391
3392 // The following two functions are deleted intentionally to disable
3393 // nested named arguments as in ``format("{}", arg("a", arg("b", 42)))``.
3394 template <typename Char>
3395 void arg(StringRef, const internal::NamedArg<Char>&) FMT_DELETED_OR_UNDEFINED;
3396 template <typename Char>
3397 void arg(WStringRef, const internal::NamedArg<Char>&) FMT_DELETED_OR_UNDEFINED;
3398 }
3399
3400 #if FMT_GCC_VERSION
3401 // Use the system_header pragma to suppress warnings about variadic macros
3402 // because suppressing -Wvariadic-macros with the diagnostic pragma doesn't
3403 // work. It is used at the end because we want to suppress as little warnings
3404 // as possible.
3405 # pragma GCC system_header
3406 #endif
3407
3408 // This is used to work around VC++ bugs in handling variadic macros.
3409 #define FMT_EXPAND(args) args
3410
3411 // Returns the number of arguments.
3412 // Based on https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s.
3413 #define FMT_NARG(...) FMT_NARG_(__VA_ARGS__, FMT_RSEQ_N())
3414 #define FMT_NARG_(...) FMT_EXPAND(FMT_ARG_N(__VA_ARGS__))
3415 #define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
3416 #define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
3417
3418 #define FMT_CONCAT(a, b) a##b
3419 #define FMT_FOR_EACH_(N, f, ...) \
3420 FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__))
3421 #define FMT_FOR_EACH(f, ...) \
3422 FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__))
3423
3424 #define FMT_ADD_ARG_NAME(type, index) type arg##index
3425 #define FMT_GET_ARG_NAME(type, index) arg##index
3426
3427 #if FMT_USE_VARIADIC_TEMPLATES
3428 # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \
3429 template <typename... Args> \
3430 ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \
3431 const Args & ... args) { \
3432 typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \
3433 typename ArgArray::Type array{ \
3434 ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \
3435 call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), \
3436 fmt::ArgList(fmt::internal::make_type(args...), array)); \
3437 }
3438 #else
3439 // Defines a wrapper for a function taking __VA_ARGS__ arguments
3440 // and n additional arguments of arbitrary types.
3441 # define FMT_WRAP(Char, ReturnType, func, call, n, ...) \
3442 template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
3443 inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \
3444 FMT_GEN(n, FMT_MAKE_ARG)) { \
3445 fmt::internal::ArgArray<n>::Type arr; \
3446 FMT_GEN(n, FMT_ASSIGN_##Char); \
3447 call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \
3448 fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), arr)); \
3449 }
3450
3451 # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \
3452 inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) { \
3453 call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \
3454 } \
3455 FMT_WRAP(Char, ReturnType, func, call, 1, __VA_ARGS__) \
3456 FMT_WRAP(Char, ReturnType, func, call, 2, __VA_ARGS__) \
3457 FMT_WRAP(Char, ReturnType, func, call, 3, __VA_ARGS__) \
3458 FMT_WRAP(Char, ReturnType, func, call, 4, __VA_ARGS__) \
3459 FMT_WRAP(Char, ReturnType, func, call, 5, __VA_ARGS__) \
3460 FMT_WRAP(Char, ReturnType, func, call, 6, __VA_ARGS__) \
3461 FMT_WRAP(Char, ReturnType, func, call, 7, __VA_ARGS__) \
3462 FMT_WRAP(Char, ReturnType, func, call, 8, __VA_ARGS__) \
3463 FMT_WRAP(Char, ReturnType, func, call, 9, __VA_ARGS__) \
3464 FMT_WRAP(Char, ReturnType, func, call, 10, __VA_ARGS__) \
3465 FMT_WRAP(Char, ReturnType, func, call, 11, __VA_ARGS__) \
3466 FMT_WRAP(Char, ReturnType, func, call, 12, __VA_ARGS__) \
3467 FMT_WRAP(Char, ReturnType, func, call, 13, __VA_ARGS__) \
3468 FMT_WRAP(Char, ReturnType, func, call, 14, __VA_ARGS__) \
3469 FMT_WRAP(Char, ReturnType, func, call, 15, __VA_ARGS__)
3470 #endif // FMT_USE_VARIADIC_TEMPLATES
3471
3472 /**
3473 \rst
3474 Defines a variadic function with the specified return type, function name
3475 and argument types passed as variable arguments to this macro.
3476
3477 **Example**::
3478
3479 void print_error(const char *file, int line, const char *format,
3480 fmt::ArgList args) {
3481 fmt::print("{}: {}: ", file, line);
3482 fmt::print(format, args);
3483 }
3484 FMT_VARIADIC(void, print_error, const char *, int, const char *)
3485
3486 ``FMT_VARIADIC`` is used for compatibility with legacy C++ compilers that
3487 don't implement variadic templates. You don't have to use this macro if
3488 you don't need legacy compiler support and can use variadic templates
3489 directly::
3490
3491 template <typename... Args>
3492 void print_error(const char *file, int line, const char *format,
3493 const Args & ... args) {
3494 fmt::print("{}: {}: ", file, line);
3495 fmt::print(format, args...);
3496 }
3497 \endrst
3498 */
3499 #define FMT_VARIADIC(ReturnType, func, ...) \
3500 FMT_VARIADIC_(char, ReturnType, func, return func, __VA_ARGS__)
3501
3502 #define FMT_VARIADIC_W(ReturnType, func, ...) \
3503 FMT_VARIADIC_(wchar_t, ReturnType, func, return func, __VA_ARGS__)
3504
3505 #define FMT_CAPTURE_ARG_(id, index) ::fmt::arg(#id, id)
3506
3507 #define FMT_CAPTURE_ARG_W_(id, index) ::fmt::arg(L###id, id)
3508
3509 /**
3510 \rst
3511 Convenient macro to capture the arguments' names and values into several
3512 ``fmt::arg(name, value)``.
3513
3514 **Example**::
3515
3516 int x = 1, y = 2;
3517 print("point: ({x}, {y})", FMT_CAPTURE(x, y));
3518 // same as:
3519 // print("point: ({x}, {y})", arg("x", x), arg("y", y));
3520
3521 \endrst
3522 */
3523 #define FMT_CAPTURE(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_, __VA_ARGS__)
3524
3525 #define FMT_CAPTURE_W(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_W_, __VA_ARGS__)
3526
3527 namespace fmt {
3528 FMT_VARIADIC(std::string, format, CStringRef)
3529 FMT_VARIADIC_W(std::wstring, format, WCStringRef)
3530 FMT_VARIADIC(void, print, CStringRef)
3531 FMT_VARIADIC(void, print, std::FILE *, CStringRef)
3532
3533 FMT_VARIADIC(void, print_colored, Color, CStringRef)
3534 FMT_VARIADIC(std::string, sprintf, CStringRef)
3535 FMT_VARIADIC_W(std::wstring, sprintf, WCStringRef)
3536 FMT_VARIADIC(int, printf, CStringRef)
3537 FMT_VARIADIC(int, fprintf, std::FILE *, CStringRef)
3538
3539 namespace internal {
3540 template <typename Char>
3541 inline bool is_name_start(Char c) {
3542 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c;
3543 }
3544
3545 // Parses an unsigned integer advancing s to the end of the parsed input.
3546 // This function assumes that the first character of s is a digit.
3547 template <typename Char>
3548 unsigned parse_nonnegative_int(const Char *&s) {
3549 assert('0' <= *s && *s <= '9');
3550 unsigned value = 0;
3551 do {
3552 unsigned new_value = value * 10 + (*s++ - '0');
3553 // Check if value wrapped around.
3554 if (new_value < value) {
3555 value = (std::numeric_limits<unsigned>::max)();
3556 break;
3557 }
3558 value = new_value;
3559 } while ('0' <= *s && *s <= '9');
3560 // Convert to unsigned to prevent a warning.
3561 unsigned max_int = (std::numeric_limits<int>::max)();
3562 if (value > max_int)
3563 FMT_THROW(FormatError("number is too big"));
3564 return value;
3565 }
3566
3567 inline void require_numeric_argument(const Arg &arg, char spec) {
3568 if (arg.type > Arg::LAST_NUMERIC_TYPE) {
3569 std::string message =
3570 fmt::format("format specifier '{}' requires numeric argument", spec);
3571 FMT_THROW(fmt::FormatError(message));
3572 }
3573 }
3574
3575 template <typename Char>
3576 void check_sign(const Char *&s, const Arg &arg) {
3577 char sign = static_cast<char>(*s);
3578 require_numeric_argument(arg, sign);
3579 if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) {
3580 FMT_THROW(FormatError(fmt::format(
3581 "format specifier '{}' requires signed argument", sign)));
3582 }
3583 ++s;
3584 }
3585 } // namespace internal
3586
3587 template <typename Char, typename AF>
3588 inline internal::Arg BasicFormatter<Char, AF>::get_arg(
3589 BasicStringRef<Char> arg_name, const char *&error) {
3590 if (check_no_auto_index(error)) {
3591 map_.init(args());
3592 const internal::Arg *arg = map_.find(arg_name);
3593 if (arg)
3594 return *arg;
3595 error = "argument not found";
3596 }
3597 return internal::Arg();
3598 }
3599
3600 template <typename Char, typename AF>
3601 inline internal::Arg BasicFormatter<Char, AF>::parse_arg_index(const Char *&s) {
3602 const char *error = 0;
3603 internal::Arg arg = *s < '0' || *s > '9' ?
3604 next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error);
3605 if (error) {
3606 FMT_THROW(FormatError(
3607 *s != '}' && *s != ':' ? "invalid format string" : error));
3608 }
3609 return arg;
3610 }
3611
3612 template <typename Char, typename AF>
3613 inline internal::Arg BasicFormatter<Char, AF>::parse_arg_name(const Char *&s) {
3614 assert(internal::is_name_start(*s));
3615 const Char *start = s;
3616 Char c;
3617 do {
3618 c = *++s;
3619 } while (internal::is_name_start(c) || ('0' <= c && c <= '9'));
3620 const char *error = 0;
3621 internal::Arg arg = get_arg(BasicStringRef<Char>(start, s - start), error);
3622 if (error)
3623 FMT_THROW(FormatError(error));
3624 return arg;
3625 }
3626
3627 template <typename Char, typename ArgFormatter>
3628 const Char *BasicFormatter<Char, ArgFormatter>::format(
3629 const Char *&format_str, const internal::Arg &arg) {
3630 using internal::Arg;
3631 const Char *s = format_str;
3632 FormatSpec spec;
3633 if (*s == ':') {
3634 if (arg.type == Arg::CUSTOM) {
3635 arg.custom.format(this, arg.custom.value, &s);
3636 return s;
3637 }
3638 ++s;
3639 // Parse fill and alignment.
3640 if (Char c = *s) {
3641 const Char *p = s + 1;
3642 spec.align_ = ALIGN_DEFAULT;
3643 do {
3644 switch (*p) {
3645 case '<':
3646 spec.align_ = ALIGN_LEFT;
3647 break;
3648 case '>':
3649 spec.align_ = ALIGN_RIGHT;
3650 break;
3651 case '=':
3652 spec.align_ = ALIGN_NUMERIC;
3653 break;
3654 case '^':
3655 spec.align_ = ALIGN_CENTER;
3656 break;
3657 }
3658 if (spec.align_ != ALIGN_DEFAULT) {
3659 if (p != s) {
3660 if (c == '}') break;
3661 if (c == '{')
3662 FMT_THROW(FormatError("invalid fill character '{'"));
3663 s += 2;
3664 spec.fill_ = c;
3665 }
3666 else ++s;
3667 if (spec.align_ == ALIGN_NUMERIC)
3668 require_numeric_argument(arg, '=');
3669 break;
3670 }
3671 } while (--p >= s);
3672 }
3673
3674 // Parse sign.
3675 switch (*s) {
3676 case '+':
3677 check_sign(s, arg);
3678 spec.flags_ |= SIGN_FLAG | PLUS_FLAG;
3679 break;
3680 case '-':
3681 check_sign(s, arg);
3682 spec.flags_ |= MINUS_FLAG;
3683 break;
3684 case ' ':
3685 check_sign(s, arg);
3686 spec.flags_ |= SIGN_FLAG;
3687 break;
3688 }
3689
3690 if (*s == '#') {
3691 require_numeric_argument(arg, '#');
3692 spec.flags_ |= HASH_FLAG;
3693 ++s;
3694 }
3695
3696 // Parse zero flag.
3697 if (*s == '0') {
3698 require_numeric_argument(arg, '0');
3699 spec.align_ = ALIGN_NUMERIC;
3700 spec.fill_ = '0';
3701 ++s;
3702 }
3703
3704 // Parse width.
3705 if ('0' <= *s && *s <= '9') {
3706 spec.width_ = internal::parse_nonnegative_int(s);
3707 }
3708 else if (*s == '{') {
3709 ++s;
3710 Arg width_arg = internal::is_name_start(*s) ?
3711 parse_arg_name(s) : parse_arg_index(s);
3712 if (*s++ != '}')
3713 FMT_THROW(FormatError("invalid format string"));
3714 ULongLong value = 0;
3715 switch (width_arg.type) {
3716 case Arg::INT:
3717 if (width_arg.int_value < 0)
3718 FMT_THROW(FormatError("negative width"));
3719 value = width_arg.int_value;
3720 break;
3721 case Arg::UINT:
3722 value = width_arg.uint_value;
3723 break;
3724 case Arg::LONG_LONG:
3725 if (width_arg.long_long_value < 0)
3726 FMT_THROW(FormatError("negative width"));
3727 value = width_arg.long_long_value;
3728 break;
3729 case Arg::ULONG_LONG:
3730 value = width_arg.ulong_long_value;
3731 break;
3732 default:
3733 FMT_THROW(FormatError("width is not integer"));
3734 }
3735 if (value >(std::numeric_limits<int>::max)())
3736 FMT_THROW(FormatError("number is too big"));
3737 spec.width_ = static_cast<int>(value);
3738 }
3739
3740 // Parse precision.
3741 if (*s == '.') {
3742 ++s;
3743 spec.precision_ = 0;
3744 if ('0' <= *s && *s <= '9') {
3745 spec.precision_ = internal::parse_nonnegative_int(s);
3746 }
3747 else if (*s == '{') {
3748 ++s;
3749 Arg precision_arg = internal::is_name_start(*s) ?
3750 parse_arg_name(s) : parse_arg_index(s);
3751 if (*s++ != '}')
3752 FMT_THROW(FormatError("invalid format string"));
3753 ULongLong value = 0;
3754 switch (precision_arg.type) {
3755 case Arg::INT:
3756 if (precision_arg.int_value < 0)
3757 FMT_THROW(FormatError("negative precision"));
3758 value = precision_arg.int_value;
3759 break;
3760 case Arg::UINT:
3761 value = precision_arg.uint_value;
3762 break;
3763 case Arg::LONG_LONG:
3764 if (precision_arg.long_long_value < 0)
3765 FMT_THROW(FormatError("negative precision"));
3766 value = precision_arg.long_long_value;
3767 break;
3768 case Arg::ULONG_LONG:
3769 value = precision_arg.ulong_long_value;
3770 break;
3771 default:
3772 FMT_THROW(FormatError("precision is not integer"));
3773 }
3774 if (value >(std::numeric_limits<int>::max)())
3775 FMT_THROW(FormatError("number is too big"));
3776 spec.precision_ = static_cast<int>(value);
3777 }
3778 else {
3779 FMT_THROW(FormatError("missing precision specifier"));
3780 }
3781 if (arg.type <= Arg::LAST_INTEGER_TYPE || arg.type == Arg::POINTER) {
3782 FMT_THROW(FormatError(
3783 fmt::format("precision not allowed in {} format specifier",
3784 arg.type == Arg::POINTER ? "pointer" : "integer")));
3785 }
3786 }
3787
3788 // Parse type.
3789 if (*s != '}' && *s)
3790 spec.type_ = static_cast<char>(*s++);
3791 }
3792
3793 if (*s++ != '}')
3794 FMT_THROW(FormatError("missing '}' in format string"));
3795
3796 // Format argument.
3797 ArgFormatter(*this, spec, s - 1).visit(arg);
3798 return s;
3799 }
3800
3801 template <typename Char, typename AF>
3802 void BasicFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) {
3803 const Char *s = format_str.c_str();
3804 const Char *start = s;
3805 while (*s) {
3806 Char c = *s++;
3807 if (c != '{' && c != '}') continue;
3808 if (*s == c) {
3809 write(writer_, start, s);
3810 start = ++s;
3811 continue;
3812 }
3813 if (c == '}')
3814 FMT_THROW(FormatError("unmatched '}' in format string"));
3815 write(writer_, start, s - 1);
3816 internal::Arg arg = internal::is_name_start(*s) ?
3817 parse_arg_name(s) : parse_arg_index(s);
3818 start = s = format(s, arg);
3819 }
3820 write(writer_, start, s);
3821 }
3822 } // namespace fmt
3823
3824 #if FMT_USE_USER_DEFINED_LITERALS
3825 namespace fmt {
3826 namespace internal {
3827
3828 template <typename Char>
3829 struct UdlFormat {
3830 const Char *str;
3831
3832 template <typename... Args>
3833 auto operator()(Args && ... args) const
3834 -> decltype(format(str, std::forward<Args>(args)...)) {
3835 return format(str, std::forward<Args>(args)...);
3836 }
3837 };
3838
3839 template <typename Char>
3840 struct UdlArg {
3841 const Char *str;
3842
3843 template <typename T>
3844 NamedArg<Char> operator=(T &&value) const {
3845 return{ str, std::forward<T>(value) };
3846 }
3847 };
3848
3849 } // namespace internal
3850
3851 inline namespace literals {
3852
3853 /**
3854 \rst
3855 C++11 literal equivalent of :func:`fmt::format`.
3856
3857 **Example**::
3858
3859 using namespace fmt::literals;
3860 std::string message = "The answer is {}"_format(42);
3861 \endrst
3862 */
3863 inline internal::UdlFormat<char>
3864 operator"" _format(const char *s, std::size_t) { return{ s }; }
3865 inline internal::UdlFormat<wchar_t>
3866 operator"" _format(const wchar_t *s, std::size_t) { return{ s }; }
3867
3868 /**
3869 \rst
3870 C++11 literal equivalent of :func:`fmt::arg`.
3871
3872 **Example**::
3873
3874 using namespace fmt::literals;
3875 print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);
3876 \endrst
3877 */
3878 inline internal::UdlArg<char>
3879 operator"" _a(const char *s, std::size_t) { return{ s }; }
3880 inline internal::UdlArg<wchar_t>
3881 operator"" _a(const wchar_t *s, std::size_t) { return{ s }; }
3882
3883 } // inline namespace literals
3884 } // namespace fmt
3885 #endif // FMT_USE_USER_DEFINED_LITERALS
3886
3887 // Restore warnings.
3888 #if FMT_GCC_VERSION >= 406
3889 # pragma GCC diagnostic pop
3890 #endif
3891
3892 #if defined(__clang__) && !defined(FMT_ICC_VERSION)
3893 # pragma clang diagnostic pop
3894 #endif
3895
3896 #ifdef FMT_HEADER_ONLY
3897 # define FMT_FUNC inline
3898 # include "format.cc"
3899 #else
3900 # define FMT_FUNC
3901 #endif
3902
3903 #endif // FMT_FORMAT_H_