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