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