SHARE
TWEET

Untitled

a guest Sep 20th, 2019 91 in 4 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  Formatting library for C++
  3.  
  4.  Copyright (c) 2012 - present, Victor Zverovich
  5.  
  6.  Permission is hereby granted, free of charge, to any person obtaining
  7.  a copy of this software and associated documentation files (the
  8.  "Software"), to deal in the Software without restriction, including
  9.  without limitation the rights to use, copy, modify, merge, publish,
  10.  distribute, sublicense, and/or sell copies of the Software, and to
  11.  permit persons to whom the Software is furnished to do so, subject to
  12.  the following conditions:
  13.  
  14.  The above copyright notice and this permission notice shall be
  15.  included in all copies or substantial portions of the Software.
  16.  
  17.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18.  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19.  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20.  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  21.  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  22.  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  23.  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24.  
  25.  --- Optional exception to the license ---
  26.  
  27.  As an exception, if, as a result of your compiling your source code, portions
  28.  of this Software are embedded into a machine-executable object form of such
  29.  source code, you may redistribute such embedded portions in such object form
  30.  without including the above copyright and permission notices.
  31.  */
  32.  
  33. #ifndef FMT_FORMAT_H_
  34. #define FMT_FORMAT_H_
  35.  
  36. #include <algorithm>
  37. #include <cassert>
  38. #include <cmath>
  39. #include <cstdint>
  40. #include <cstring>
  41. #include <iterator>
  42. #include <limits>
  43. #include <memory>
  44. #include <stdexcept>
  45.  
  46. #include "core.h"
  47.  
  48. #ifdef __clang__
  49. #  define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
  50. #else
  51. #  define FMT_CLANG_VERSION 0
  52. #endif
  53.  
  54. #ifdef __INTEL_COMPILER
  55. #  define FMT_ICC_VERSION __INTEL_COMPILER
  56. #elif defined(__ICL)
  57. #  define FMT_ICC_VERSION __ICL
  58. #else
  59. #  define FMT_ICC_VERSION 0
  60. #endif
  61.  
  62. #ifdef __NVCC__
  63. #  define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__)
  64. #else
  65. #  define FMT_CUDA_VERSION 0
  66. #endif
  67.  
  68. #ifdef __has_builtin
  69. #  define FMT_HAS_BUILTIN(x) __has_builtin(x)
  70. #else
  71. #  define FMT_HAS_BUILTIN(x) 0
  72. #endif
  73.  
  74. #ifndef FMT_THROW
  75. #  if FMT_EXCEPTIONS
  76. #    if FMT_MSC_VER
  77. FMT_BEGIN_NAMESPACE
  78. namespace internal {
  79. template <typename Exception> inline void do_throw(const Exception& x) {
  80.   // Silence unreachable code warnings in MSVC because these are nearly
  81.   // impossible to fix in a generic code.
  82.   volatile bool b = true;
  83.   if (b) throw x;
  84. }
  85. }  // namespace internal
  86. FMT_END_NAMESPACE
  87. #      define FMT_THROW(x) fmt::internal::do_throw(x)
  88. #    else
  89. #      define FMT_THROW(x) throw x
  90. #    endif
  91. #  else
  92. #    define FMT_THROW(x)              \
  93.       do {                            \
  94.         static_cast<void>(sizeof(x)); \
  95.         assert(false);                \
  96.       } while (false)
  97. #  endif
  98. #endif
  99.  
  100. #ifndef FMT_USE_USER_DEFINED_LITERALS
  101. // For Intel and NVIDIA compilers both they and the system gcc/msc support UDLs.
  102. #  if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 407 ||      \
  103.        FMT_MSC_VER >= 1900) &&                                              \
  104.       (!(FMT_ICC_VERSION || FMT_CUDA_VERSION) || FMT_ICC_VERSION >= 1500 || \
  105.        FMT_CUDA_VERSION >= 700)
  106. #    define FMT_USE_USER_DEFINED_LITERALS 1
  107. #  else
  108. #    define FMT_USE_USER_DEFINED_LITERALS 0
  109. #  endif
  110. #endif
  111.  
  112. #ifndef FMT_USE_UDL_TEMPLATE
  113. // EDG front end based compilers (icc, nvcc) do not support UDL templates yet
  114. // and GCC 9 warns about them.
  115. #  if FMT_USE_USER_DEFINED_LITERALS && FMT_ICC_VERSION == 0 && \
  116.       FMT_CUDA_VERSION == 0 &&                                 \
  117.       ((FMT_GCC_VERSION >= 600 && FMT_GCC_VERSION <= 900 &&    \
  118.         __cplusplus >= 201402L) ||                             \
  119.        FMT_CLANG_VERSION >= 304)
  120. #    define FMT_USE_UDL_TEMPLATE 1
  121. #  else
  122. #    define FMT_USE_UDL_TEMPLATE 0
  123. #  endif
  124. #endif
  125.  
  126. // __builtin_clz is broken in clang with Microsoft CodeGen:
  127. // https://github.com/fmtlib/fmt/issues/519
  128. #if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clz)) && !FMT_MSC_VER
  129. #  define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
  130. #endif
  131. #if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clzll)) && !FMT_MSC_VER
  132. #  define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
  133. #endif
  134.  
  135. // Some compilers masquerade as both MSVC and GCC-likes or otherwise support
  136. // __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the
  137. // MSVC intrinsics if the clz and clzll builtins are not available.
  138. #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(_MANAGED)
  139. #  include <intrin.h>  // _BitScanReverse, _BitScanReverse64
  140.  
  141. FMT_BEGIN_NAMESPACE
  142. namespace internal {
  143. // Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning.
  144. #  ifndef __clang__
  145. #    pragma intrinsic(_BitScanReverse)
  146. #  endif
  147. inline uint32_t clz(uint32_t x) {
  148.   unsigned long r = 0;
  149.   _BitScanReverse(&r, x);
  150.  
  151.   assert(x != 0);
  152.   // Static analysis complains about using uninitialized data
  153.   // "r", but the only way that can happen is if "x" is 0,
  154.   // which the callers guarantee to not happen.
  155. #  pragma warning(suppress : 6102)
  156.   return 31 - r;
  157. }
  158. #  define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n)
  159.  
  160. #  if defined(_WIN64) && !defined(__clang__)
  161. #    pragma intrinsic(_BitScanReverse64)
  162. #  endif
  163.  
  164. inline uint32_t clzll(uint64_t x) {
  165.   unsigned long r = 0;
  166. #  ifdef _WIN64
  167.   _BitScanReverse64(&r, x);
  168. #  else
  169.   // Scan the high 32 bits.
  170.   if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32))) return 63 - (r + 32);
  171.  
  172.   // Scan the low 32 bits.
  173.   _BitScanReverse(&r, static_cast<uint32_t>(x));
  174. #  endif
  175.  
  176.   assert(x != 0);
  177.   // Static analysis complains about using uninitialized data
  178.   // "r", but the only way that can happen is if "x" is 0,
  179.   // which the callers guarantee to not happen.
  180. #  pragma warning(suppress : 6102)
  181.   return 63 - r;
  182. }
  183. #  define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n)
  184. }  // namespace internal
  185. FMT_END_NAMESPACE
  186. #endif
  187.  
  188. #ifndef FMT_NUMERIC_ALIGN
  189. #  define FMT_NUMERIC_ALIGN 1
  190. #endif
  191.  
  192. FMT_BEGIN_NAMESPACE
  193. namespace internal {
  194.  
  195. // A fallback implementation of uintptr_t for systems that lack it.
  196. struct fallback_uintptr {
  197.   unsigned char value[sizeof(void*)];
  198. };
  199. #ifdef UINTPTR_MAX
  200. using uintptr_t = ::uintptr_t;
  201. #else
  202. using uintptr_t = fallback_uintptr;
  203. #endif
  204.  
  205. // An equivalent of `*reinterpret_cast<Dest*>(&source)` that doesn't produce
  206. // undefined behavior (e.g. due to type aliasing).
  207. // Example: uint64_t d = bit_cast<uint64_t>(2.718);
  208. template <typename Dest, typename Source>
  209. inline Dest bit_cast(const Source& source) {
  210.   static_assert(sizeof(Dest) == sizeof(Source), "size mismatch");
  211.   Dest dest;
  212.   std::memcpy(&dest, &source, sizeof(dest));
  213.   return dest;
  214. }
  215.  
  216. // Returns the largest possible value for type T. Same as
  217. // std::numeric_limits<T>::max() but shorter and not affected by the max macro.
  218. template <typename T> constexpr T max_value() {
  219.   return (std::numeric_limits<T>::max)();
  220. }
  221.  
  222. // An approximation of iterator_t for pre-C++20 systems.
  223. template <typename T>
  224. using iterator_t = decltype(std::begin(std::declval<T&>()));
  225.  
  226. // Detect the iterator category of *any* given type in a SFINAE-friendly way.
  227. // Unfortunately, older implementations of std::iterator_traits are not safe
  228. // for use in a SFINAE-context.
  229. template <typename It, typename Enable = void>
  230. struct iterator_category : std::false_type {};
  231.  
  232. template <typename T> struct iterator_category<T*> {
  233.   using type = std::random_access_iterator_tag;
  234. };
  235.  
  236. template <typename It>
  237. struct iterator_category<It, void_t<typename It::iterator_category>> {
  238.   using type = typename It::iterator_category;
  239. };
  240.  
  241. // Detect if *any* given type models the OutputIterator concept.
  242. template <typename It> class is_output_iterator {
  243.   // Check for mutability because all iterator categories derived from
  244.   // std::input_iterator_tag *may* also meet the requirements of an
  245.   // OutputIterator, thereby falling into the category of 'mutable iterators'
  246.   // [iterator.requirements.general] clause 4. The compiler reveals this
  247.   // property only at the point of *actually dereferencing* the iterator!
  248.   template <typename U>
  249.   static decltype(*(std::declval<U>())) test(std::input_iterator_tag);
  250.   template <typename U> static char& test(std::output_iterator_tag);
  251.   template <typename U> static const char& test(...);
  252.  
  253.   using type = decltype(test<It>(typename iterator_category<It>::type{}));
  254.  
  255.  public:
  256.   static const bool value = !std::is_const<remove_reference_t<type>>::value;
  257. };
  258.  
  259. // A workaround for std::string not having mutable data() until C++17.
  260. template <typename Char> inline Char* get_data(std::basic_string<Char>& s) {
  261.   return &s[0];
  262. }
  263. template <typename Container>
  264. inline typename Container::value_type* get_data(Container& c) {
  265.   return c.data();
  266. }
  267.  
  268. #ifdef _SECURE_SCL
  269. // Make a checked iterator to avoid MSVC warnings.
  270. template <typename T> using checked_ptr = stdext::checked_array_iterator<T*>;
  271. template <typename T> checked_ptr<T> make_checked(T* p, std::size_t size) {
  272.   return {p, size};
  273. }
  274. #else
  275. template <typename T> using checked_ptr = T*;
  276. template <typename T> inline T* make_checked(T* p, std::size_t) { return p; }
  277. #endif
  278.  
  279. template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)>
  280. inline checked_ptr<typename Container::value_type> reserve(
  281.     std::back_insert_iterator<Container>& it, std::size_t n) {
  282.   Container& c = get_container(it);
  283.   std::size_t size = c.size();
  284.   c.resize(size + n);
  285.   return make_checked(get_data(c) + size, n);
  286. }
  287.  
  288. template <typename Iterator>
  289. inline Iterator& reserve(Iterator& it, std::size_t) {
  290.   return it;
  291. }
  292.  
  293. // An output iterator that counts the number of objects written to it and
  294. // discards them.
  295. template <typename T> class counting_iterator {
  296.  private:
  297.   std::size_t count_;
  298.   mutable T blackhole_;
  299.  
  300.  public:
  301.   using iterator_category = std::output_iterator_tag;
  302.   using value_type = T;
  303.   using difference_type = std::ptrdiff_t;
  304.   using pointer = T*;
  305.   using reference = T&;
  306.   using _Unchecked_type = counting_iterator;  // Mark iterator as checked.
  307.  
  308.   counting_iterator() : count_(0) {}
  309.  
  310.   std::size_t count() const { return count_; }
  311.  
  312.   counting_iterator& operator++() {
  313.     ++count_;
  314.     return *this;
  315.   }
  316.  
  317.   counting_iterator operator++(int) {
  318.     auto it = *this;
  319.     ++*this;
  320.     return it;
  321.   }
  322.  
  323.   T& operator*() const { return blackhole_; }
  324. };
  325.  
  326. template <typename OutputIt> class truncating_iterator_base {
  327.  protected:
  328.   OutputIt out_;
  329.   std::size_t limit_;
  330.   std::size_t count_;
  331.  
  332.   truncating_iterator_base(OutputIt out, std::size_t limit)
  333.       : out_(out), limit_(limit), count_(0) {}
  334.  
  335.  public:
  336.   using iterator_category = std::output_iterator_tag;
  337.   using difference_type = void;
  338.   using pointer = void;
  339.   using reference = void;
  340.   using _Unchecked_type =
  341.       truncating_iterator_base;  // Mark iterator as checked.
  342.  
  343.   OutputIt base() const { return out_; }
  344.   std::size_t count() const { return count_; }
  345. };
  346.  
  347. // An output iterator that truncates the output and counts the number of objects
  348. // written to it.
  349. template <typename OutputIt,
  350.           typename Enable = typename std::is_void<
  351.               typename std::iterator_traits<OutputIt>::value_type>::type>
  352. class truncating_iterator;
  353.  
  354. template <typename OutputIt>
  355. class truncating_iterator<OutputIt, std::false_type>
  356.     : public truncating_iterator_base<OutputIt> {
  357.   using traits = std::iterator_traits<OutputIt>;
  358.  
  359.   mutable typename traits::value_type blackhole_;
  360.  
  361.  public:
  362.   using value_type = typename traits::value_type;
  363.  
  364.   truncating_iterator(OutputIt out, std::size_t limit)
  365.       : truncating_iterator_base<OutputIt>(out, limit) {}
  366.  
  367.   truncating_iterator& operator++() {
  368.     if (this->count_++ < this->limit_) ++this->out_;
  369.     return *this;
  370.   }
  371.  
  372.   truncating_iterator operator++(int) {
  373.     auto it = *this;
  374.     ++*this;
  375.     return it;
  376.   }
  377.  
  378.   value_type& operator*() const {
  379.     return this->count_ < this->limit_ ? *this->out_ : blackhole_;
  380.   }
  381. };
  382.  
  383. template <typename OutputIt>
  384. class truncating_iterator<OutputIt, std::true_type>
  385.     : public truncating_iterator_base<OutputIt> {
  386.  public:
  387.   using value_type = typename OutputIt::container_type::value_type;
  388.  
  389.   truncating_iterator(OutputIt out, std::size_t limit)
  390.       : truncating_iterator_base<OutputIt>(out, limit) {}
  391.  
  392.   truncating_iterator& operator=(value_type val) {
  393.     if (this->count_++ < this->limit_) this->out_ = val;
  394.     return *this;
  395.   }
  396.  
  397.   truncating_iterator& operator++() { return *this; }
  398.   truncating_iterator& operator++(int) { return *this; }
  399.   truncating_iterator& operator*() { return *this; }
  400. };
  401.  
  402. // A range with the specified output iterator and value type.
  403. template <typename OutputIt, typename T = typename OutputIt::value_type>
  404. class output_range {
  405.  private:
  406.   OutputIt it_;
  407.  
  408.  public:
  409.   using value_type = T;
  410.   using iterator = OutputIt;
  411.   struct sentinel {};
  412.  
  413.   explicit output_range(OutputIt it) : it_(it) {}
  414.   OutputIt begin() const { return it_; }
  415.   sentinel end() const { return {}; }  // Sentinel is not used yet.
  416. };
  417.  
  418. template <typename Char>
  419. inline size_t count_code_points(basic_string_view<Char> s) {
  420.   return s.size();
  421. }
  422.  
  423. // Counts the number of code points in a UTF-8 string.
  424. inline size_t count_code_points(basic_string_view<char8_t> s) {
  425.   const char8_t* data = s.data();
  426.   size_t num_code_points = 0;
  427.   for (size_t i = 0, size = s.size(); i != size; ++i) {
  428.     if ((data[i] & 0xc0) != 0x80) ++num_code_points;
  429.   }
  430.   return num_code_points;
  431. }
  432.  
  433. inline char8_t to_char8_t(char c) { return static_cast<char8_t>(c); }
  434.  
  435. template <typename InputIt, typename OutChar>
  436. using needs_conversion = bool_constant<
  437.     std::is_same<typename std::iterator_traits<InputIt>::value_type,
  438.                  char>::value &&
  439.     std::is_same<OutChar, char8_t>::value>;
  440.  
  441. template <typename OutChar, typename InputIt, typename OutputIt,
  442.           FMT_ENABLE_IF(!needs_conversion<InputIt, OutChar>::value)>
  443. OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) {
  444.   return std::copy(begin, end, it);
  445. }
  446.  
  447. template <typename OutChar, typename InputIt, typename OutputIt,
  448.           FMT_ENABLE_IF(needs_conversion<InputIt, OutChar>::value)>
  449. OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) {
  450.   return std::transform(begin, end, it, to_char8_t);
  451. }
  452.  
  453. #ifndef FMT_USE_GRISU
  454. #  define FMT_USE_GRISU 1
  455. #endif
  456.  
  457. template <typename T> constexpr bool use_grisu() {
  458.   return FMT_USE_GRISU && std::numeric_limits<double>::is_iec559 &&
  459.          sizeof(T) <= sizeof(double);
  460. }
  461.  
  462. template <typename T>
  463. template <typename U>
  464. void buffer<T>::append(const U* begin, const U* end) {
  465.   std::size_t new_size = size_ + to_unsigned(end - begin);
  466.   reserve(new_size);
  467.   std::uninitialized_copy(begin, end, make_checked(ptr_, capacity_) + size_);
  468.   size_ = new_size;
  469. }
  470. }  // namespace internal
  471.  
  472. // A range with an iterator appending to a buffer.
  473. template <typename T>
  474. class buffer_range : public internal::output_range<
  475.                          std::back_insert_iterator<internal::buffer<T>>, T> {
  476.  public:
  477.   using iterator = std::back_insert_iterator<internal::buffer<T>>;
  478.   using internal::output_range<iterator, T>::output_range;
  479.   buffer_range(internal::buffer<T>& buf)
  480.       : internal::output_range<iterator, T>(std::back_inserter(buf)) {}
  481. };
  482.  
  483. // A UTF-8 string view.
  484. class u8string_view : public basic_string_view<char8_t> {
  485.  public:
  486.   u8string_view(const char* s)
  487.       : basic_string_view<char8_t>(reinterpret_cast<const char8_t*>(s)) {}
  488.   u8string_view(const char* s, size_t count) FMT_NOEXCEPT
  489.       : basic_string_view<char8_t>(reinterpret_cast<const char8_t*>(s), count) {
  490.   }
  491. };
  492.  
  493. #if FMT_USE_USER_DEFINED_LITERALS
  494. inline namespace literals {
  495. inline u8string_view operator"" _u(const char* s, std::size_t n) {
  496.   return {s, n};
  497. }
  498. }  // namespace literals
  499. #endif
  500.  
  501. // The number of characters to store in the basic_memory_buffer object itself
  502. // to avoid dynamic memory allocation.
  503. enum { inline_buffer_size = 500 };
  504.  
  505. /**
  506.   \rst
  507.   A dynamically growing memory buffer for trivially copyable/constructible types
  508.   with the first ``SIZE`` elements stored in the object itself.
  509.  
  510.   You can use one of the following type aliases for common character types:
  511.  
  512.   +----------------+------------------------------+
  513.   | Type           | Definition                   |
  514.   +================+==============================+
  515.   | memory_buffer  | basic_memory_buffer<char>    |
  516.   +----------------+------------------------------+
  517.   | wmemory_buffer | basic_memory_buffer<wchar_t> |
  518.   +----------------+------------------------------+
  519.  
  520.   **Example**::
  521.  
  522.      fmt::memory_buffer out;
  523.      format_to(out, "The answer is {}.", 42);
  524.  
  525.   This will append the following output to the ``out`` object:
  526.  
  527.   .. code-block:: none
  528.  
  529.      The answer is 42.
  530.  
  531.   The output can be converted to an ``std::string`` with ``to_string(out)``.
  532.   \endrst
  533.  */
  534. template <typename T, std::size_t SIZE = inline_buffer_size,
  535.           typename Allocator = std::allocator<T>>
  536. class basic_memory_buffer : private Allocator, public internal::buffer<T> {
  537.  private:
  538.   T store_[SIZE];
  539.  
  540.   // Deallocate memory allocated by the buffer.
  541.   void deallocate() {
  542.     T* data = this->data();
  543.     if (data != store_) Allocator::deallocate(data, this->capacity());
  544.   }
  545.  
  546.  protected:
  547.   void grow(std::size_t size) FMT_OVERRIDE;
  548.  
  549.  public:
  550.   using value_type = T;
  551.   using const_reference = const T&;
  552.  
  553.   explicit basic_memory_buffer(const Allocator& alloc = Allocator())
  554.       : Allocator(alloc) {
  555.     this->set(store_, SIZE);
  556.   }
  557.   ~basic_memory_buffer() { deallocate(); }
  558.  
  559.  private:
  560.   // Move data from other to this buffer.
  561.   void move(basic_memory_buffer& other) {
  562.     Allocator &this_alloc = *this, &other_alloc = other;
  563.     this_alloc = std::move(other_alloc);
  564.     T* data = other.data();
  565.     std::size_t size = other.size(), capacity = other.capacity();
  566.     if (data == other.store_) {
  567.       this->set(store_, capacity);
  568.       std::uninitialized_copy(other.store_, other.store_ + size,
  569.                               internal::make_checked(store_, capacity));
  570.     } else {
  571.       this->set(data, capacity);
  572.       // Set pointer to the inline array so that delete is not called
  573.       // when deallocating.
  574.       other.set(other.store_, 0);
  575.     }
  576.     this->resize(size);
  577.   }
  578.  
  579.  public:
  580.   /**
  581.     \rst
  582.     Constructs a :class:`fmt::basic_memory_buffer` object moving the content
  583.     of the other object to it.
  584.     \endrst
  585.    */
  586.   basic_memory_buffer(basic_memory_buffer&& other) { move(other); }
  587.  
  588.   /**
  589.     \rst
  590.     Moves the content of the other ``basic_memory_buffer`` object to this one.
  591.     \endrst
  592.    */
  593.   basic_memory_buffer& operator=(basic_memory_buffer&& other) {
  594.     assert(this != &other);
  595.     deallocate();
  596.     move(other);
  597.     return *this;
  598.   }
  599.  
  600.   // Returns a copy of the allocator associated with this buffer.
  601.   Allocator get_allocator() const { return *this; }
  602. };
  603.  
  604. template <typename T, std::size_t SIZE, typename Allocator>
  605. void basic_memory_buffer<T, SIZE, Allocator>::grow(std::size_t size) {
  606. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  607.   if (size > 1000) throw std::runtime_error("fuzz mode - won't grow that much");
  608. #endif
  609.   std::size_t old_capacity = this->capacity();
  610.   std::size_t new_capacity = old_capacity + old_capacity / 2;
  611.   if (size > new_capacity) new_capacity = size;
  612.   T* old_data = this->data();
  613.   T* new_data = std::allocator_traits<Allocator>::allocate(*this, new_capacity);
  614.   // The following code doesn't throw, so the raw pointer above doesn't leak.
  615.   std::uninitialized_copy(old_data, old_data + this->size(),
  616.                           internal::make_checked(new_data, new_capacity));
  617.   this->set(new_data, new_capacity);
  618.   // deallocate must not throw according to the standard, but even if it does,
  619.   // the buffer already uses the new storage and will deallocate it in
  620.   // destructor.
  621.   if (old_data != store_) Allocator::deallocate(old_data, old_capacity);
  622. }
  623.  
  624. using memory_buffer = basic_memory_buffer<char>;
  625. using wmemory_buffer = basic_memory_buffer<wchar_t>;
  626.  
  627. /** A formatting error such as invalid format string. */
  628. class FMT_API format_error : public std::runtime_error {
  629.  public:
  630.   explicit format_error(const char* message) : std::runtime_error(message) {}
  631.   explicit format_error(const std::string& message)
  632.       : std::runtime_error(message) {}
  633.   ~format_error() FMT_NOEXCEPT;
  634. };
  635.  
  636. namespace internal {
  637.  
  638. // Returns true if value is negative, false otherwise.
  639. // Same as `value < 0` but doesn't produce warnings if T is an unsigned type.
  640. template <typename T, FMT_ENABLE_IF(std::numeric_limits<T>::is_signed)>
  641. FMT_CONSTEXPR bool is_negative(T value) {
  642.   return value < 0;
  643. }
  644. template <typename T, FMT_ENABLE_IF(!std::numeric_limits<T>::is_signed)>
  645. FMT_CONSTEXPR bool is_negative(T) {
  646.   return false;
  647. }
  648.  
  649. // Smallest of uint32_t, uint64_t, uint128_t that is large enough to
  650. // represent all values of T.
  651. template <typename T>
  652. using uint32_or_64_or_128_t = conditional_t<
  653.     std::numeric_limits<T>::digits <= 32, uint32_t,
  654.     conditional_t<std::numeric_limits<T>::digits <= 64, uint64_t, uint128_t>>;
  655.  
  656. // Static data is placed in this class template for the header-only config.
  657. template <typename T = void> struct FMT_EXTERN_TEMPLATE_API basic_data {
  658.   static const uint64_t powers_of_10_64[];
  659.   static const uint32_t zero_or_powers_of_10_32[];
  660.   static const uint64_t zero_or_powers_of_10_64[];
  661.   static const uint64_t pow10_significands[];
  662.   static const int16_t pow10_exponents[];
  663.   static const char digits[];
  664.   static const char hex_digits[];
  665.   static const char foreground_color[];
  666.   static const char background_color[];
  667.   static const char reset_color[5];
  668.   static const wchar_t wreset_color[5];
  669. };
  670.  
  671. FMT_EXTERN template struct basic_data<void>;
  672.  
  673. // This is a struct rather than an alias to avoid shadowing warnings in gcc.
  674. struct data : basic_data<> {};
  675.  
  676. #ifdef FMT_BUILTIN_CLZLL
  677. // Returns the number of decimal digits in n. Leading zeros are not counted
  678. // except for n == 0 in which case count_digits returns 1.
  679. inline int count_digits(uint64_t n) {
  680.   // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
  681.   // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits.
  682.   int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12;
  683.   return t - (n < data::zero_or_powers_of_10_64[t]) + 1;
  684. }
  685. #else
  686. // Fallback version of count_digits used when __builtin_clz is not available.
  687. inline int count_digits(uint64_t n) {
  688.   int count = 1;
  689.   for (;;) {
  690.     // Integer division is slow so do it for a group of four digits instead
  691.     // of for every digit. The idea comes from the talk by Alexandrescu
  692.     // "Three Optimization Tips for C++". See speed-test for a comparison.
  693.     if (n < 10) return count;
  694.     if (n < 100) return count + 1;
  695.     if (n < 1000) return count + 2;
  696.     if (n < 10000) return count + 3;
  697.     n /= 10000u;
  698.     count += 4;
  699.   }
  700. }
  701. #endif
  702.  
  703. #if FMT_USE_INT128
  704. inline int count_digits(uint128_t n) {
  705.   int count = 1;
  706.   for (;;) {
  707.     // Integer division is slow so do it for a group of four digits instead
  708.     // of for every digit. The idea comes from the talk by Alexandrescu
  709.     // "Three Optimization Tips for C++". See speed-test for a comparison.
  710.     if (n < 10) return count;
  711.     if (n < 100) return count + 1;
  712.     if (n < 1000) return count + 2;
  713.     if (n < 10000) return count + 3;
  714.     n /= 10000u;
  715.     count += 4;
  716.   }
  717. }
  718. #endif
  719.  
  720. // Counts the number of digits in n. BITS = log2(radix).
  721. template <unsigned BITS, typename UInt> inline int count_digits(UInt n) {
  722.   int num_digits = 0;
  723.   do {
  724.     ++num_digits;
  725.   } while ((n >>= BITS) != 0);
  726.   return num_digits;
  727. }
  728.  
  729. template <> int count_digits<4>(internal::fallback_uintptr n);
  730.  
  731. #if FMT_HAS_CPP_ATTRIBUTE(always_inline)
  732. #  define FMT_ALWAYS_INLINE __attribute__((always_inline))
  733. #else
  734. #  define FMT_ALWAYS_INLINE
  735. #endif
  736.  
  737. template <typename Handler>
  738. inline char* lg(uint32_t n, Handler h) FMT_ALWAYS_INLINE;
  739.  
  740. // Computes g = floor(log10(n)) and calls h.on<g>(n);
  741. template <typename Handler> inline char* lg(uint32_t n, Handler h) {
  742.   return n < 100 ? n < 10 ? h.template on<0>(n) : h.template on<1>(n)
  743.                  : n < 1000000
  744.                        ? n < 10000 ? n < 1000 ? h.template on<2>(n)
  745.                                               : h.template on<3>(n)
  746.                                    : n < 100000 ? h.template on<4>(n)
  747.                                                 : h.template on<5>(n)
  748.                        : n < 100000000 ? n < 10000000 ? h.template on<6>(n)
  749.                                                       : h.template on<7>(n)
  750.                                        : n < 1000000000 ? h.template on<8>(n)
  751.                                                         : h.template on<9>(n);
  752. }
  753.  
  754. // An lg handler that formats a decimal number.
  755. // Usage: lg(n, decimal_formatter(buffer));
  756. class decimal_formatter {
  757.  private:
  758.   char* buffer_;
  759.  
  760.   void write_pair(unsigned N, uint32_t index) {
  761.     std::memcpy(buffer_ + N, data::digits + index * 2, 2);
  762.   }
  763.  
  764.  public:
  765.   explicit decimal_formatter(char* buf) : buffer_(buf) {}
  766.  
  767.   template <unsigned N> char* on(uint32_t u) {
  768.     if (N == 0) {
  769.       *buffer_ = static_cast<char>(u) + '0';
  770.     } else if (N == 1) {
  771.       write_pair(0, u);
  772.     } else {
  773.       // The idea of using 4.32 fixed-point numbers is based on
  774.       // https://github.com/jeaiii/itoa
  775.       unsigned n = N - 1;
  776.       unsigned a = n / 5 * n * 53 / 16;
  777.       uint64_t t =
  778.           ((1ULL << (32 + a)) / data::zero_or_powers_of_10_32[n] + 1 - n / 9);
  779.       t = ((t * u) >> a) + n / 5 * 4;
  780.       write_pair(0, t >> 32);
  781.       for (unsigned i = 2; i < N; i += 2) {
  782.         t = 100ULL * static_cast<uint32_t>(t);
  783.         write_pair(i, t >> 32);
  784.       }
  785.       if (N % 2 == 0) {
  786.         buffer_[N] =
  787.             static_cast<char>((10ULL * static_cast<uint32_t>(t)) >> 32) + '0';
  788.       }
  789.     }
  790.     return buffer_ += N + 1;
  791.   }
  792. };
  793.  
  794. #ifdef FMT_BUILTIN_CLZ
  795. // Optional version of count_digits for better performance on 32-bit platforms.
  796. inline int count_digits(uint32_t n) {
  797.   int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12;
  798.   return t - (n < data::zero_or_powers_of_10_32[t]) + 1;
  799. }
  800. #endif
  801.  
  802. template <typename Char> FMT_API Char thousands_sep_impl(locale_ref loc);
  803. template <typename Char> inline Char thousands_sep(locale_ref loc) {
  804.   return Char(thousands_sep_impl<char>(loc));
  805. }
  806. template <> inline wchar_t thousands_sep(locale_ref loc) {
  807.   return thousands_sep_impl<wchar_t>(loc);
  808. }
  809.  
  810. template <typename Char> FMT_API Char decimal_point_impl(locale_ref loc);
  811. template <typename Char> inline Char decimal_point(locale_ref loc) {
  812.   return Char(decimal_point_impl<char>(loc));
  813. }
  814. template <> inline wchar_t decimal_point(locale_ref loc) {
  815.   return decimal_point_impl<wchar_t>(loc);
  816. }
  817.  
  818. // Formats a decimal unsigned integer value writing into buffer.
  819. // add_thousands_sep is called after writing each char to add a thousands
  820. // separator if necessary.
  821. template <typename UInt, typename Char, typename F>
  822. inline Char* format_decimal(Char* buffer, UInt value, int num_digits,
  823.                             F add_thousands_sep) {
  824.   FMT_ASSERT(num_digits >= 0, "invalid digit count");
  825.   buffer += num_digits;
  826.   Char* end = buffer;
  827.   while (value >= 100) {
  828.     // Integer division is slow so do it for a group of two digits instead
  829.     // of for every digit. The idea comes from the talk by Alexandrescu
  830.     // "Three Optimization Tips for C++". See speed-test for a comparison.
  831.     unsigned index = static_cast<unsigned>((value % 100) * 2);
  832.     value /= 100;
  833.     *--buffer = static_cast<Char>(data::digits[index + 1]);
  834.     add_thousands_sep(buffer);
  835.     *--buffer = static_cast<Char>(data::digits[index]);
  836.     add_thousands_sep(buffer);
  837.   }
  838.   if (value < 10) {
  839.     *--buffer = static_cast<Char>('0' + value);
  840.     return end;
  841.   }
  842.   unsigned index = static_cast<unsigned>(value * 2);
  843.   *--buffer = static_cast<Char>(data::digits[index + 1]);
  844.   add_thousands_sep(buffer);
  845.   *--buffer = static_cast<Char>(data::digits[index]);
  846.   return end;
  847. }
  848.  
  849. template <typename Int> constexpr int digits10() noexcept {
  850.   return std::numeric_limits<Int>::digits10;
  851. }
  852. template <> constexpr int digits10<int128_t>() noexcept { return 38; }
  853. template <> constexpr int digits10<uint128_t>() noexcept { return 38; }
  854.  
  855. template <typename Char, typename UInt, typename Iterator, typename F>
  856. inline Iterator format_decimal(Iterator out, UInt value, int num_digits,
  857.                                F add_thousands_sep) {
  858.   FMT_ASSERT(num_digits >= 0, "invalid digit count");
  859.   // Buffer should be large enough to hold all digits (<= digits10 + 1).
  860.   enum { max_size = digits10<UInt>() + 1 };
  861.   Char buffer[max_size + max_size / 3];
  862.   auto end = format_decimal(buffer, value, num_digits, add_thousands_sep);
  863.   return internal::copy_str<Char>(buffer, end, out);
  864. }
  865.  
  866. template <typename Char, typename It, typename UInt>
  867. inline It format_decimal(It out, UInt value, int num_digits) {
  868.   return format_decimal<Char>(out, value, num_digits, [](Char*) {});
  869. }
  870.  
  871. template <unsigned BASE_BITS, typename Char, typename UInt>
  872. inline Char* format_uint(Char* buffer, UInt value, int num_digits,
  873.                          bool upper = false) {
  874.   buffer += num_digits;
  875.   Char* end = buffer;
  876.   do {
  877.     const char* digits = upper ? "0123456789ABCDEF" : data::hex_digits;
  878.     unsigned digit = (value & ((1 << BASE_BITS) - 1));
  879.     *--buffer = static_cast<Char>(BASE_BITS < 4 ? static_cast<char>('0' + digit)
  880.                                                 : digits[digit]);
  881.   } while ((value >>= BASE_BITS) != 0);
  882.   return end;
  883. }
  884.  
  885. template <unsigned BASE_BITS, typename Char>
  886. Char* format_uint(Char* buffer, internal::fallback_uintptr n, int num_digits,
  887.                   bool = false) {
  888.   auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
  889.   int start = (num_digits + char_digits - 1) / char_digits - 1;
  890.   if (int start_digits = num_digits % char_digits) {
  891.     unsigned value = n.value[start--];
  892.     buffer = format_uint<BASE_BITS>(buffer, value, start_digits);
  893.   }
  894.   for (; start >= 0; --start) {
  895.     unsigned value = n.value[start];
  896.     buffer += char_digits;
  897.     auto p = buffer;
  898.     for (int i = 0; i < char_digits; ++i) {
  899.       unsigned digit = (value & ((1 << BASE_BITS) - 1));
  900.       *--p = static_cast<Char>(data::hex_digits[digit]);
  901.       value >>= BASE_BITS;
  902.     }
  903.   }
  904.   return buffer;
  905. }
  906.  
  907. template <unsigned BASE_BITS, typename Char, typename It, typename UInt>
  908. inline It format_uint(It out, UInt value, int num_digits, bool upper = false) {
  909.   // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1).
  910.   char buffer[std::numeric_limits<UInt>::digits / BASE_BITS + 1];
  911.   format_uint<BASE_BITS>(buffer, value, num_digits, upper);
  912.   return internal::copy_str<Char>(buffer, buffer + num_digits, out);
  913. }
  914.  
  915. #ifndef _WIN32
  916. #  define FMT_USE_WINDOWS_H 0
  917. #elif !defined(FMT_USE_WINDOWS_H)
  918. #  define FMT_USE_WINDOWS_H 1
  919. #endif
  920.  
  921. // Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h.
  922. // All the functionality that relies on it will be disabled too.
  923. #if FMT_USE_WINDOWS_H
  924. // A converter from UTF-8 to UTF-16.
  925. // It is only provided for Windows since other systems support UTF-8 natively.
  926. class utf8_to_utf16 {
  927.  private:
  928.   wmemory_buffer buffer_;
  929.  
  930.  public:
  931.   FMT_API explicit utf8_to_utf16(string_view s);
  932.   operator wstring_view() const { return wstring_view(&buffer_[0], size()); }
  933.   size_t size() const { return buffer_.size() - 1; }
  934.   const wchar_t* c_str() const { return &buffer_[0]; }
  935.   std::wstring str() const { return std::wstring(&buffer_[0], size()); }
  936. };
  937.  
  938. // A converter from UTF-16 to UTF-8.
  939. // It is only provided for Windows since other systems support UTF-8 natively.
  940. class utf16_to_utf8 {
  941.  private:
  942.   memory_buffer buffer_;
  943.  
  944.  public:
  945.   utf16_to_utf8() {}
  946.   FMT_API explicit utf16_to_utf8(wstring_view s);
  947.   operator string_view() const { return string_view(&buffer_[0], size()); }
  948.   size_t size() const { return buffer_.size() - 1; }
  949.   const char* c_str() const { return &buffer_[0]; }
  950.   std::string str() const { return std::string(&buffer_[0], size()); }
  951.  
  952.   // Performs conversion returning a system error code instead of
  953.   // throwing exception on conversion error. This method may still throw
  954.   // in case of memory allocation error.
  955.   FMT_API int convert(wstring_view s);
  956. };
  957.  
  958. FMT_API void format_windows_error(fmt::internal::buffer<char>& out,
  959.                                   int error_code,
  960.                                   fmt::string_view message) FMT_NOEXCEPT;
  961. #endif
  962.  
  963. template <typename T = void> struct null {};
  964.  
  965. // Workaround an array initialization issue in gcc 4.8.
  966. template <typename Char> struct fill_t {
  967.  private:
  968.   Char data_[6];
  969.  
  970.  public:
  971.   FMT_CONSTEXPR Char& operator[](size_t index) { return data_[index]; }
  972.   FMT_CONSTEXPR const Char& operator[](size_t index) const {
  973.     return data_[index];
  974.   }
  975.  
  976.   static FMT_CONSTEXPR fill_t<Char> make() {
  977.     auto fill = fill_t<Char>();
  978.     fill[0] = Char(' ');
  979.     return fill;
  980.   }
  981. };
  982. }  // namespace internal
  983.  
  984. // We cannot use enum classes as bit fields because of a gcc bug
  985. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414.
  986. namespace align {
  987. enum type { none, left, right, center, numeric };
  988. }
  989. using align_t = align::type;
  990.  
  991. namespace sign {
  992. enum type { none, minus, plus, space };
  993. }
  994. using sign_t = sign::type;
  995.  
  996. // Format specifiers for built-in and string types.
  997. template <typename Char> struct basic_format_specs {
  998.   int width;
  999.   int precision;
  1000.   char type;
  1001.   align_t align : 4;
  1002.   sign_t sign : 3;
  1003.   bool alt : 1;  // Alternate form ('#').
  1004.   internal::fill_t<Char> fill;
  1005.  
  1006.   constexpr basic_format_specs()
  1007.       : width(0),
  1008.         precision(-1),
  1009.         type(0),
  1010.         align(align::none),
  1011.         sign(sign::none),
  1012.         alt(false),
  1013.         fill(internal::fill_t<Char>::make()) {}
  1014. };
  1015.  
  1016. using format_specs = basic_format_specs<char>;
  1017.  
  1018. namespace internal {
  1019.  
  1020. // Writes the exponent exp in the form "[+-]d{2,3}" to buffer.
  1021. template <typename Char, typename It> It write_exponent(int exp, It it) {
  1022.   FMT_ASSERT(-1000 < exp && exp < 1000, "exponent out of range");
  1023.   if (exp < 0) {
  1024.     *it++ = static_cast<Char>('-');
  1025.     exp = -exp;
  1026.   } else {
  1027.     *it++ = static_cast<Char>('+');
  1028.   }
  1029.   if (exp >= 100) {
  1030.     *it++ = static_cast<Char>(static_cast<char>('0' + exp / 100));
  1031.     exp %= 100;
  1032.   }
  1033.   const char* d = data::digits + exp * 2;
  1034.   *it++ = static_cast<Char>(d[0]);
  1035.   *it++ = static_cast<Char>(d[1]);
  1036.   return it;
  1037. }
  1038.  
  1039. struct gen_digits_params {
  1040.   int num_digits;
  1041.   bool fixed;
  1042.   bool upper;
  1043.   bool trailing_zeros;
  1044. };
  1045.  
  1046. // The number is given as v = digits * pow(10, exp).
  1047. template <typename Char, typename It>
  1048. It grisu_prettify(const char* digits, int size, int exp, It it,
  1049.                   gen_digits_params params, Char decimal_point) {
  1050.   // pow(10, full_exp - 1) <= v <= pow(10, full_exp).
  1051.   int full_exp = size + exp;
  1052.   if (!params.fixed) {
  1053.     // Insert a decimal point after the first digit and add an exponent.
  1054.     *it++ = static_cast<Char>(*digits);
  1055.     if (size > 1) *it++ = decimal_point;
  1056.     exp += size - 1;
  1057.     it = copy_str<Char>(digits + 1, digits + size, it);
  1058.     if (size < params.num_digits)
  1059.       it = std::fill_n(it, params.num_digits - size, static_cast<Char>('0'));
  1060.     *it++ = static_cast<Char>(params.upper ? 'E' : 'e');
  1061.     return write_exponent<Char>(exp, it);
  1062.   }
  1063.   if (size <= full_exp) {
  1064.     // 1234e7 -> 12340000000[.0+]
  1065.     it = copy_str<Char>(digits, digits + size, it);
  1066.     it = std::fill_n(it, full_exp - size, static_cast<Char>('0'));
  1067.     int num_zeros = (std::max)(params.num_digits - full_exp, 1);
  1068.     if (params.trailing_zeros) {
  1069.       *it++ = decimal_point;
  1070. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  1071.       if (num_zeros > 1000)
  1072.         throw std::runtime_error("fuzz mode - avoiding excessive cpu use");
  1073. #endif
  1074.       it = std::fill_n(it, num_zeros, static_cast<Char>('0'));
  1075.     }
  1076.   } else if (full_exp > 0) {
  1077.     // 1234e-2 -> 12.34[0+]
  1078.     it = copy_str<Char>(digits, digits + full_exp, it);
  1079.     if (!params.trailing_zeros) {
  1080.       // Remove trailing zeros.
  1081.       while (size > full_exp && digits[size - 1] == '0') --size;
  1082.       if (size != full_exp) *it++ = decimal_point;
  1083.       return copy_str<Char>(digits + full_exp, digits + size, it);
  1084.     }
  1085.     *it++ = decimal_point;
  1086.     it = copy_str<Char>(digits + full_exp, digits + size, it);
  1087.     if (params.num_digits > size) {
  1088.       // Add trailing zeros.
  1089.       int num_zeros = params.num_digits - size;
  1090.       it = std::fill_n(it, num_zeros, static_cast<Char>('0'));
  1091.     }
  1092.   } else {
  1093.     // 1234e-6 -> 0.001234
  1094.     *it++ = static_cast<Char>('0');
  1095.     int num_zeros = -full_exp;
  1096.     if (params.num_digits >= 0 && params.num_digits < num_zeros)
  1097.       num_zeros = params.num_digits;
  1098.     if (!params.trailing_zeros)
  1099.       while (size > 0 && digits[size - 1] == '0') --size;
  1100.     if (num_zeros != 0 || size != 0) {
  1101.       *it++ = decimal_point;
  1102.       it = std::fill_n(it, num_zeros, static_cast<Char>('0'));
  1103.       it = copy_str<Char>(digits, digits + size, it);
  1104.     }
  1105.   }
  1106.   return it;
  1107. }
  1108.  
  1109. namespace grisu_options {
  1110. enum { fixed = 1, grisu3 = 2 };
  1111. }
  1112.  
  1113. // Formats value using the Grisu algorithm:
  1114. // https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf
  1115. template <typename Double, FMT_ENABLE_IF(sizeof(Double) == sizeof(uint64_t))>
  1116. FMT_API bool grisu_format(Double, buffer<char>&, int, unsigned, int&);
  1117. template <typename Double, FMT_ENABLE_IF(sizeof(Double) != sizeof(uint64_t))>
  1118. inline bool grisu_format(Double, buffer<char>&, int, unsigned, int&) {
  1119.   return false;
  1120. }
  1121.  
  1122. struct sprintf_specs {
  1123.   int precision;
  1124.   char type;
  1125.   bool alt : 1;
  1126.  
  1127.   template <typename Char>
  1128.   constexpr sprintf_specs(basic_format_specs<Char> specs)
  1129.       : precision(specs.precision), type(specs.type), alt(specs.alt) {}
  1130.  
  1131.   constexpr bool has_precision() const { return precision >= 0; }
  1132. };
  1133.  
  1134. template <typename Double>
  1135. char* sprintf_format(Double, internal::buffer<char>&, sprintf_specs);
  1136.  
  1137. template <typename Handler>
  1138. FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler&& handler) {
  1139.   switch (spec) {
  1140.   case 0:
  1141.   case 'd':
  1142.     handler.on_dec();
  1143.     break;
  1144.   case 'x':
  1145.   case 'X':
  1146.     handler.on_hex();
  1147.     break;
  1148.   case 'b':
  1149.   case 'B':
  1150.     handler.on_bin();
  1151.     break;
  1152.   case 'o':
  1153.     handler.on_oct();
  1154.     break;
  1155.   case 'n':
  1156.     handler.on_num();
  1157.     break;
  1158.   default:
  1159.     handler.on_error();
  1160.   }
  1161. }
  1162.  
  1163. template <typename Handler>
  1164. FMT_CONSTEXPR void handle_float_type_spec(char spec, Handler&& handler) {
  1165.   switch (spec) {
  1166.   case 0:
  1167.   case 'g':
  1168.   case 'G':
  1169.     handler.on_general();
  1170.     break;
  1171.   case 'e':
  1172.   case 'E':
  1173.     handler.on_exp();
  1174.     break;
  1175.   case 'f':
  1176.   case 'F':
  1177.     handler.on_fixed();
  1178.     break;
  1179.   case '%':
  1180.     handler.on_percent();
  1181.     break;
  1182.   case 'a':
  1183.   case 'A':
  1184.     handler.on_hex();
  1185.     break;
  1186.   case 'n':
  1187.     handler.on_num();
  1188.     break;
  1189.   default:
  1190.     handler.on_error();
  1191.     break;
  1192.   }
  1193. }
  1194.  
  1195. template <typename Char, typename Handler>
  1196. FMT_CONSTEXPR void handle_char_specs(const basic_format_specs<Char>* specs,
  1197.                                      Handler&& handler) {
  1198.   if (!specs) return handler.on_char();
  1199.   if (specs->type && specs->type != 'c') return handler.on_int();
  1200.   if (specs->align == align::numeric || specs->sign != sign::none || specs->alt)
  1201.     handler.on_error("invalid format specifier for char");
  1202.   handler.on_char();
  1203. }
  1204.  
  1205. template <typename Char, typename Handler>
  1206. FMT_CONSTEXPR void handle_cstring_type_spec(Char spec, Handler&& handler) {
  1207.   if (spec == 0 || spec == 's')
  1208.     handler.on_string();
  1209.   else if (spec == 'p')
  1210.     handler.on_pointer();
  1211.   else
  1212.     handler.on_error("invalid type specifier");
  1213. }
  1214.  
  1215. template <typename Char, typename ErrorHandler>
  1216. FMT_CONSTEXPR void check_string_type_spec(Char spec, ErrorHandler&& eh) {
  1217.   if (spec != 0 && spec != 's') eh.on_error("invalid type specifier");
  1218. }
  1219.  
  1220. template <typename Char, typename ErrorHandler>
  1221. FMT_CONSTEXPR void check_pointer_type_spec(Char spec, ErrorHandler&& eh) {
  1222.   if (spec != 0 && spec != 'p') eh.on_error("invalid type specifier");
  1223. }
  1224.  
  1225. template <typename ErrorHandler> class int_type_checker : private ErrorHandler {
  1226.  public:
  1227.   FMT_CONSTEXPR explicit int_type_checker(ErrorHandler eh) : ErrorHandler(eh) {}
  1228.  
  1229.   FMT_CONSTEXPR void on_dec() {}
  1230.   FMT_CONSTEXPR void on_hex() {}
  1231.   FMT_CONSTEXPR void on_bin() {}
  1232.   FMT_CONSTEXPR void on_oct() {}
  1233.   FMT_CONSTEXPR void on_num() {}
  1234.  
  1235.   FMT_CONSTEXPR void on_error() {
  1236.     ErrorHandler::on_error("invalid type specifier");
  1237.   }
  1238. };
  1239.  
  1240. template <typename ErrorHandler>
  1241. class float_type_checker : private ErrorHandler {
  1242.  public:
  1243.   FMT_CONSTEXPR explicit float_type_checker(ErrorHandler eh)
  1244.       : ErrorHandler(eh) {}
  1245.  
  1246.   FMT_CONSTEXPR void on_general() {}
  1247.   FMT_CONSTEXPR void on_exp() {}
  1248.   FMT_CONSTEXPR void on_fixed() {}
  1249.   FMT_CONSTEXPR void on_percent() {}
  1250.   FMT_CONSTEXPR void on_hex() {}
  1251.   FMT_CONSTEXPR void on_num() {}
  1252.  
  1253.   FMT_CONSTEXPR void on_error() {
  1254.     ErrorHandler::on_error("invalid type specifier");
  1255.   }
  1256. };
  1257.  
  1258. template <typename ErrorHandler>
  1259. class char_specs_checker : public ErrorHandler {
  1260.  private:
  1261.   char type_;
  1262.  
  1263.  public:
  1264.   FMT_CONSTEXPR char_specs_checker(char type, ErrorHandler eh)
  1265.       : ErrorHandler(eh), type_(type) {}
  1266.  
  1267.   FMT_CONSTEXPR void on_int() {
  1268.     handle_int_type_spec(type_, int_type_checker<ErrorHandler>(*this));
  1269.   }
  1270.   FMT_CONSTEXPR void on_char() {}
  1271. };
  1272.  
  1273. template <typename ErrorHandler>
  1274. class cstring_type_checker : public ErrorHandler {
  1275.  public:
  1276.   FMT_CONSTEXPR explicit cstring_type_checker(ErrorHandler eh)
  1277.       : ErrorHandler(eh) {}
  1278.  
  1279.   FMT_CONSTEXPR void on_string() {}
  1280.   FMT_CONSTEXPR void on_pointer() {}
  1281. };
  1282.  
  1283. template <typename Context>
  1284. void arg_map<Context>::init(const basic_format_args<Context>& args) {
  1285.   if (map_) return;
  1286.   map_ = new entry[internal::to_unsigned(args.max_size())];
  1287.   if (args.is_packed()) {
  1288.     for (int i = 0;; ++i) {
  1289.       internal::type arg_type = args.type(i);
  1290.       if (arg_type == internal::none_type) return;
  1291.       if (arg_type == internal::named_arg_type) push_back(args.values_[i]);
  1292.     }
  1293.   }
  1294.   for (int i = 0, n = args.max_size(); i < n; ++i) {
  1295.     auto type = args.args_[i].type_;
  1296.     if (type == internal::named_arg_type) push_back(args.args_[i].value_);
  1297.   }
  1298. }
  1299.  
  1300. // This template provides operations for formatting and writing data into a
  1301. // character range.
  1302. template <typename Range> class basic_writer {
  1303.  public:
  1304.   using char_type = typename Range::value_type;
  1305.   using iterator = typename Range::iterator;
  1306.   using format_specs = basic_format_specs<char_type>;
  1307.  
  1308.  private:
  1309.   iterator out_;  // Output iterator.
  1310.   internal::locale_ref locale_;
  1311.  
  1312.   // Attempts to reserve space for n extra characters in the output range.
  1313.   // Returns a pointer to the reserved range or a reference to out_.
  1314.   auto reserve(std::size_t n) -> decltype(internal::reserve(out_, n)) {
  1315.     return internal::reserve(out_, n);
  1316.   }
  1317.  
  1318.   template <typename F> struct padded_int_writer {
  1319.     size_t size_;
  1320.     string_view prefix;
  1321.     char_type fill;
  1322.     std::size_t padding;
  1323.     F f;
  1324.  
  1325.     size_t size() const { return size_; }
  1326.     size_t width() const { return size_; }
  1327.  
  1328.     template <typename It> void operator()(It&& it) const {
  1329.       if (prefix.size() != 0)
  1330.         it = internal::copy_str<char_type>(prefix.begin(), prefix.end(), it);
  1331.       it = std::fill_n(it, padding, fill);
  1332.       f(it);
  1333.     }
  1334.   };
  1335.  
  1336.   // Writes an integer in the format
  1337.   //   <left-padding><prefix><numeric-padding><digits><right-padding>
  1338.   // where <digits> are written by f(it).
  1339.   template <typename F>
  1340.   void write_int(int num_digits, string_view prefix, format_specs specs, F f) {
  1341.     std::size_t size = prefix.size() + internal::to_unsigned(num_digits);
  1342.     char_type fill = specs.fill[0];
  1343.     std::size_t padding = 0;
  1344.     if (specs.align == align::numeric) {
  1345.       auto unsiged_width = internal::to_unsigned(specs.width);
  1346.       if (unsiged_width > size) {
  1347.         padding = unsiged_width - size;
  1348.         size = unsiged_width;
  1349.       }
  1350.     } else if (specs.precision > num_digits) {
  1351.       size = prefix.size() + internal::to_unsigned(specs.precision);
  1352.       padding = internal::to_unsigned(specs.precision - num_digits);
  1353.       fill = static_cast<char_type>('0');
  1354.     }
  1355.     if (specs.align == align::none) specs.align = align::right;
  1356.     write_padded(specs, padded_int_writer<F>{size, prefix, fill, padding, f});
  1357.   }
  1358.  
  1359.   // Writes a decimal integer.
  1360.   template <typename Int> void write_decimal(Int value) {
  1361.     auto abs_value = static_cast<uint32_or_64_or_128_t<Int>>(value);
  1362.     bool is_negative = internal::is_negative(value);
  1363.     if (is_negative) abs_value = 0 - abs_value;
  1364.     int num_digits = internal::count_digits(abs_value);
  1365.     auto&& it =
  1366.         reserve((is_negative ? 1 : 0) + static_cast<size_t>(num_digits));
  1367.     if (is_negative) *it++ = static_cast<char_type>('-');
  1368.     it = internal::format_decimal<char_type>(it, abs_value, num_digits);
  1369.   }
  1370.  
  1371.   // The handle_int_type_spec handler that writes an integer.
  1372.   template <typename Int, typename Specs> struct int_writer {
  1373.     using unsigned_type = uint32_or_64_or_128_t<Int>;
  1374.  
  1375.     basic_writer<Range>& writer;
  1376.     const Specs& specs;
  1377.     unsigned_type abs_value;
  1378.     char prefix[4];
  1379.     unsigned prefix_size;
  1380.  
  1381.     string_view get_prefix() const { return string_view(prefix, prefix_size); }
  1382.  
  1383.     int_writer(basic_writer<Range>& w, Int value, const Specs& s)
  1384.         : writer(w),
  1385.           specs(s),
  1386.           abs_value(static_cast<unsigned_type>(value)),
  1387.           prefix_size(0) {
  1388.       if (internal::is_negative(value)) {
  1389.         prefix[0] = '-';
  1390.         ++prefix_size;
  1391.         abs_value = 0 - abs_value;
  1392.       } else if (specs.sign != sign::none && specs.sign != sign::minus) {
  1393.         prefix[0] = specs.sign == sign::plus ? '+' : ' ';
  1394.         ++prefix_size;
  1395.       }
  1396.     }
  1397.  
  1398.     struct dec_writer {
  1399.       unsigned_type abs_value;
  1400.       int num_digits;
  1401.  
  1402.       template <typename It> void operator()(It&& it) const {
  1403.         it = internal::format_decimal<char_type>(it, abs_value, num_digits);
  1404.       }
  1405.     };
  1406.  
  1407.     void on_dec() {
  1408.       int num_digits = internal::count_digits(abs_value);
  1409.       writer.write_int(num_digits, get_prefix(), specs,
  1410.                        dec_writer{abs_value, num_digits});
  1411.     }
  1412.  
  1413.     struct hex_writer {
  1414.       int_writer& self;
  1415.       int num_digits;
  1416.  
  1417.       template <typename It> void operator()(It&& it) const {
  1418.         it = internal::format_uint<4, char_type>(it, self.abs_value, num_digits,
  1419.                                                  self.specs.type != 'x');
  1420.       }
  1421.     };
  1422.  
  1423.     void on_hex() {
  1424.       if (specs.alt) {
  1425.         prefix[prefix_size++] = '0';
  1426.         prefix[prefix_size++] = specs.type;
  1427.       }
  1428.       int num_digits = internal::count_digits<4>(abs_value);
  1429.       writer.write_int(num_digits, get_prefix(), specs,
  1430.                        hex_writer{*this, num_digits});
  1431.     }
  1432.  
  1433.     template <int BITS> struct bin_writer {
  1434.       unsigned_type abs_value;
  1435.       int num_digits;
  1436.  
  1437.       template <typename It> void operator()(It&& it) const {
  1438.         it = internal::format_uint<BITS, char_type>(it, abs_value, num_digits);
  1439.       }
  1440.     };
  1441.  
  1442.     void on_bin() {
  1443.       if (specs.alt) {
  1444.         prefix[prefix_size++] = '0';
  1445.         prefix[prefix_size++] = static_cast<char>(specs.type);
  1446.       }
  1447.       int num_digits = internal::count_digits<1>(abs_value);
  1448.       writer.write_int(num_digits, get_prefix(), specs,
  1449.                        bin_writer<1>{abs_value, num_digits});
  1450.     }
  1451.  
  1452.     void on_oct() {
  1453.       int num_digits = internal::count_digits<3>(abs_value);
  1454.       if (specs.alt && specs.precision <= num_digits && abs_value != 0) {
  1455.         // Octal prefix '0' is counted as a digit, so only add it if precision
  1456.         // is not greater than the number of digits.
  1457.         prefix[prefix_size++] = '0';
  1458.       }
  1459.       writer.write_int(num_digits, get_prefix(), specs,
  1460.                        bin_writer<3>{abs_value, num_digits});
  1461.     }
  1462.  
  1463.     enum { sep_size = 1 };
  1464.  
  1465.     struct num_writer {
  1466.       unsigned_type abs_value;
  1467.       int size;
  1468.       char_type sep;
  1469.  
  1470.       template <typename It> void operator()(It&& it) const {
  1471.         basic_string_view<char_type> s(&sep, sep_size);
  1472.         // Index of a decimal digit with the least significant digit having
  1473.         // index 0.
  1474.         unsigned digit_index = 0;
  1475.         it = internal::format_decimal<char_type>(
  1476.             it, abs_value, size, [s, &digit_index](char_type*& buffer) {
  1477.               if (++digit_index % 3 != 0) return;
  1478.               buffer -= s.size();
  1479.               std::uninitialized_copy(s.data(), s.data() + s.size(),
  1480.                                       internal::make_checked(buffer, s.size()));
  1481.             });
  1482.       }
  1483.     };
  1484.  
  1485.     void on_num() {
  1486.       char_type sep = internal::thousands_sep<char_type>(writer.locale_);
  1487.       if (!sep) return on_dec();
  1488.       int num_digits = internal::count_digits(abs_value);
  1489.       int size = num_digits + sep_size * ((num_digits - 1) / 3);
  1490.       writer.write_int(size, get_prefix(), specs,
  1491.                        num_writer{abs_value, size, sep});
  1492.     }
  1493.  
  1494.     FMT_NORETURN void on_error() {
  1495.       FMT_THROW(format_error("invalid type specifier"));
  1496.     }
  1497.   };
  1498.  
  1499.   enum { inf_size = 3 };  // This is an enum to workaround a bug in MSVC.
  1500.  
  1501.   struct inf_or_nan_writer {
  1502.     char sign;
  1503.     bool as_percentage;
  1504.     const char* str;
  1505.  
  1506.     size_t size() const {
  1507.       return static_cast<std::size_t>(inf_size + (sign ? 1 : 0) +
  1508.                                       (as_percentage ? 1 : 0));
  1509.     }
  1510.     size_t width() const { return size(); }
  1511.  
  1512.     template <typename It> void operator()(It&& it) const {
  1513.       if (sign) *it++ = static_cast<char_type>(sign);
  1514.       it = internal::copy_str<char_type>(
  1515.           str, str + static_cast<std::size_t>(inf_size), it);
  1516.       if (as_percentage) *it++ = static_cast<char_type>('%');
  1517.     }
  1518.   };
  1519.  
  1520.   struct double_writer {
  1521.     char sign;
  1522.     internal::buffer<char>& buffer;
  1523.     char* decimal_point_pos;
  1524.     char_type decimal_point;
  1525.  
  1526.     size_t size() const { return buffer.size() + (sign ? 1 : 0); }
  1527.     size_t width() const { return size(); }
  1528.  
  1529.     template <typename It> void operator()(It&& it) {
  1530.       if (sign) *it++ = static_cast<char_type>(sign);
  1531.       auto begin = buffer.begin();
  1532.       if (decimal_point_pos) {
  1533.         it = internal::copy_str<char_type>(begin, decimal_point_pos, it);
  1534.         *it++ = decimal_point;
  1535.         begin = decimal_point_pos + 1;
  1536.       }
  1537.       it = internal::copy_str<char_type>(begin, buffer.end(), it);
  1538.     }
  1539.   };
  1540.  
  1541.   class grisu_writer {
  1542.    private:
  1543.     internal::buffer<char>& digits_;
  1544.     size_t size_;
  1545.     char sign_;
  1546.     int exp_;
  1547.     internal::gen_digits_params params_;
  1548.     char_type decimal_point_;
  1549.  
  1550.    public:
  1551.     grisu_writer(char sign, internal::buffer<char>& digits, int exp,
  1552.                  const internal::gen_digits_params& params,
  1553.                  char_type decimal_point)
  1554.         : digits_(digits),
  1555.           sign_(sign),
  1556.           exp_(exp),
  1557.           params_(params),
  1558.           decimal_point_(decimal_point) {
  1559.       int num_digits = static_cast<int>(digits.size());
  1560.       int full_exp = num_digits + exp - 1;
  1561.       int precision = params.num_digits > 0 ? params.num_digits : 11;
  1562.       params_.fixed |= full_exp >= -4 && full_exp < precision;
  1563.       auto it = internal::grisu_prettify<char>(
  1564.           digits.data(), num_digits, exp, internal::counting_iterator<char>(),
  1565.           params_, '.');
  1566.       size_ = it.count();
  1567.     }
  1568.  
  1569.     size_t size() const { return size_ + (sign_ ? 1 : 0); }
  1570.     size_t width() const { return size(); }
  1571.  
  1572.     template <typename It> void operator()(It&& it) {
  1573.       if (sign_) *it++ = static_cast<char_type>(sign_);
  1574.       int num_digits = static_cast<int>(digits_.size());
  1575.       it = internal::grisu_prettify<char_type>(digits_.data(), num_digits, exp_,
  1576.                                                it, params_, decimal_point_);
  1577.     }
  1578.   };
  1579.  
  1580.   template <typename Char> struct str_writer {
  1581.     const Char* s;
  1582.     size_t size_;
  1583.  
  1584.     size_t size() const { return size_; }
  1585.     size_t width() const {
  1586.       return internal::count_code_points(basic_string_view<Char>(s, size_));
  1587.     }
  1588.  
  1589.     template <typename It> void operator()(It&& it) const {
  1590.       it = internal::copy_str<char_type>(s, s + size_, it);
  1591.     }
  1592.   };
  1593.  
  1594.   template <typename UIntPtr> struct pointer_writer {
  1595.     UIntPtr value;
  1596.     int num_digits;
  1597.  
  1598.     size_t size() const { return to_unsigned(num_digits) + 2; }
  1599.     size_t width() const { return size(); }
  1600.  
  1601.     template <typename It> void operator()(It&& it) const {
  1602.       *it++ = static_cast<char_type>('0');
  1603.       *it++ = static_cast<char_type>('x');
  1604.       it = internal::format_uint<4, char_type>(it, value, num_digits);
  1605.     }
  1606.   };
  1607.  
  1608.  public:
  1609.   /** Constructs a ``basic_writer`` object. */
  1610.   explicit basic_writer(Range out,
  1611.                         internal::locale_ref loc = internal::locale_ref())
  1612.       : out_(out.begin()), locale_(loc) {}
  1613.  
  1614.   iterator out() const { return out_; }
  1615.  
  1616.   // Writes a value in the format
  1617.   //   <left-padding><value><right-padding>
  1618.   // where <value> is written by f(it).
  1619.   template <typename F> void write_padded(const format_specs& specs, F&& f) {
  1620.     // User-perceived width (in code points).
  1621.     unsigned width = to_unsigned(specs.width);
  1622.     size_t size = f.size();  // The number of code units.
  1623.     size_t num_code_points = width != 0 ? f.width() : size;
  1624.     if (width <= num_code_points) return f(reserve(size));
  1625.     auto&& it = reserve(width + (size - num_code_points));
  1626.     char_type fill = specs.fill[0];
  1627.     std::size_t padding = width - num_code_points;
  1628.     if (specs.align == align::right) {
  1629.       it = std::fill_n(it, padding, fill);
  1630.       f(it);
  1631.     } else if (specs.align == align::center) {
  1632.       std::size_t left_padding = padding / 2;
  1633.       it = std::fill_n(it, left_padding, fill);
  1634.       f(it);
  1635.       it = std::fill_n(it, padding - left_padding, fill);
  1636.     } else {
  1637.       f(it);
  1638.       it = std::fill_n(it, padding, fill);
  1639.     }
  1640.   }
  1641.  
  1642.   void write(int value) { write_decimal(value); }
  1643.   void write(long value) { write_decimal(value); }
  1644.   void write(long long value) { write_decimal(value); }
  1645.  
  1646.   void write(unsigned value) { write_decimal(value); }
  1647.   void write(unsigned long value) { write_decimal(value); }
  1648.   void write(unsigned long long value) { write_decimal(value); }
  1649.  
  1650. #if FMT_USE_INT128
  1651.   void write(int128_t value) { write_decimal(value); }
  1652.   void write(uint128_t value) { write_decimal(value); }
  1653. #endif
  1654.  
  1655.   // Writes a formatted integer.
  1656.   template <typename T, typename Spec>
  1657.   void write_int(T value, const Spec& spec) {
  1658.     internal::handle_int_type_spec(spec.type,
  1659.                                    int_writer<T, Spec>(*this, value, spec));
  1660.   }
  1661.  
  1662.   void write(double value, const format_specs& specs = format_specs()) {
  1663.     write_double(value, specs);
  1664.   }
  1665.  
  1666.   /**
  1667.     \rst
  1668.     Formats *value* using the general format for floating-point numbers
  1669.     (``'g'``) and writes it to the buffer.
  1670.     \endrst
  1671.    */
  1672.   void write(long double value, const format_specs& specs = format_specs()) {
  1673.     write_double(value, specs);
  1674.   }
  1675.  
  1676.   // Formats a floating-point number (double or long double).
  1677.   template <typename T, bool USE_GRISU = fmt::internal::use_grisu<T>()>
  1678.   void write_double(T value, const format_specs& specs);
  1679.  
  1680.   /** Writes a character to the buffer. */
  1681.   void write(char value) {
  1682.     auto&& it = reserve(1);
  1683.     *it++ = value;
  1684.   }
  1685.  
  1686.   template <typename Char, FMT_ENABLE_IF(std::is_same<Char, char_type>::value)>
  1687.   void write(Char value) {
  1688.     auto&& it = reserve(1);
  1689.     *it++ = value;
  1690.   }
  1691.  
  1692.   /**
  1693.     \rst
  1694.     Writes *value* to the buffer.
  1695.     \endrst
  1696.    */
  1697.   void write(string_view value) {
  1698.     auto&& it = reserve(value.size());
  1699.     it = internal::copy_str<char_type>(value.begin(), value.end(), it);
  1700.   }
  1701.   void write(wstring_view value) {
  1702.     static_assert(std::is_same<char_type, wchar_t>::value, "");
  1703.     auto&& it = reserve(value.size());
  1704.     it = std::copy(value.begin(), value.end(), it);
  1705.   }
  1706.  
  1707.   // Writes a formatted string.
  1708.   template <typename Char>
  1709.   void write(const Char* s, std::size_t size, const format_specs& specs) {
  1710.     write_padded(specs, str_writer<Char>{s, size});
  1711.   }
  1712.  
  1713.   template <typename Char>
  1714.   void write(basic_string_view<Char> s,
  1715.              const format_specs& specs = format_specs()) {
  1716.     const Char* data = s.data();
  1717.     std::size_t size = s.size();
  1718.     if (specs.precision >= 0 && internal::to_unsigned(specs.precision) < size)
  1719.       size = internal::to_unsigned(specs.precision);
  1720.     write(data, size, specs);
  1721.   }
  1722.  
  1723.   template <typename UIntPtr>
  1724.   void write_pointer(UIntPtr value, const format_specs* specs) {
  1725.     int num_digits = internal::count_digits<4>(value);
  1726.     auto pw = pointer_writer<UIntPtr>{value, num_digits};
  1727.     if (!specs) return pw(reserve(to_unsigned(num_digits) + 2));
  1728.     format_specs specs_copy = *specs;
  1729.     if (specs_copy.align == align::none) specs_copy.align = align::right;
  1730.     write_padded(specs_copy, pw);
  1731.   }
  1732. };
  1733.  
  1734. using writer = basic_writer<buffer_range<char>>;
  1735.  
  1736. template <typename T> struct is_integral : std::is_integral<T> {};
  1737. template <> struct is_integral<int128_t> : std::true_type {};
  1738. template <> struct is_integral<uint128_t> : std::true_type {};
  1739.  
  1740. template <typename Range, typename ErrorHandler = internal::error_handler>
  1741. class arg_formatter_base {
  1742.  public:
  1743.   using char_type = typename Range::value_type;
  1744.   using iterator = typename Range::iterator;
  1745.   using format_specs = basic_format_specs<char_type>;
  1746.  
  1747.  private:
  1748.   using writer_type = basic_writer<Range>;
  1749.   writer_type writer_;
  1750.   format_specs* specs_;
  1751.  
  1752.   struct char_writer {
  1753.     char_type value;
  1754.  
  1755.     size_t size() const { return 1; }
  1756.     size_t width() const { return 1; }
  1757.  
  1758.     template <typename It> void operator()(It&& it) const { *it++ = value; }
  1759.   };
  1760.  
  1761.   void write_char(char_type value) {
  1762.     if (specs_)
  1763.       writer_.write_padded(*specs_, char_writer{value});
  1764.     else
  1765.       writer_.write(value);
  1766.   }
  1767.  
  1768.   void write_pointer(const void* p) {
  1769.     writer_.write_pointer(internal::bit_cast<internal::uintptr_t>(p), specs_);
  1770.   }
  1771.  
  1772.  protected:
  1773.   writer_type& writer() { return writer_; }
  1774.   FMT_DEPRECATED format_specs* spec() { return specs_; }
  1775.   format_specs* specs() { return specs_; }
  1776.   iterator out() { return writer_.out(); }
  1777.  
  1778.   void write(bool value) {
  1779.     string_view sv(value ? "true" : "false");
  1780.     specs_ ? writer_.write(sv, *specs_) : writer_.write(sv);
  1781.   }
  1782.  
  1783.   void write(const char_type* value) {
  1784.     if (!value) {
  1785.       FMT_THROW(format_error("string pointer is null"));
  1786.     } else {
  1787.       auto length = std::char_traits<char_type>::length(value);
  1788.       basic_string_view<char_type> sv(value, length);
  1789.       specs_ ? writer_.write(sv, *specs_) : writer_.write(sv);
  1790.     }
  1791.   }
  1792.  
  1793.  public:
  1794.   arg_formatter_base(Range r, format_specs* s, locale_ref loc)
  1795.       : writer_(r, loc), specs_(s) {}
  1796.  
  1797.   iterator operator()(monostate) {
  1798.     FMT_ASSERT(false, "invalid argument type");
  1799.     return out();
  1800.   }
  1801.  
  1802.   template <typename T, FMT_ENABLE_IF(is_integral<T>::value)>
  1803.   iterator operator()(T value) {
  1804.     if (specs_)
  1805.       writer_.write_int(value, *specs_);
  1806.     else
  1807.       writer_.write(value);
  1808.     return out();
  1809.   }
  1810.  
  1811.   iterator operator()(char_type value) {
  1812.     internal::handle_char_specs(
  1813.         specs_, char_spec_handler(*this, static_cast<char_type>(value)));
  1814.     return out();
  1815.   }
  1816.  
  1817.   iterator operator()(bool value) {
  1818.     if (specs_ && specs_->type) return (*this)(value ? 1 : 0);
  1819.     write(value != 0);
  1820.     return out();
  1821.   }
  1822.  
  1823.   template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
  1824.   iterator operator()(T value) {
  1825.     writer_.write_double(value, specs_ ? *specs_ : format_specs());
  1826.     return out();
  1827.   }
  1828.  
  1829.   struct char_spec_handler : ErrorHandler {
  1830.     arg_formatter_base& formatter;
  1831.     char_type value;
  1832.  
  1833.     char_spec_handler(arg_formatter_base& f, char_type val)
  1834.         : formatter(f), value(val) {}
  1835.  
  1836.     void on_int() {
  1837.       if (formatter.specs_)
  1838.         formatter.writer_.write_int(value, *formatter.specs_);
  1839.       else
  1840.         formatter.writer_.write(value);
  1841.     }
  1842.     void on_char() { formatter.write_char(value); }
  1843.   };
  1844.  
  1845.   struct cstring_spec_handler : internal::error_handler {
  1846.     arg_formatter_base& formatter;
  1847.     const char_type* value;
  1848.  
  1849.     cstring_spec_handler(arg_formatter_base& f, const char_type* val)
  1850.         : formatter(f), value(val) {}
  1851.  
  1852.     void on_string() { formatter.write(value); }
  1853.     void on_pointer() { formatter.write_pointer(value); }
  1854.   };
  1855.  
  1856.   iterator operator()(const char_type* value) {
  1857.     if (!specs_) return write(value), out();
  1858.     internal::handle_cstring_type_spec(specs_->type,
  1859.                                        cstring_spec_handler(*this, value));
  1860.     return out();
  1861.   }
  1862.  
  1863.   iterator operator()(basic_string_view<char_type> value) {
  1864.     if (specs_) {
  1865.       internal::check_string_type_spec(specs_->type, internal::error_handler());
  1866.       writer_.write(value, *specs_);
  1867.     } else {
  1868.       writer_.write(value);
  1869.     }
  1870.     return out();
  1871.   }
  1872.  
  1873.   iterator operator()(const void* value) {
  1874.     if (specs_)
  1875.       check_pointer_type_spec(specs_->type, internal::error_handler());
  1876.     write_pointer(value);
  1877.     return out();
  1878.   }
  1879. };
  1880.  
  1881. template <typename Char> FMT_CONSTEXPR bool is_name_start(Char c) {
  1882.   return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c;
  1883. }
  1884.  
  1885. // Parses the range [begin, end) as an unsigned integer. This function assumes
  1886. // that the range is non-empty and the first character is a digit.
  1887. template <typename Char, typename ErrorHandler>
  1888. FMT_CONSTEXPR int parse_nonnegative_int(const Char*& begin, const Char* end,
  1889.                                         ErrorHandler&& eh) {
  1890.   assert(begin != end && '0' <= *begin && *begin <= '9');
  1891.   if (*begin == '0') {
  1892.     ++begin;
  1893.     return 0;
  1894.   }
  1895.   unsigned value = 0;
  1896.   // Convert to unsigned to prevent a warning.
  1897.   constexpr unsigned max_int = max_value<int>();
  1898.   unsigned big = max_int / 10;
  1899.   do {
  1900.     // Check for overflow.
  1901.     if (value > big) {
  1902.       value = max_int + 1;
  1903.       break;
  1904.     }
  1905.     value = value * 10 + unsigned(*begin - '0');
  1906.     ++begin;
  1907.   } while (begin != end && '0' <= *begin && *begin <= '9');
  1908.   if (value > max_int) eh.on_error("number is too big");
  1909.   return static_cast<int>(value);
  1910. }
  1911.  
  1912. template <typename Context> class custom_formatter {
  1913.  private:
  1914.   using char_type = typename Context::char_type;
  1915.  
  1916.   basic_parse_context<char_type>& parse_ctx_;
  1917.   Context& ctx_;
  1918.  
  1919.  public:
  1920.   explicit custom_formatter(basic_parse_context<char_type>& parse_ctx,
  1921.                             Context& ctx)
  1922.       : parse_ctx_(parse_ctx), ctx_(ctx) {}
  1923.  
  1924.   bool operator()(typename basic_format_arg<Context>::handle h) const {
  1925.     h.format(parse_ctx_, ctx_);
  1926.     return true;
  1927.   }
  1928.  
  1929.   template <typename T> bool operator()(T) const { return false; }
  1930. };
  1931.  
  1932. template <typename T>
  1933. using is_integer =
  1934.     bool_constant<is_integral<T>::value && !std::is_same<T, bool>::value &&
  1935.                   !std::is_same<T, char>::value &&
  1936.                   !std::is_same<T, wchar_t>::value>;
  1937.  
  1938. template <typename ErrorHandler> class width_checker {
  1939.  public:
  1940.   explicit FMT_CONSTEXPR width_checker(ErrorHandler& eh) : handler_(eh) {}
  1941.  
  1942.   template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
  1943.   FMT_CONSTEXPR unsigned long long operator()(T value) {
  1944.     if (is_negative(value)) handler_.on_error("negative width");
  1945.     return static_cast<unsigned long long>(value);
  1946.   }
  1947.  
  1948.   template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
  1949.   FMT_CONSTEXPR unsigned long long operator()(T) {
  1950.     handler_.on_error("width is not integer");
  1951.     return 0;
  1952.   }
  1953.  
  1954.  private:
  1955.   ErrorHandler& handler_;
  1956. };
  1957.  
  1958. template <typename ErrorHandler> class precision_checker {
  1959.  public:
  1960.   explicit FMT_CONSTEXPR precision_checker(ErrorHandler& eh) : handler_(eh) {}
  1961.  
  1962.   template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
  1963.   FMT_CONSTEXPR unsigned long long operator()(T value) {
  1964.     if (is_negative(value)) handler_.on_error("negative precision");
  1965.     return static_cast<unsigned long long>(value);
  1966.   }
  1967.  
  1968.   template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
  1969.   FMT_CONSTEXPR unsigned long long operator()(T) {
  1970.     handler_.on_error("precision is not integer");
  1971.     return 0;
  1972.   }
  1973.  
  1974.  private:
  1975.   ErrorHandler& handler_;
  1976. };
  1977.  
  1978. // A format specifier handler that sets fields in basic_format_specs.
  1979. template <typename Char> class specs_setter {
  1980.  public:
  1981.   explicit FMT_CONSTEXPR specs_setter(basic_format_specs<Char>& specs)
  1982.       : specs_(specs) {}
  1983.  
  1984.   FMT_CONSTEXPR specs_setter(const specs_setter& other)
  1985.       : specs_(other.specs_) {}
  1986.  
  1987.   FMT_CONSTEXPR void on_align(align_t align) { specs_.align = align; }
  1988.   FMT_CONSTEXPR void on_fill(Char fill) { specs_.fill[0] = fill; }
  1989.   FMT_CONSTEXPR void on_plus() { specs_.sign = sign::plus; }
  1990.   FMT_CONSTEXPR void on_minus() { specs_.sign = sign::minus; }
  1991.   FMT_CONSTEXPR void on_space() { specs_.sign = sign::space; }
  1992.   FMT_CONSTEXPR void on_hash() { specs_.alt = true; }
  1993.  
  1994.   FMT_CONSTEXPR void on_zero() {
  1995.     specs_.align = align::numeric;
  1996.     specs_.fill[0] = Char('0');
  1997.   }
  1998.  
  1999.   FMT_CONSTEXPR void on_width(int width) { specs_.width = width; }
  2000.   FMT_CONSTEXPR void on_precision(int precision) {
  2001.     specs_.precision = precision;
  2002.   }
  2003.   FMT_CONSTEXPR void end_precision() {}
  2004.  
  2005.   FMT_CONSTEXPR void on_type(Char type) {
  2006.     specs_.type = static_cast<char>(type);
  2007.   }
  2008.  
  2009.  protected:
  2010.   basic_format_specs<Char>& specs_;
  2011. };
  2012.  
  2013. template <typename ErrorHandler> class numeric_specs_checker {
  2014.  public:
  2015.   FMT_CONSTEXPR numeric_specs_checker(ErrorHandler& eh, internal::type arg_type)
  2016.       : error_handler_(eh), arg_type_(arg_type) {}
  2017.  
  2018.   FMT_CONSTEXPR void require_numeric_argument() {
  2019.     if (!is_arithmetic_type(arg_type_))
  2020.       error_handler_.on_error("format specifier requires numeric argument");
  2021.   }
  2022.  
  2023.   FMT_CONSTEXPR void check_sign() {
  2024.     require_numeric_argument();
  2025.     if (is_integral_type(arg_type_) && arg_type_ != int_type &&
  2026.         arg_type_ != long_long_type && arg_type_ != internal::char_type) {
  2027.       error_handler_.on_error("format specifier requires signed argument");
  2028.     }
  2029.   }
  2030.  
  2031.   FMT_CONSTEXPR void check_precision() {
  2032.     if (is_integral_type(arg_type_) || arg_type_ == internal::pointer_type)
  2033.       error_handler_.on_error("precision not allowed for this argument type");
  2034.   }
  2035.  
  2036.  private:
  2037.   ErrorHandler& error_handler_;
  2038.   internal::type arg_type_;
  2039. };
  2040.  
  2041. // A format specifier handler that checks if specifiers are consistent with the
  2042. // argument type.
  2043. template <typename Handler> class specs_checker : public Handler {
  2044.  public:
  2045.   FMT_CONSTEXPR specs_checker(const Handler& handler, internal::type arg_type)
  2046.       : Handler(handler), checker_(*this, arg_type) {}
  2047.  
  2048.   FMT_CONSTEXPR specs_checker(const specs_checker& other)
  2049.       : Handler(other), checker_(*this, other.arg_type_) {}
  2050.  
  2051.   FMT_CONSTEXPR void on_align(align_t align) {
  2052.     if (align == align::numeric) checker_.require_numeric_argument();
  2053.     Handler::on_align(align);
  2054.   }
  2055.  
  2056.   FMT_CONSTEXPR void on_plus() {
  2057.     checker_.check_sign();
  2058.     Handler::on_plus();
  2059.   }
  2060.  
  2061.   FMT_CONSTEXPR void on_minus() {
  2062.     checker_.check_sign();
  2063.     Handler::on_minus();
  2064.   }
  2065.  
  2066.   FMT_CONSTEXPR void on_space() {
  2067.     checker_.check_sign();
  2068.     Handler::on_space();
  2069.   }
  2070.  
  2071.   FMT_CONSTEXPR void on_hash() {
  2072.     checker_.require_numeric_argument();
  2073.     Handler::on_hash();
  2074.   }
  2075.  
  2076.   FMT_CONSTEXPR void on_zero() {
  2077.     checker_.require_numeric_argument();
  2078.     Handler::on_zero();
  2079.   }
  2080.  
  2081.   FMT_CONSTEXPR void end_precision() { checker_.check_precision(); }
  2082.  
  2083.  private:
  2084.   numeric_specs_checker<Handler> checker_;
  2085. };
  2086.  
  2087. template <template <typename> class Handler, typename FormatArg,
  2088.           typename ErrorHandler>
  2089. FMT_CONSTEXPR int get_dynamic_spec(FormatArg arg, ErrorHandler eh) {
  2090.   unsigned long long value = visit_format_arg(Handler<ErrorHandler>(eh), arg);
  2091.   if (value > to_unsigned(max_value<int>())) eh.on_error("number is too big");
  2092.   return static_cast<int>(value);
  2093. }
  2094.  
  2095. struct auto_id {};
  2096.  
  2097. template <typename Context>
  2098. FMT_CONSTEXPR typename Context::format_arg get_arg(Context& ctx, int id) {
  2099.   auto arg = ctx.arg(id);
  2100.   if (!arg) ctx.on_error("argument index out of range");
  2101.   return arg;
  2102. }
  2103.  
  2104. // The standard format specifier handler with checking.
  2105. template <typename ParseContext, typename Context>
  2106. class specs_handler : public specs_setter<typename Context::char_type> {
  2107.  public:
  2108.   using char_type = typename Context::char_type;
  2109.  
  2110.   FMT_CONSTEXPR specs_handler(basic_format_specs<char_type>& specs,
  2111.                               ParseContext& parse_ctx, Context& ctx)
  2112.       : specs_setter<char_type>(specs),
  2113.         parse_context_(parse_ctx),
  2114.         context_(ctx) {}
  2115.  
  2116.   template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
  2117.     this->specs_.width = get_dynamic_spec<width_checker>(
  2118.         get_arg(arg_id), context_.error_handler());
  2119.   }
  2120.  
  2121.   template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
  2122.     this->specs_.precision = get_dynamic_spec<precision_checker>(
  2123.         get_arg(arg_id), context_.error_handler());
  2124.   }
  2125.  
  2126.   void on_error(const char* message) { context_.on_error(message); }
  2127.  
  2128.  private:
  2129.   // This is only needed for compatibility with gcc 4.4.
  2130.   using format_arg = typename Context::format_arg;
  2131.  
  2132.   FMT_CONSTEXPR format_arg get_arg(auto_id) {
  2133.     return internal::get_arg(context_, parse_context_.next_arg_id());
  2134.   }
  2135.  
  2136.   FMT_CONSTEXPR format_arg get_arg(int arg_id) {
  2137.     parse_context_.check_arg_id(arg_id);
  2138.     return internal::get_arg(context_, arg_id);
  2139.   }
  2140.  
  2141.   FMT_CONSTEXPR format_arg get_arg(basic_string_view<char_type> arg_id) {
  2142.     parse_context_.check_arg_id(arg_id);
  2143.     return context_.arg(arg_id);
  2144.   }
  2145.  
  2146.   ParseContext& parse_context_;
  2147.   Context& context_;
  2148. };
  2149.  
  2150. enum class arg_id_kind { none, index, name };
  2151.  
  2152. // An argument reference.
  2153. template <typename Char> struct arg_ref {
  2154.   FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {}
  2155.   FMT_CONSTEXPR explicit arg_ref(int index)
  2156.       : kind(arg_id_kind::index), val(index) {}
  2157.   FMT_CONSTEXPR explicit arg_ref(basic_string_view<Char> name)
  2158.       : kind(arg_id_kind::name), val(name) {}
  2159.  
  2160.   FMT_CONSTEXPR arg_ref& operator=(int idx) {
  2161.     kind = arg_id_kind::index;
  2162.     val.index = idx;
  2163.     return *this;
  2164.   }
  2165.  
  2166.   arg_id_kind kind;
  2167.   union value {
  2168.     FMT_CONSTEXPR value() : index(0u) {}
  2169.     FMT_CONSTEXPR value(int id) : index(id) {}
  2170.     FMT_CONSTEXPR value(basic_string_view<Char> n) : name(n) {}
  2171.  
  2172.     int index;
  2173.     basic_string_view<Char> name;
  2174.   } val;
  2175. };
  2176.  
  2177. // Format specifiers with width and precision resolved at formatting rather
  2178. // than parsing time to allow re-using the same parsed specifiers with
  2179. // different sets of arguments (precompilation of format strings).
  2180. template <typename Char>
  2181. struct dynamic_format_specs : basic_format_specs<Char> {
  2182.   arg_ref<Char> width_ref;
  2183.   arg_ref<Char> precision_ref;
  2184. };
  2185.  
  2186. // Format spec handler that saves references to arguments representing dynamic
  2187. // width and precision to be resolved at formatting time.
  2188. template <typename ParseContext>
  2189. class dynamic_specs_handler
  2190.     : public specs_setter<typename ParseContext::char_type> {
  2191.  public:
  2192.   using char_type = typename ParseContext::char_type;
  2193.  
  2194.   FMT_CONSTEXPR dynamic_specs_handler(dynamic_format_specs<char_type>& specs,
  2195.                                       ParseContext& ctx)
  2196.       : specs_setter<char_type>(specs), specs_(specs), context_(ctx) {}
  2197.  
  2198.   FMT_CONSTEXPR dynamic_specs_handler(const dynamic_specs_handler& other)
  2199.       : specs_setter<char_type>(other),
  2200.         specs_(other.specs_),
  2201.         context_(other.context_) {}
  2202.  
  2203.   template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
  2204.     specs_.width_ref = make_arg_ref(arg_id);
  2205.   }
  2206.  
  2207.   template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
  2208.     specs_.precision_ref = make_arg_ref(arg_id);
  2209.   }
  2210.  
  2211.   FMT_CONSTEXPR void on_error(const char* message) {
  2212.     context_.on_error(message);
  2213.   }
  2214.  
  2215.  private:
  2216.   using arg_ref_type = arg_ref<char_type>;
  2217.  
  2218.   FMT_CONSTEXPR arg_ref_type make_arg_ref(int arg_id) {
  2219.     context_.check_arg_id(arg_id);
  2220.     return arg_ref_type(arg_id);
  2221.   }
  2222.  
  2223.   FMT_CONSTEXPR arg_ref_type make_arg_ref(auto_id) {
  2224.     return arg_ref_type(context_.next_arg_id());
  2225.   }
  2226.  
  2227.   FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<char_type> arg_id) {
  2228.     context_.check_arg_id(arg_id);
  2229.     basic_string_view<char_type> format_str(
  2230.         context_.begin(), to_unsigned(context_.end() - context_.begin()));
  2231.     return arg_ref_type(arg_id);
  2232.   }
  2233.  
  2234.   dynamic_format_specs<char_type>& specs_;
  2235.   ParseContext& context_;
  2236. };
  2237.  
  2238. template <typename Char, typename IDHandler>
  2239. FMT_CONSTEXPR const Char* parse_arg_id(const Char* begin, const Char* end,
  2240.                                        IDHandler&& handler) {
  2241.   assert(begin != end);
  2242.   Char c = *begin;
  2243.   if (c == '}' || c == ':') return handler(), begin;
  2244.   if (c >= '0' && c <= '9') {
  2245.     int index = parse_nonnegative_int(begin, end, handler);
  2246.     if (begin == end || (*begin != '}' && *begin != ':'))
  2247.       return handler.on_error("invalid format string"), begin;
  2248.     handler(index);
  2249.     return begin;
  2250.   }
  2251.   if (!is_name_start(c))
  2252.     return handler.on_error("invalid format string"), begin;
  2253.   auto it = begin;
  2254.   do {
  2255.     ++it;
  2256.   } while (it != end && (is_name_start(c = *it) || ('0' <= c && c <= '9')));
  2257.   handler(basic_string_view<Char>(begin, to_unsigned(it - begin)));
  2258.   return it;
  2259. }
  2260.  
  2261. // Adapts SpecHandler to IDHandler API for dynamic width.
  2262. template <typename SpecHandler, typename Char> struct width_adapter {
  2263.   explicit FMT_CONSTEXPR width_adapter(SpecHandler& h) : handler(h) {}
  2264.  
  2265.   FMT_CONSTEXPR void operator()() { handler.on_dynamic_width(auto_id()); }
  2266.   FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_width(id); }
  2267.   FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
  2268.     handler.on_dynamic_width(id);
  2269.   }
  2270.  
  2271.   FMT_CONSTEXPR void on_error(const char* message) {
  2272.     handler.on_error(message);
  2273.   }
  2274.  
  2275.   SpecHandler& handler;
  2276. };
  2277.  
  2278. // Adapts SpecHandler to IDHandler API for dynamic precision.
  2279. template <typename SpecHandler, typename Char> struct precision_adapter {
  2280.   explicit FMT_CONSTEXPR precision_adapter(SpecHandler& h) : handler(h) {}
  2281.  
  2282.   FMT_CONSTEXPR void operator()() { handler.on_dynamic_precision(auto_id()); }
  2283.   FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_precision(id); }
  2284.   FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
  2285.     handler.on_dynamic_precision(id);
  2286.   }
  2287.  
  2288.   FMT_CONSTEXPR void on_error(const char* message) {
  2289.     handler.on_error(message);
  2290.   }
  2291.  
  2292.   SpecHandler& handler;
  2293. };
  2294.  
  2295. // Parses fill and alignment.
  2296. template <typename Char, typename Handler>
  2297. FMT_CONSTEXPR const Char* parse_align(const Char* begin, const Char* end,
  2298.                                       Handler&& handler) {
  2299.   FMT_ASSERT(begin != end, "");
  2300.   auto align = align::none;
  2301.   int i = 0;
  2302.   if (begin + 1 != end) ++i;
  2303.   do {
  2304.     switch (static_cast<char>(begin[i])) {
  2305.     case '<':
  2306.       align = align::left;
  2307.       break;
  2308.     case '>':
  2309.       align = align::right;
  2310.       break;
  2311. #if FMT_NUMERIC_ALIGN
  2312.     case '=':
  2313.       align = align::numeric;
  2314.       break;
  2315. #endif
  2316.     case '^':
  2317.       align = align::center;
  2318.       break;
  2319.     }
  2320.     if (align != align::none) {
  2321.       if (i > 0) {
  2322.         auto c = *begin;
  2323.         if (c == '{')
  2324.           return handler.on_error("invalid fill character '{'"), begin;
  2325.         begin += 2;
  2326.         handler.on_fill(c);
  2327.       } else
  2328.         ++begin;
  2329.       handler.on_align(align);
  2330.       break;
  2331.     }
  2332.   } while (i-- > 0);
  2333.   return begin;
  2334. }
  2335.  
  2336. template <typename Char, typename Handler>
  2337. FMT_CONSTEXPR const Char* parse_width(const Char* begin, const Char* end,
  2338.                                       Handler&& handler) {
  2339.   FMT_ASSERT(begin != end, "");
  2340.   if ('0' <= *begin && *begin <= '9') {
  2341.     handler.on_width(parse_nonnegative_int(begin, end, handler));
  2342.   } else if (*begin == '{') {
  2343.     ++begin;
  2344.     if (begin != end)
  2345.       begin = parse_arg_id(begin, end, width_adapter<Handler, Char>(handler));
  2346.     if (begin == end || *begin != '}')
  2347.       return handler.on_error("invalid format string"), begin;
  2348.     ++begin;
  2349.   }
  2350.   return begin;
  2351. }
  2352.  
  2353. template <typename Char, typename Handler>
  2354. FMT_CONSTEXPR const Char* parse_precision(const Char* begin, const Char* end,
  2355.                                           Handler&& handler) {
  2356.   ++begin;
  2357.   auto c = begin != end ? *begin : Char();
  2358.   if ('0' <= c && c <= '9') {
  2359.     handler.on_precision(parse_nonnegative_int(begin, end, handler));
  2360.   } else if (c == '{') {
  2361.     ++begin;
  2362.     if (begin != end) {
  2363.       begin =
  2364.           parse_arg_id(begin, end, precision_adapter<Handler, Char>(handler));
  2365.     }
  2366.     if (begin == end || *begin++ != '}')
  2367.       return handler.on_error("invalid format string"), begin;
  2368.   } else {
  2369.     return handler.on_error("missing precision specifier"), begin;
  2370.   }
  2371.   handler.end_precision();
  2372.   return begin;
  2373. }
  2374.  
  2375. // Parses standard format specifiers and sends notifications about parsed
  2376. // components to handler.
  2377. template <typename Char, typename SpecHandler>
  2378. FMT_CONSTEXPR const Char* parse_format_specs(const Char* begin, const Char* end,
  2379.                                              SpecHandler&& handler) {
  2380.   if (begin == end || *begin == '}') return begin;
  2381.  
  2382.   begin = parse_align(begin, end, handler);
  2383.   if (begin == end) return begin;
  2384.  
  2385.   // Parse sign.
  2386.   switch (static_cast<char>(*begin)) {
  2387.   case '+':
  2388.     handler.on_plus();
  2389.     ++begin;
  2390.     break;
  2391.   case '-':
  2392.     handler.on_minus();
  2393.     ++begin;
  2394.     break;
  2395.   case ' ':
  2396.     handler.on_space();
  2397.     ++begin;
  2398.     break;
  2399.   }
  2400.   if (begin == end) return begin;
  2401.  
  2402.   if (*begin == '#') {
  2403.     handler.on_hash();
  2404.     if (++begin == end) return begin;
  2405.   }
  2406.  
  2407.   // Parse zero flag.
  2408.   if (*begin == '0') {
  2409.     handler.on_zero();
  2410.     if (++begin == end) return begin;
  2411.   }
  2412.  
  2413.   begin = parse_width(begin, end, handler);
  2414.   if (begin == end) return begin;
  2415.  
  2416.   // Parse precision.
  2417.   if (*begin == '.') {
  2418.     begin = parse_precision(begin, end, handler);
  2419.   }
  2420.  
  2421.   // Parse type.
  2422.   if (begin != end && *begin != '}') handler.on_type(*begin++);
  2423.   return begin;
  2424. }
  2425.  
  2426. // Return the result via the out param to workaround gcc bug 77539.
  2427. template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>
  2428. FMT_CONSTEXPR bool find(Ptr first, Ptr last, T value, Ptr& out) {
  2429.   for (out = first; out != last; ++out) {
  2430.     if (*out == value) return true;
  2431.   }
  2432.   return false;
  2433. }
  2434.  
  2435. template <>
  2436. inline bool find<false, char>(const char* first, const char* last, char value,
  2437.                               const char*& out) {
  2438.   out = static_cast<const char*>(
  2439.       std::memchr(first, value, internal::to_unsigned(last - first)));
  2440.   return out != nullptr;
  2441. }
  2442.  
  2443. template <typename Handler, typename Char> struct id_adapter {
  2444.   FMT_CONSTEXPR void operator()() { handler.on_arg_id(); }
  2445.   FMT_CONSTEXPR void operator()(int id) { handler.on_arg_id(id); }
  2446.   FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
  2447.     handler.on_arg_id(id);
  2448.   }
  2449.   FMT_CONSTEXPR void on_error(const char* message) {
  2450.     handler.on_error(message);
  2451.   }
  2452.   Handler& handler;
  2453. };
  2454.  
  2455. template <bool IS_CONSTEXPR, typename Char, typename Handler>
  2456. FMT_CONSTEXPR void parse_format_string(basic_string_view<Char> format_str,
  2457.                                        Handler&& handler) {
  2458.   struct pfs_writer {
  2459.     FMT_CONSTEXPR void operator()(const Char* begin, const Char* end) {
  2460.       if (begin == end) return;
  2461.       for (;;) {
  2462.         const Char* p = nullptr;
  2463.         if (!find<IS_CONSTEXPR>(begin, end, '}', p))
  2464.           return handler_.on_text(begin, end);
  2465.         ++p;
  2466.         if (p == end || *p != '}')
  2467.           return handler_.on_error("unmatched '}' in format string");
  2468.         handler_.on_text(begin, p);
  2469.         begin = p + 1;
  2470.       }
  2471.     }
  2472.     Handler& handler_;
  2473.   } write{handler};
  2474.   auto begin = format_str.data();
  2475.   auto end = begin + format_str.size();
  2476.   while (begin != end) {
  2477.     // Doing two passes with memchr (one for '{' and another for '}') is up to
  2478.     // 2.5x faster than the naive one-pass implementation on big format strings.
  2479.     const Char* p = begin;
  2480.     if (*begin != '{' && !find<IS_CONSTEXPR>(begin, end, '{', p))
  2481.       return write(begin, end);
  2482.     write(begin, p);
  2483.     ++p;
  2484.     if (p == end) return handler.on_error("invalid format string");
  2485.     if (static_cast<char>(*p) == '}') {
  2486.       handler.on_arg_id();
  2487.       handler.on_replacement_field(p);
  2488.     } else if (*p == '{') {
  2489.       handler.on_text(p, p + 1);
  2490.     } else {
  2491.       p = parse_arg_id(p, end, id_adapter<Handler, Char>{handler});
  2492.       Char c = p != end ? *p : Char();
  2493.       if (c == '}') {
  2494.         handler.on_replacement_field(p);
  2495.       } else if (c == ':') {
  2496.         p = handler.on_format_specs(p + 1, end);
  2497.         if (p == end || *p != '}')
  2498.           return handler.on_error("unknown format specifier");
  2499.       } else {
  2500.         return handler.on_error("missing '}' in format string");
  2501.       }
  2502.     }
  2503.     begin = p + 1;
  2504.   }
  2505. }
  2506.  
  2507. template <typename T, typename ParseContext>
  2508. FMT_CONSTEXPR const typename ParseContext::char_type* parse_format_specs(
  2509.     ParseContext& ctx) {
  2510.   using char_type = typename ParseContext::char_type;
  2511.   using context = buffer_context<char_type>;
  2512.   using mapped_type =
  2513.       conditional_t<internal::mapped_type_constant<T, context>::value !=
  2514.                         internal::custom_type,
  2515.                     decltype(arg_mapper<context>().map(std::declval<T>())), T>;
  2516.   conditional_t<has_formatter<mapped_type, context>::value,
  2517.                 formatter<mapped_type, char_type>,
  2518.                 internal::fallback_formatter<T, char_type>>
  2519.       f;
  2520.   return f.parse(ctx);
  2521. }
  2522.  
  2523. template <typename Char, typename ErrorHandler, typename... Args>
  2524. class format_string_checker {
  2525.  public:
  2526.   explicit FMT_CONSTEXPR format_string_checker(
  2527.       basic_string_view<Char> format_str, ErrorHandler eh)
  2528.       : arg_id_(max_value<unsigned>()),
  2529.         context_(format_str, eh),
  2530.         parse_funcs_{&parse_format_specs<Args, parse_context_type>...} {}
  2531.  
  2532.   FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
  2533.  
  2534.   FMT_CONSTEXPR void on_arg_id() {
  2535.     arg_id_ = context_.next_arg_id();
  2536.     check_arg_id();
  2537.   }
  2538.   FMT_CONSTEXPR void on_arg_id(int id) {
  2539.     arg_id_ = id;
  2540.     context_.check_arg_id(id);
  2541.     check_arg_id();
  2542.   }
  2543.   FMT_CONSTEXPR void on_arg_id(basic_string_view<Char>) {
  2544.     on_error("compile-time checks don't support named arguments");
  2545.   }
  2546.  
  2547.   FMT_CONSTEXPR void on_replacement_field(const Char*) {}
  2548.  
  2549.   FMT_CONSTEXPR const Char* on_format_specs(const Char* begin, const Char*) {
  2550.     advance_to(context_, begin);
  2551.     return arg_id_ < num_args ? parse_funcs_[arg_id_](context_) : begin;
  2552.   }
  2553.  
  2554.   FMT_CONSTEXPR void on_error(const char* message) {
  2555.     context_.on_error(message);
  2556.   }
  2557.  
  2558.  private:
  2559.   using parse_context_type = basic_parse_context<Char, ErrorHandler>;
  2560.   enum { num_args = sizeof...(Args) };
  2561.  
  2562.   FMT_CONSTEXPR void check_arg_id() {
  2563.     if (arg_id_ >= num_args) context_.on_error("argument index out of range");
  2564.   }
  2565.  
  2566.   // Format specifier parsing function.
  2567.   using parse_func = const Char* (*)(parse_context_type&);
  2568.  
  2569.   unsigned arg_id_;
  2570.   parse_context_type context_;
  2571.   parse_func parse_funcs_[num_args > 0 ? num_args : 1];
  2572. };
  2573.  
  2574. template <typename Char, typename ErrorHandler, typename... Args>
  2575. FMT_CONSTEXPR bool do_check_format_string(basic_string_view<Char> s,
  2576.                                           ErrorHandler eh = ErrorHandler()) {
  2577.   format_string_checker<Char, ErrorHandler, Args...> checker(s, eh);
  2578.   parse_format_string<true>(s, checker);
  2579.   return true;
  2580. }
  2581.  
  2582. template <typename... Args, typename S,
  2583.           enable_if_t<(is_compile_string<S>::value), int>>
  2584. void check_format_string(S format_str) {
  2585.   FMT_CONSTEXPR_DECL bool invalid_format =
  2586.       internal::do_check_format_string<typename S::char_type,
  2587.                                        internal::error_handler, Args...>(
  2588.           to_string_view(format_str));
  2589.   (void)invalid_format;
  2590. }
  2591.  
  2592. template <template <typename> class Handler, typename Context>
  2593. void handle_dynamic_spec(int& value, arg_ref<typename Context::char_type> ref,
  2594.                          Context& ctx) {
  2595.   switch (ref.kind) {
  2596.   case arg_id_kind::none:
  2597.     break;
  2598.   case arg_id_kind::index:
  2599.     value = internal::get_dynamic_spec<Handler>(ctx.arg(ref.val.index),
  2600.                                                 ctx.error_handler());
  2601.     break;
  2602.   case arg_id_kind::name:
  2603.     value = internal::get_dynamic_spec<Handler>(ctx.arg(ref.val.name),
  2604.                                                 ctx.error_handler());
  2605.     break;
  2606.   }
  2607. }
  2608. }  // namespace internal
  2609.  
  2610. template <typename Range>
  2611. using basic_writer FMT_DEPRECATED_ALIAS = internal::basic_writer<Range>;
  2612. using writer FMT_DEPRECATED_ALIAS = internal::writer;
  2613. using wwriter FMT_DEPRECATED_ALIAS =
  2614.     internal::basic_writer<buffer_range<wchar_t>>;
  2615.  
  2616. /** The default argument formatter. */
  2617. template <typename Range>
  2618. class arg_formatter : public internal::arg_formatter_base<Range> {
  2619.  private:
  2620.   using char_type = typename Range::value_type;
  2621.   using base = internal::arg_formatter_base<Range>;
  2622.   using context_type = basic_format_context<typename base::iterator, char_type>;
  2623.  
  2624.   context_type& ctx_;
  2625.   basic_parse_context<char_type>* parse_ctx_;
  2626.  
  2627.  public:
  2628.   using range = Range;
  2629.   using iterator = typename base::iterator;
  2630.   using format_specs = typename base::format_specs;
  2631.  
  2632.   /**
  2633.     \rst
  2634.     Constructs an argument formatter object.
  2635.     *ctx* is a reference to the formatting context,
  2636.     *specs* contains format specifier information for standard argument types.
  2637.     \endrst
  2638.    */
  2639.   explicit arg_formatter(context_type& ctx,
  2640.                          basic_parse_context<char_type>* parse_ctx = nullptr,
  2641.                          format_specs* specs = nullptr)
  2642.       : base(Range(ctx.out()), specs, ctx.locale()),
  2643.         ctx_(ctx),
  2644.         parse_ctx_(parse_ctx) {}
  2645.  
  2646.   using base::operator();
  2647.  
  2648.   /** Formats an argument of a user-defined type. */
  2649.   iterator operator()(typename basic_format_arg<context_type>::handle handle) {
  2650.     handle.format(*parse_ctx_, ctx_);
  2651.     return this->out();
  2652.   }
  2653. };
  2654.  
  2655. /**
  2656.  An error returned by an operating system or a language runtime,
  2657.  for example a file opening error.
  2658. */
  2659. class FMT_API system_error : public std::runtime_error {
  2660.  private:
  2661.   void init(int err_code, string_view format_str, format_args args);
  2662.  
  2663.  protected:
  2664.   int error_code_;
  2665.  
  2666.   system_error() : std::runtime_error(""), error_code_(0) {}
  2667.  
  2668.  public:
  2669.   /**
  2670.    \rst
  2671.    Constructs a :class:`fmt::system_error` object with a description
  2672.    formatted with `fmt::format_system_error`. *message* and additional
  2673.    arguments passed into the constructor are formatted similarly to
  2674.    `fmt::format`.
  2675.  
  2676.    **Example**::
  2677.  
  2678.      // This throws a system_error with the description
  2679.      //   cannot open file 'madeup': No such file or directory
  2680.      // or similar (system message may vary).
  2681.      const char *filename = "madeup";
  2682.      std::FILE *file = std::fopen(filename, "r");
  2683.      if (!file)
  2684.        throw fmt::system_error(errno, "cannot open file '{}'", filename);
  2685.    \endrst
  2686.   */
  2687.   template <typename... Args>
  2688.   system_error(int error_code, string_view message, const Args&... args)
  2689.       : std::runtime_error("") {
  2690.     init(error_code, message, make_format_args(args...));
  2691.   }
  2692.   ~system_error() FMT_NOEXCEPT;
  2693.  
  2694.   int error_code() const { return error_code_; }
  2695. };
  2696.  
  2697. /**
  2698.   \rst
  2699.   Formats an error returned by an operating system or a language runtime,
  2700.   for example a file opening error, and writes it to *out* in the following
  2701.   form:
  2702.  
  2703.   .. parsed-literal::
  2704.      *<message>*: *<system-message>*
  2705.  
  2706.   where *<message>* is the passed message and *<system-message>* is
  2707.   the system message corresponding to the error code.
  2708.   *error_code* is a system error code as given by ``errno``.
  2709.   If *error_code* is not a valid error code such as -1, the system message
  2710.   may look like "Unknown error -1" and is platform-dependent.
  2711.   \endrst
  2712.  */
  2713. FMT_API void format_system_error(internal::buffer<char>& out, int error_code,
  2714.                                  fmt::string_view message) FMT_NOEXCEPT;
  2715.  
  2716. struct float_spec_handler {
  2717.   char type;
  2718.   bool upper;
  2719.   bool fixed;
  2720.   bool as_percentage;
  2721.   bool use_locale;
  2722.  
  2723.   explicit float_spec_handler(char t)
  2724.       : type(t),
  2725.         upper(false),
  2726.         fixed(false),
  2727.         as_percentage(false),
  2728.         use_locale(false) {}
  2729.  
  2730.   void on_general() {
  2731.     if (type == 'G') upper = true;
  2732.   }
  2733.  
  2734.   void on_exp() {
  2735.     if (type == 'E') upper = true;
  2736.   }
  2737.  
  2738.   void on_fixed() {
  2739.     fixed = true;
  2740.     if (type == 'F') upper = true;
  2741.   }
  2742.  
  2743.   void on_percent() {
  2744.     fixed = true;
  2745.     as_percentage = true;
  2746.   }
  2747.  
  2748.   void on_hex() {
  2749.     if (type == 'A') upper = true;
  2750.   }
  2751.  
  2752.   void on_num() { use_locale = true; }
  2753.  
  2754.   FMT_NORETURN void on_error() {
  2755.     FMT_THROW(format_error("invalid type specifier"));
  2756.   }
  2757. };
  2758.  
  2759. template <typename Range>
  2760. template <typename T, bool USE_GRISU>
  2761. void internal::basic_writer<Range>::write_double(T value,
  2762.                                                  const format_specs& specs) {
  2763.   // Check type.
  2764.   float_spec_handler handler(static_cast<char>(specs.type));
  2765.   internal::handle_float_type_spec(handler.type, handler);
  2766.  
  2767.   char sign = 0;
  2768.   // Use signbit instead of value < 0 since the latter is always false for NaN.
  2769.   if (std::signbit(value)) {
  2770.     sign = '-';
  2771.     value = -value;
  2772.   } else if (specs.sign != sign::none) {
  2773.     if (specs.sign == sign::plus)
  2774.       sign = '+';
  2775.     else if (specs.sign == sign::space)
  2776.       sign = ' ';
  2777.   }
  2778.  
  2779.   if (!std::isfinite(value)) {
  2780.     // Format infinity and NaN ourselves because sprintf's output is not
  2781.     // consistent across platforms.
  2782.     const char* str = std::isinf(value) ? (handler.upper ? "INF" : "inf")
  2783.                                         : (handler.upper ? "NAN" : "nan");
  2784.     return write_padded(specs,
  2785.                         inf_or_nan_writer{sign, handler.as_percentage, str});
  2786.   }
  2787.  
  2788.   if (handler.as_percentage) value *= 100;
  2789.  
  2790.   memory_buffer buffer;
  2791.   int exp = 0;
  2792.   int precision = specs.precision >= 0 || !specs.type ? specs.precision : 6;
  2793.   bool use_grisu = USE_GRISU &&
  2794.                    (specs.type != 'a' && specs.type != 'A' &&
  2795.                     specs.type != 'e' && specs.type != 'E') &&
  2796.                    internal::grisu_format(
  2797.                        static_cast<double>(value), buffer, precision,
  2798.                        handler.fixed ? internal::grisu_options::fixed : 0, exp);
  2799.   char* decimal_point_pos = nullptr;
  2800.   if (!use_grisu)
  2801.     decimal_point_pos = internal::sprintf_format(value, buffer, specs);
  2802.  
  2803.   if (handler.as_percentage) {
  2804.     buffer.push_back('%');
  2805.     --exp;  // Adjust decimal place position.
  2806.   }
  2807.   format_specs as = specs;
  2808.   if (specs.align == align::numeric) {
  2809.     if (sign) {
  2810.       auto&& it = reserve(1);
  2811.       *it++ = static_cast<char_type>(sign);
  2812.       sign = 0;
  2813.       if (as.width) --as.width;
  2814.     }
  2815.     as.align = align::right;
  2816.   } else if (specs.align == align::none) {
  2817.     as.align = align::right;
  2818.   }
  2819.   char_type decimal_point = handler.use_locale
  2820.                                 ? internal::decimal_point<char_type>(locale_)
  2821.                                 : static_cast<char_type>('.');
  2822.   if (use_grisu) {
  2823.     auto params = internal::gen_digits_params();
  2824.     params.fixed = handler.fixed;
  2825.     params.num_digits = precision;
  2826.     params.trailing_zeros =
  2827.         (precision != 0 && (handler.fixed || !specs.type)) || specs.alt;
  2828.     write_padded(as, grisu_writer(sign, buffer, exp, params, decimal_point));
  2829.   } else {
  2830.     write_padded(as,
  2831.                  double_writer{sign, buffer, decimal_point_pos, decimal_point});
  2832.   }
  2833. }
  2834.  
  2835. // Reports a system error without throwing an exception.
  2836. // Can be used to report errors from destructors.
  2837. FMT_API void report_system_error(int error_code,
  2838.                                  string_view message) FMT_NOEXCEPT;
  2839.  
  2840. #if FMT_USE_WINDOWS_H
  2841.  
  2842. /** A Windows error. */
  2843. class windows_error : public system_error {
  2844.  private:
  2845.   FMT_API void init(int error_code, string_view format_str, format_args args);
  2846.  
  2847.  public:
  2848.   /**
  2849.    \rst
  2850.    Constructs a :class:`fmt::windows_error` object with the description
  2851.    of the form
  2852.  
  2853.    .. parsed-literal::
  2854.      *<message>*: *<system-message>*
  2855.  
  2856.    where *<message>* is the formatted message and *<system-message>* is the
  2857.    system message corresponding to the error code.
  2858.    *error_code* is a Windows error code as given by ``GetLastError``.
  2859.    If *error_code* is not a valid error code such as -1, the system message
  2860.    will look like "error -1".
  2861.  
  2862.    **Example**::
  2863.  
  2864.      // This throws a windows_error with the description
  2865.      //   cannot open file 'madeup': The system cannot find the file specified.
  2866.      // or similar (system message may vary).
  2867.      const char *filename = "madeup";
  2868.      LPOFSTRUCT of = LPOFSTRUCT();
  2869.      HFILE file = OpenFile(filename, &of, OF_READ);
  2870.      if (file == HFILE_ERROR) {
  2871.        throw fmt::windows_error(GetLastError(),
  2872.                                 "cannot open file '{}'", filename);
  2873.      }
  2874.    \endrst
  2875.   */
  2876.   template <typename... Args>
  2877.   windows_error(int error_code, string_view message, const Args&... args) {
  2878.     init(error_code, message, make_format_args(args...));
  2879.   }
  2880. };
  2881.  
  2882. // Reports a Windows error without throwing an exception.
  2883. // Can be used to report errors from destructors.
  2884. FMT_API void report_windows_error(int error_code,
  2885.                                   string_view message) FMT_NOEXCEPT;
  2886.  
  2887. #endif
  2888.  
  2889. /** Fast integer formatter. */
  2890. class format_int {
  2891.  private:
  2892.   // Buffer should be large enough to hold all digits (digits10 + 1),
  2893.   // a sign and a null character.
  2894.   enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 };
  2895.   mutable char buffer_[buffer_size];
  2896.   char* str_;
  2897.  
  2898.   // Formats value in reverse and returns a pointer to the beginning.
  2899.   char* format_decimal(unsigned long long value) {
  2900.     char* ptr = buffer_ + (buffer_size - 1);  // Parens to workaround MSVC bug.
  2901.     while (value >= 100) {
  2902.       // Integer division is slow so do it for a group of two digits instead
  2903.       // of for every digit. The idea comes from the talk by Alexandrescu
  2904.       // "Three Optimization Tips for C++". See speed-test for a comparison.
  2905.       unsigned index = static_cast<unsigned>((value % 100) * 2);
  2906.       value /= 100;
  2907.       *--ptr = internal::data::digits[index + 1];
  2908.       *--ptr = internal::data::digits[index];
  2909.     }
  2910.     if (value < 10) {
  2911.       *--ptr = static_cast<char>('0' + value);
  2912.       return ptr;
  2913.     }
  2914.     unsigned index = static_cast<unsigned>(value * 2);
  2915.     *--ptr = internal::data::digits[index + 1];
  2916.     *--ptr = internal::data::digits[index];
  2917.     return ptr;
  2918.   }
  2919.  
  2920.   void format_signed(long long value) {
  2921.     unsigned long long abs_value = static_cast<unsigned long long>(value);
  2922.     bool negative = value < 0;
  2923.     if (negative) abs_value = 0 - abs_value;
  2924.     str_ = format_decimal(abs_value);
  2925.     if (negative) *--str_ = '-';
  2926.   }
  2927.  
  2928.  public:
  2929.   explicit format_int(int value) { format_signed(value); }
  2930.   explicit format_int(long value) { format_signed(value); }
  2931.   explicit format_int(long long value) { format_signed(value); }
  2932.   explicit format_int(unsigned value) : str_(format_decimal(value)) {}
  2933.   explicit format_int(unsigned long value) : str_(format_decimal(value)) {}
  2934.   explicit format_int(unsigned long long value) : str_(format_decimal(value)) {}
  2935.  
  2936.   /** Returns the number of characters written to the output buffer. */
  2937.   std::size_t size() const {
  2938.     return internal::to_unsigned(buffer_ - str_ + buffer_size - 1);
  2939.   }
  2940.  
  2941.   /**
  2942.     Returns a pointer to the output buffer content. No terminating null
  2943.     character is appended.
  2944.    */
  2945.   const char* data() const { return str_; }
  2946.  
  2947.   /**
  2948.     Returns a pointer to the output buffer content with terminating null
  2949.     character appended.
  2950.    */
  2951.   const char* c_str() const {
  2952.     buffer_[buffer_size - 1] = '\0';
  2953.     return str_;
  2954.   }
  2955.  
  2956.   /**
  2957.     \rst
  2958.     Returns the content of the output buffer as an ``std::string``.
  2959.     \endrst
  2960.    */
  2961.   std::string str() const { return std::string(str_, size()); }
  2962. };
  2963.  
  2964. // A formatter specialization for the core types corresponding to internal::type
  2965. // constants.
  2966. template <typename T, typename Char>
  2967. struct formatter<T, Char,
  2968.                  enable_if_t<internal::type_constant<T, Char>::value !=
  2969.                              internal::custom_type>> {
  2970.   FMT_CONSTEXPR formatter() {}
  2971.  
  2972.   // Parses format specifiers stopping either at the end of the range or at the
  2973.   // terminating '}'.
  2974.   template <typename ParseContext>
  2975.   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  2976.     using handler_type = internal::dynamic_specs_handler<ParseContext>;
  2977.     auto type = internal::type_constant<T, Char>::value;
  2978.     internal::specs_checker<handler_type> handler(handler_type(specs_, ctx),
  2979.                                                   type);
  2980.     auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
  2981.     auto eh = ctx.error_handler();
  2982.     switch (type) {
  2983.     case internal::none_type:
  2984.     case internal::named_arg_type:
  2985.       FMT_ASSERT(false, "invalid argument type");
  2986.       break;
  2987.     case internal::int_type:
  2988.     case internal::uint_type:
  2989.     case internal::long_long_type:
  2990.     case internal::ulong_long_type:
  2991.     case internal::int128_type:
  2992.     case internal::uint128_type:
  2993.     case internal::bool_type:
  2994.       handle_int_type_spec(specs_.type,
  2995.                            internal::int_type_checker<decltype(eh)>(eh));
  2996.       break;
  2997.     case internal::char_type:
  2998.       handle_char_specs(
  2999.           &specs_, internal::char_specs_checker<decltype(eh)>(specs_.type, eh));
  3000.       break;
  3001.     case internal::double_type:
  3002.     case internal::long_double_type:
  3003.       handle_float_type_spec(specs_.type,
  3004.                              internal::float_type_checker<decltype(eh)>(eh));
  3005.       break;
  3006.     case internal::cstring_type:
  3007.       internal::handle_cstring_type_spec(
  3008.           specs_.type, internal::cstring_type_checker<decltype(eh)>(eh));
  3009.       break;
  3010.     case internal::string_type:
  3011.       internal::check_string_type_spec(specs_.type, eh);
  3012.       break;
  3013.     case internal::pointer_type:
  3014.       internal::check_pointer_type_spec(specs_.type, eh);
  3015.       break;
  3016.     case internal::custom_type:
  3017.       // Custom format specifiers should be checked in parse functions of
  3018.       // formatter specializations.
  3019.       break;
  3020.     }
  3021.     return it;
  3022.   }
  3023.  
  3024.   template <typename FormatContext>
  3025.   auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) {
  3026.     internal::handle_dynamic_spec<internal::width_checker>(
  3027.         specs_.width, specs_.width_ref, ctx);
  3028.     internal::handle_dynamic_spec<internal::precision_checker>(
  3029.         specs_.precision, specs_.precision_ref, ctx);
  3030.     using range_type =
  3031.         internal::output_range<typename FormatContext::iterator,
  3032.                                typename FormatContext::char_type>;
  3033.     return visit_format_arg(arg_formatter<range_type>(ctx, nullptr, &specs_),
  3034.                             internal::make_arg<FormatContext>(val));
  3035.   }
  3036.  
  3037.  private:
  3038.   internal::dynamic_format_specs<Char> specs_;
  3039. };
  3040.  
  3041. #define FMT_FORMAT_AS(Type, Base)                                             \
  3042.   template <typename Char>                                                    \
  3043.   struct formatter<Type, Char> : formatter<Base, Char> {                      \
  3044.     template <typename FormatContext>                                         \
  3045.     auto format(const Type& val, FormatContext& ctx) -> decltype(ctx.out()) { \
  3046.       return formatter<Base, Char>::format(val, ctx);                         \
  3047.     }                                                                         \
  3048.   }
  3049.  
  3050. FMT_FORMAT_AS(signed char, int);
  3051. FMT_FORMAT_AS(unsigned char, unsigned);
  3052. FMT_FORMAT_AS(short, int);
  3053. FMT_FORMAT_AS(unsigned short, unsigned);
  3054. FMT_FORMAT_AS(long, long long);
  3055. FMT_FORMAT_AS(unsigned long, unsigned long long);
  3056. FMT_FORMAT_AS(float, double);
  3057. FMT_FORMAT_AS(Char*, const Char*);
  3058. FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>);
  3059. FMT_FORMAT_AS(std::nullptr_t, const void*);
  3060. FMT_FORMAT_AS(internal::std_string_view<Char>, basic_string_view<Char>);
  3061.  
  3062. template <typename Char>
  3063. struct formatter<void*, Char> : formatter<const void*, Char> {
  3064.   template <typename FormatContext>
  3065.   auto format(void* val, FormatContext& ctx) -> decltype(ctx.out()) {
  3066.     return formatter<const void*, Char>::format(val, ctx);
  3067.   }
  3068. };
  3069.  
  3070. template <typename Char, size_t N>
  3071. struct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> {
  3072.   template <typename FormatContext>
  3073.   auto format(const Char* val, FormatContext& ctx) -> decltype(ctx.out()) {
  3074.     return formatter<basic_string_view<Char>, Char>::format(val, ctx);
  3075.   }
  3076. };
  3077.  
  3078. // A formatter for types known only at run time such as variant alternatives.
  3079. //
  3080. // Usage:
  3081. //   using variant = std::variant<int, std::string>;
  3082. //   template <>
  3083. //   struct formatter<variant>: dynamic_formatter<> {
  3084. //     void format(buffer &buf, const variant &v, context &ctx) {
  3085. //       visit([&](const auto &val) { format(buf, val, ctx); }, v);
  3086. //     }
  3087. //   };
  3088. template <typename Char = char> class dynamic_formatter {
  3089.  private:
  3090.   struct null_handler : internal::error_handler {
  3091.     void on_align(align_t) {}
  3092.     void on_plus() {}
  3093.     void on_minus() {}
  3094.     void on_space() {}
  3095.     void on_hash() {}
  3096.   };
  3097.  
  3098.  public:
  3099.   template <typename ParseContext>
  3100.   auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  3101.     format_str_ = ctx.begin();
  3102.     // Checks are deferred to formatting time when the argument type is known.
  3103.     internal::dynamic_specs_handler<ParseContext> handler(specs_, ctx);
  3104.     return parse_format_specs(ctx.begin(), ctx.end(), handler);
  3105.   }
  3106.  
  3107.   template <typename T, typename FormatContext>
  3108.   auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) {
  3109.     handle_specs(ctx);
  3110.     internal::specs_checker<null_handler> checker(
  3111.         null_handler(),
  3112.         internal::mapped_type_constant<T, FormatContext>::value);
  3113.     checker.on_align(specs_.align);
  3114.     switch (specs_.sign) {
  3115.     case sign::none:
  3116.       break;
  3117.     case sign::plus:
  3118.       checker.on_plus();
  3119.       break;
  3120.     case sign::minus:
  3121.       checker.on_minus();
  3122.       break;
  3123.     case sign::space:
  3124.       checker.on_space();
  3125.       break;
  3126.     }
  3127.     if (specs_.alt) checker.on_hash();
  3128.     if (specs_.precision >= 0) checker.end_precision();
  3129.     using range = internal::output_range<typename FormatContext::iterator,
  3130.                                          typename FormatContext::char_type>;
  3131.     visit_format_arg(arg_formatter<range>(ctx, nullptr, &specs_),
  3132.                      internal::make_arg<FormatContext>(val));
  3133.     return ctx.out();
  3134.   }
  3135.  
  3136.  private:
  3137.   template <typename Context> void handle_specs(Context& ctx) {
  3138.     internal::handle_dynamic_spec<internal::width_checker>(
  3139.         specs_.width, specs_.width_ref, ctx);
  3140.     internal::handle_dynamic_spec<internal::precision_checker>(
  3141.         specs_.precision, specs_.precision_ref, ctx);
  3142.   }
  3143.  
  3144.   internal::dynamic_format_specs<Char> specs_;
  3145.   const Char* format_str_;
  3146. };
  3147.  
  3148. template <typename Range, typename Char>
  3149. typename basic_format_context<Range, Char>::format_arg
  3150. basic_format_context<Range, Char>::arg(basic_string_view<char_type> name) {
  3151.   map_.init(args_);
  3152.   format_arg arg = map_.find(name);
  3153.   if (arg.type() == internal::none_type) this->on_error("argument not found");
  3154.   return arg;
  3155. }
  3156.  
  3157. template <typename Char, typename ErrorHandler>
  3158. FMT_CONSTEXPR void advance_to(basic_parse_context<Char, ErrorHandler>& ctx,
  3159.                               const Char* p) {
  3160.   ctx.advance_to(ctx.begin() + (p - &*ctx.begin()));
  3161. }
  3162.  
  3163. template <typename ArgFormatter, typename Char, typename Context>
  3164. struct format_handler : internal::error_handler {
  3165.   using range = typename ArgFormatter::range;
  3166.  
  3167.   format_handler(range r, basic_string_view<Char> str,
  3168.                  basic_format_args<Context> format_args,
  3169.                  internal::locale_ref loc)
  3170.       : parse_context(str), context(r.begin(), format_args, loc) {}
  3171.  
  3172.   void on_text(const Char* begin, const Char* end) {
  3173.     auto size = internal::to_unsigned(end - begin);
  3174.     auto out = context.out();
  3175.     auto&& it = internal::reserve(out, size);
  3176.     it = std::copy_n(begin, size, it);
  3177.     context.advance_to(out);
  3178.   }
  3179.  
  3180.   void get_arg(int id) { arg = internal::get_arg(context, id); }
  3181.  
  3182.   void on_arg_id() { get_arg(parse_context.next_arg_id()); }
  3183.   void on_arg_id(int id) {
  3184.     parse_context.check_arg_id(id);
  3185.     get_arg(id);
  3186.   }
  3187.   void on_arg_id(basic_string_view<Char> id) { arg = context.arg(id); }
  3188.  
  3189.   void on_replacement_field(const Char* p) {
  3190.     advance_to(parse_context, p);
  3191.     internal::custom_formatter<Context> f(parse_context, context);
  3192.     if (!visit_format_arg(f, arg))
  3193.       context.advance_to(
  3194.           visit_format_arg(ArgFormatter(context, &parse_context), arg));
  3195.   }
  3196.  
  3197.   const Char* on_format_specs(const Char* begin, const Char* end) {
  3198.     advance_to(parse_context, begin);
  3199.     internal::custom_formatter<Context> f(parse_context, context);
  3200.     if (visit_format_arg(f, arg)) return parse_context.begin();
  3201.     basic_format_specs<Char> specs;
  3202.     using internal::specs_handler;
  3203.     using parse_context_t = basic_parse_context<Char>;
  3204.     internal::specs_checker<specs_handler<parse_context_t, Context>> handler(
  3205.         specs_handler<parse_context_t, Context>(specs, parse_context, context),
  3206.         arg.type());
  3207.     begin = parse_format_specs(begin, end, handler);
  3208.     if (begin == end || *begin != '}') on_error("missing '}' in format string");
  3209.     advance_to(parse_context, begin);
  3210.     context.advance_to(
  3211.         visit_format_arg(ArgFormatter(context, &parse_context, &specs), arg));
  3212.     return begin;
  3213.   }
  3214.  
  3215.   basic_parse_context<Char> parse_context;
  3216.   Context context;
  3217.   basic_format_arg<Context> arg;
  3218. };
  3219.  
  3220. /** Formats arguments and writes the output to the range. */
  3221. template <typename ArgFormatter, typename Char, typename Context>
  3222. typename Context::iterator vformat_to(
  3223.     typename ArgFormatter::range out, basic_string_view<Char> format_str,
  3224.     basic_format_args<Context> args,
  3225.     internal::locale_ref loc = internal::locale_ref()) {
  3226.   format_handler<ArgFormatter, Char, Context> h(out, format_str, args, loc);
  3227.   internal::parse_format_string<false>(format_str, h);
  3228.   return h.context.out();
  3229. }
  3230.  
  3231. // Casts ``p`` to ``const void*`` for pointer formatting.
  3232. // Example:
  3233. //   auto s = format("{}", ptr(p));
  3234. template <typename T> inline const void* ptr(const T* p) { return p; }
  3235. template <typename T> inline const void* ptr(const std::unique_ptr<T>& p) {
  3236.   return p.get();
  3237. }
  3238. template <typename T> inline const void* ptr(const std::shared_ptr<T>& p) {
  3239.   return p.get();
  3240. }
  3241.  
  3242. template <typename It, typename Char> struct arg_join : internal::view {
  3243.   It begin;
  3244.   It end;
  3245.   basic_string_view<Char> sep;
  3246.  
  3247.   arg_join(It b, It e, basic_string_view<Char> s) : begin(b), end(e), sep(s) {}
  3248. };
  3249.  
  3250. template <typename It, typename Char>
  3251. struct formatter<arg_join<It, Char>, Char>
  3252.     : formatter<typename std::iterator_traits<It>::value_type, Char> {
  3253.   template <typename FormatContext>
  3254.   auto format(const arg_join<It, Char>& value, FormatContext& ctx)
  3255.       -> decltype(ctx.out()) {
  3256.     using base = formatter<typename std::iterator_traits<It>::value_type, Char>;
  3257.     auto it = value.begin;
  3258.     auto out = ctx.out();
  3259.     if (it != value.end) {
  3260.       out = base::format(*it++, ctx);
  3261.       while (it != value.end) {
  3262.         out = std::copy(value.sep.begin(), value.sep.end(), out);
  3263.         ctx.advance_to(out);
  3264.         out = base::format(*it++, ctx);
  3265.       }
  3266.     }
  3267.     return out;
  3268.   }
  3269. };
  3270.  
  3271. /**
  3272.   Returns an object that formats the iterator range `[begin, end)` with elements
  3273.   separated by `sep`.
  3274.  */
  3275. template <typename It>
  3276. arg_join<It, char> join(It begin, It end, string_view sep) {
  3277.   return {begin, end, sep};
  3278. }
  3279.  
  3280. template <typename It>
  3281. arg_join<It, wchar_t> join(It begin, It end, wstring_view sep) {
  3282.   return {begin, end, sep};
  3283. }
  3284.  
  3285. /**
  3286.   \rst
  3287.   Returns an object that formats `range` with elements separated by `sep`.
  3288.  
  3289.   **Example**::
  3290.  
  3291.     std::vector<int> v = {1, 2, 3};
  3292.     fmt::print("{}", fmt::join(v, ", "));
  3293.     // Output: "1, 2, 3"
  3294.   \endrst
  3295.  */
  3296. template <typename Range>
  3297. arg_join<internal::iterator_t<const Range>, char> join(const Range& range,
  3298.                                                        string_view sep) {
  3299.   return join(std::begin(range), std::end(range), sep);
  3300. }
  3301.  
  3302. template <typename Range>
  3303. arg_join<internal::iterator_t<const Range>, wchar_t> join(const Range& range,
  3304.                                                           wstring_view sep) {
  3305.   return join(std::begin(range), std::end(range), sep);
  3306. }
  3307.  
  3308. /**
  3309.   \rst
  3310.   Converts *value* to ``std::string`` using the default format for type *T*.
  3311.   It doesn't support user-defined types with custom formatters.
  3312.  
  3313.   **Example**::
  3314.  
  3315.     #include <fmt/format.h>
  3316.  
  3317.     std::string answer = fmt::to_string(42);
  3318.   \endrst
  3319.  */
  3320. template <typename T> inline std::string to_string(const T& value) {
  3321.   return format("{}", value);
  3322. }
  3323.  
  3324. /**
  3325.   Converts *value* to ``std::wstring`` using the default format for type *T*.
  3326.  */
  3327. template <typename T> inline std::wstring to_wstring(const T& value) {
  3328.   return format(L"{}", value);
  3329. }
  3330.  
  3331. template <typename Char, std::size_t SIZE>
  3332. std::basic_string<Char> to_string(const basic_memory_buffer<Char, SIZE>& buf) {
  3333.   return std::basic_string<Char>(buf.data(), buf.size());
  3334. }
  3335.  
  3336. template <typename Char>
  3337. typename buffer_context<Char>::iterator internal::vformat_to(
  3338.     internal::buffer<Char>& buf, basic_string_view<Char> format_str,
  3339.     basic_format_args<buffer_context<Char>> args) {
  3340.   using range = buffer_range<Char>;
  3341.   return vformat_to<arg_formatter<range>>(buf, to_string_view(format_str),
  3342.                                           args);
  3343. }
  3344.  
  3345. template <typename S, typename Char = char_t<S>,
  3346.           FMT_ENABLE_IF(internal::is_string<S>::value)>
  3347. inline typename buffer_context<Char>::iterator vformat_to(
  3348.     internal::buffer<Char>& buf, const S& format_str,
  3349.     basic_format_args<buffer_context<Char>> args) {
  3350.   return internal::vformat_to(buf, to_string_view(format_str), args);
  3351. }
  3352.  
  3353. template <typename S, typename... Args, std::size_t SIZE = inline_buffer_size,
  3354.           typename Char = enable_if_t<internal::is_string<S>::value, char_t<S>>>
  3355. inline typename buffer_context<Char>::iterator format_to(
  3356.     basic_memory_buffer<Char, SIZE>& buf, const S& format_str, Args&&... args) {
  3357.   internal::check_format_string<Args...>(format_str);
  3358.   using context = buffer_context<Char>;
  3359.   return internal::vformat_to(buf, to_string_view(format_str),
  3360.                               {make_format_args<context>(args...)});
  3361. }
  3362.  
  3363. template <typename OutputIt, typename Char = char>
  3364. using format_context_t = basic_format_context<OutputIt, Char>;
  3365.  
  3366. template <typename OutputIt, typename Char = char>
  3367. using format_args_t = basic_format_args<format_context_t<OutputIt, Char>>;
  3368.  
  3369. template <typename S, typename OutputIt, typename... Args,
  3370.           FMT_ENABLE_IF(
  3371.               internal::is_output_iterator<OutputIt>::value &&
  3372.               !internal::is_contiguous_back_insert_iterator<OutputIt>::value)>
  3373. inline OutputIt vformat_to(OutputIt out, const S& format_str,
  3374.                            format_args_t<OutputIt, char_t<S>> args) {
  3375.   using range = internal::output_range<OutputIt, char_t<S>>;
  3376.   return vformat_to<arg_formatter<range>>(range(out),
  3377.                                           to_string_view(format_str), args);
  3378. }
  3379.  
  3380. /**
  3381.  \rst
  3382.  Formats arguments, writes the result to the output iterator ``out`` and returns
  3383.  the iterator past the end of the output range.
  3384.  
  3385.  **Example**::
  3386.  
  3387.    std::vector<char> out;
  3388.    fmt::format_to(std::back_inserter(out), "{}", 42);
  3389.  \endrst
  3390.  */
  3391. template <typename OutputIt, typename S, typename... Args,
  3392.           FMT_ENABLE_IF(
  3393.               internal::is_output_iterator<OutputIt>::value &&
  3394.               !internal::is_contiguous_back_insert_iterator<OutputIt>::value &&
  3395.               internal::is_string<S>::value)>
  3396. inline OutputIt format_to(OutputIt out, const S& format_str, Args&&... args) {
  3397.   internal::check_format_string<Args...>(format_str);
  3398.   using context = format_context_t<OutputIt, char_t<S>>;
  3399.   return vformat_to(out, to_string_view(format_str),
  3400.                     {make_format_args<context>(args...)});
  3401. }
  3402.  
  3403. template <typename OutputIt> struct format_to_n_result {
  3404.   /** Iterator past the end of the output range. */
  3405.   OutputIt out;
  3406.   /** Total (not truncated) output size. */
  3407.   std::size_t size;
  3408. };
  3409.  
  3410. template <typename OutputIt, typename Char = typename OutputIt::value_type>
  3411. using format_to_n_context =
  3412.     format_context_t<fmt::internal::truncating_iterator<OutputIt>, Char>;
  3413.  
  3414. template <typename OutputIt, typename Char = typename OutputIt::value_type>
  3415. using format_to_n_args = basic_format_args<format_to_n_context<OutputIt, Char>>;
  3416.  
  3417. template <typename OutputIt, typename Char, typename... Args>
  3418. inline format_arg_store<format_to_n_context<OutputIt, Char>, Args...>
  3419. make_format_to_n_args(const Args&... args) {
  3420.   return format_arg_store<format_to_n_context<OutputIt, Char>, Args...>(
  3421.       args...);
  3422. }
  3423.  
  3424. template <typename OutputIt, typename Char, typename... Args,
  3425.           FMT_ENABLE_IF(internal::is_output_iterator<OutputIt>::value)>
  3426. inline format_to_n_result<OutputIt> vformat_to_n(
  3427.     OutputIt out, std::size_t n, basic_string_view<Char> format_str,
  3428.     format_to_n_args<OutputIt, Char> args) {
  3429.   auto it = vformat_to(internal::truncating_iterator<OutputIt>(out, n),
  3430.                        format_str, args);
  3431.   return {it.base(), it.count()};
  3432. }
  3433.  
  3434. /**
  3435.  \rst
  3436.  Formats arguments, writes up to ``n`` characters of the result to the output
  3437.  iterator ``out`` and returns the total output size and the iterator past the
  3438.  end of the output range.
  3439.  \endrst
  3440.  */
  3441. template <typename OutputIt, typename S, typename... Args,
  3442.           FMT_ENABLE_IF(internal::is_string<S>::value&&
  3443.                             internal::is_output_iterator<OutputIt>::value)>
  3444. inline format_to_n_result<OutputIt> format_to_n(OutputIt out, std::size_t n,
  3445.                                                 const S& format_str,
  3446.                                                 const Args&... args) {
  3447.   internal::check_format_string<Args...>(format_str);
  3448.   using context = format_to_n_context<OutputIt, char_t<S>>;
  3449.   return vformat_to_n(out, n, to_string_view(format_str),
  3450.                       {make_format_args<context>(args...)});
  3451. }
  3452.  
  3453. template <typename Char>
  3454. inline std::basic_string<Char> internal::vformat(
  3455.     basic_string_view<Char> format_str,
  3456.     basic_format_args<buffer_context<Char>> args) {
  3457.   basic_memory_buffer<Char> buffer;
  3458.   internal::vformat_to(buffer, format_str, args);
  3459.   return fmt::to_string(buffer);
  3460. }
  3461.  
  3462. /**
  3463.   Returns the number of characters in the output of
  3464.   ``format(format_str, args...)``.
  3465.  */
  3466. template <typename... Args>
  3467. inline std::size_t formatted_size(string_view format_str, const Args&... args) {
  3468.   auto it = format_to(internal::counting_iterator<char>(), format_str, args...);
  3469.   return it.count();
  3470. }
  3471.  
  3472. #if FMT_USE_USER_DEFINED_LITERALS
  3473. namespace internal {
  3474.  
  3475. #  if FMT_USE_UDL_TEMPLATE
  3476. template <typename Char, Char... CHARS> class udl_formatter {
  3477.  public:
  3478.   template <typename... Args>
  3479.   std::basic_string<Char> operator()(Args&&... args) const {
  3480.     FMT_CONSTEXPR_DECL Char s[] = {CHARS..., '\0'};
  3481.     FMT_CONSTEXPR_DECL bool invalid_format =
  3482.         do_check_format_string<Char, error_handler, remove_cvref_t<Args>...>(
  3483.             basic_string_view<Char>(s, sizeof...(CHARS)));
  3484.     (void)invalid_format;
  3485.     return format(s, std::forward<Args>(args)...);
  3486.   }
  3487. };
  3488. #  else
  3489. template <typename Char> struct udl_formatter {
  3490.   basic_string_view<Char> str;
  3491.  
  3492.   template <typename... Args>
  3493.   std::basic_string<Char> operator()(Args&&... args) const {
  3494.     return format(str, std::forward<Args>(args)...);
  3495.   }
  3496. };
  3497. #  endif  // FMT_USE_UDL_TEMPLATE
  3498.  
  3499. template <typename Char> struct udl_arg {
  3500.   basic_string_view<Char> str;
  3501.  
  3502.   template <typename T> named_arg<T, Char> operator=(T&& value) const {
  3503.     return {str, std::forward<T>(value)};
  3504.   }
  3505. };
  3506.  
  3507. }  // namespace internal
  3508.  
  3509. inline namespace literals {
  3510. #  if FMT_USE_UDL_TEMPLATE
  3511. #    pragma GCC diagnostic push
  3512. #    if FMT_CLANG_VERSION
  3513. #      pragma GCC diagnostic ignored "-Wgnu-string-literal-operator-template"
  3514. #    endif
  3515. template <typename Char, Char... CHARS>
  3516. FMT_CONSTEXPR internal::udl_formatter<Char, CHARS...> operator""_format() {
  3517.   return {};
  3518. }
  3519. #    pragma GCC diagnostic pop
  3520. #  else
  3521. /**
  3522.   \rst
  3523.   User-defined literal equivalent of :func:`fmt::format`.
  3524.  
  3525.   **Example**::
  3526.  
  3527.     using namespace fmt::literals;
  3528.     std::string message = "The answer is {}"_format(42);
  3529.   \endrst
  3530.  */
  3531. FMT_CONSTEXPR internal::udl_formatter<char> operator"" _format(const char* s,
  3532.                                                                std::size_t n) {
  3533.   return {{s, n}};
  3534. }
  3535. FMT_CONSTEXPR internal::udl_formatter<wchar_t> operator"" _format(
  3536.     const wchar_t* s, std::size_t n) {
  3537.   return {{s, n}};
  3538. }
  3539. #  endif  // FMT_USE_UDL_TEMPLATE
  3540.  
  3541. /**
  3542.   \rst
  3543.   User-defined literal equivalent of :func:`fmt::arg`.
  3544.  
  3545.   **Example**::
  3546.  
  3547.     using namespace fmt::literals;
  3548.     fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);
  3549.   \endrst
  3550.  */
  3551. FMT_CONSTEXPR internal::udl_arg<char> operator"" _a(const char* s,
  3552.                                                     std::size_t n) {
  3553.   return {{s, n}};
  3554. }
  3555. FMT_CONSTEXPR internal::udl_arg<wchar_t> operator"" _a(const wchar_t* s,
  3556.                                                        std::size_t n) {
  3557.   return {{s, n}};
  3558. }
  3559. }  // namespace literals
  3560. #endif  // FMT_USE_USER_DEFINED_LITERALS
  3561. FMT_END_NAMESPACE
  3562.  
  3563. /**
  3564.   \rst
  3565.   Constructs a compile-time format string.
  3566.  
  3567.   **Example**::
  3568.  
  3569.     // A compile-time error because 'd' is an invalid specifier for strings.
  3570.     std::string s = format(FMT_STRING("{:d}"), "foo");
  3571.   \endrst
  3572.  */
  3573. #define FMT_STRING(s)                                                    \
  3574.   [] {                                                                   \
  3575.     struct str : fmt::compile_string {                                   \
  3576.       using char_type = typename std::remove_cv<std::remove_pointer<     \
  3577.           typename std::decay<decltype(s)>::type>::type>::type;          \
  3578.       FMT_CONSTEXPR operator fmt::basic_string_view<char_type>() const { \
  3579.         return {s, sizeof(s) / sizeof(char_type) - 1};                   \
  3580.       }                                                                  \
  3581.     } result;                                                            \
  3582.     /* Suppress Qt Creator warning about unused operator. */             \
  3583.     (void)static_cast<fmt::basic_string_view<typename str::char_type>>(  \
  3584.         result);                                                         \
  3585.     return result;                                                       \
  3586.   }()
  3587.  
  3588. #if defined(FMT_STRING_ALIAS) && FMT_STRING_ALIAS
  3589. /**
  3590.   \rst
  3591.   Constructs a compile-time format string. This macro is disabled by default to
  3592.   prevent potential name collisions. To enable it define ``FMT_STRING_ALIAS`` to
  3593.   1 before including ``fmt/format.h``.
  3594.  
  3595.   **Example**::
  3596.  
  3597.     #define FMT_STRING_ALIAS 1
  3598.     #include <fmt/format.h>
  3599.     // A compile-time error because 'd' is an invalid specifier for strings.
  3600.     std::string s = format(fmt("{:d}"), "foo");
  3601.   \endrst
  3602.  */
  3603. #  define fmt(s) FMT_STRING(s)
  3604. #endif
  3605.  
  3606. #ifdef FMT_HEADER_ONLY
  3607. #  define FMT_FUNC inline
  3608. #  include "format-inl.h"
  3609. #else
  3610. #  define FMT_FUNC
  3611. #endif
  3612.  
  3613. #endif  // FMT_FORMAT_H_
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top