You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4217 lines
151 KiB

  1. /*
  2. Formatting library for C++
  3. Copyright (c) 2012 - present, Victor Zverovich
  4. Permission is hereby granted, free of charge, to any person obtaining
  5. a copy of this software and associated documentation files (the
  6. "Software"), to deal in the Software without restriction, including
  7. without limitation the rights to use, copy, modify, merge, publish,
  8. distribute, sublicense, and/or sell copies of the Software, and to
  9. permit persons to whom the Software is furnished to do so, subject to
  10. the following conditions:
  11. The above copyright notice and this permission notice shall be
  12. included in all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  17. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  18. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  19. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. --- Optional exception to the license ---
  21. As an exception, if, as a result of your compiling your source code, portions
  22. of this Software are embedded into a machine-executable object form of such
  23. source code, you may redistribute such embedded portions in such object form
  24. without including the above copyright and permission notices.
  25. */
  26. #ifndef FMT_FORMAT_H_
  27. #define FMT_FORMAT_H_
  28. #include <cmath> // std::signbit
  29. #include <cstdint> // uint32_t
  30. #include <cstring> // std::memcpy
  31. #include <limits> // std::numeric_limits
  32. #include <memory> // std::uninitialized_copy
  33. #include <stdexcept> // std::runtime_error
  34. #include <system_error> // std::system_error
  35. #ifdef __cpp_lib_bit_cast
  36. # include <bit> // std::bitcast
  37. #endif
  38. #include "core.h"
  39. #if FMT_GCC_VERSION
  40. # define FMT_GCC_VISIBILITY_HIDDEN __attribute__((visibility("hidden")))
  41. #else
  42. # define FMT_GCC_VISIBILITY_HIDDEN
  43. #endif
  44. #ifdef __NVCC__
  45. # define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__)
  46. #else
  47. # define FMT_CUDA_VERSION 0
  48. #endif
  49. #ifdef __has_builtin
  50. # define FMT_HAS_BUILTIN(x) __has_builtin(x)
  51. #else
  52. # define FMT_HAS_BUILTIN(x) 0
  53. #endif
  54. #if FMT_GCC_VERSION || FMT_CLANG_VERSION
  55. # define FMT_NOINLINE __attribute__((noinline))
  56. #else
  57. # define FMT_NOINLINE
  58. #endif
  59. #if FMT_MSC_VERSION
  60. # define FMT_MSC_DEFAULT = default
  61. #else
  62. # define FMT_MSC_DEFAULT
  63. #endif
  64. #ifndef FMT_THROW
  65. # if FMT_EXCEPTIONS
  66. # if FMT_MSC_VERSION || defined(__NVCC__)
  67. FMT_BEGIN_NAMESPACE
  68. namespace detail {
  69. template <typename Exception> inline void do_throw(const Exception& x) {
  70. // Silence unreachable code warnings in MSVC and NVCC because these
  71. // are nearly impossible to fix in a generic code.
  72. volatile bool b = true;
  73. if (b) throw x;
  74. }
  75. } // namespace detail
  76. FMT_END_NAMESPACE
  77. # define FMT_THROW(x) detail::do_throw(x)
  78. # else
  79. # define FMT_THROW(x) throw x
  80. # endif
  81. # else
  82. # define FMT_THROW(x) \
  83. do { \
  84. FMT_ASSERT(false, (x).what()); \
  85. } while (false)
  86. # endif
  87. #endif
  88. #if FMT_EXCEPTIONS
  89. # define FMT_TRY try
  90. # define FMT_CATCH(x) catch (x)
  91. #else
  92. # define FMT_TRY if (true)
  93. # define FMT_CATCH(x) if (false)
  94. #endif
  95. #ifndef FMT_MAYBE_UNUSED
  96. # if FMT_HAS_CPP17_ATTRIBUTE(maybe_unused)
  97. # define FMT_MAYBE_UNUSED [[maybe_unused]]
  98. # else
  99. # define FMT_MAYBE_UNUSED
  100. # endif
  101. #endif
  102. #ifndef FMT_USE_USER_DEFINED_LITERALS
  103. // EDG based compilers (Intel, NVIDIA, Elbrus, etc), GCC and MSVC support UDLs.
  104. # if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 407 || \
  105. FMT_MSC_VERSION >= 1900) && \
  106. (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= /* UDL feature */ 480)
  107. # define FMT_USE_USER_DEFINED_LITERALS 1
  108. # else
  109. # define FMT_USE_USER_DEFINED_LITERALS 0
  110. # endif
  111. #endif
  112. // Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of
  113. // integer formatter template instantiations to just one by only using the
  114. // largest integer type. This results in a reduction in binary size but will
  115. // cause a decrease in integer formatting performance.
  116. #if !defined(FMT_REDUCE_INT_INSTANTIATIONS)
  117. # define FMT_REDUCE_INT_INSTANTIATIONS 0
  118. #endif
  119. // __builtin_clz is broken in clang with Microsoft CodeGen:
  120. // https://github.com/fmtlib/fmt/issues/519.
  121. #if !FMT_MSC_VERSION
  122. # if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION
  123. # define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
  124. # endif
  125. # if FMT_HAS_BUILTIN(__builtin_clzll) || FMT_GCC_VERSION || FMT_ICC_VERSION
  126. # define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
  127. # endif
  128. #endif
  129. // __builtin_ctz is broken in Intel Compiler Classic on Windows:
  130. // https://github.com/fmtlib/fmt/issues/2510.
  131. #ifndef __ICL
  132. # if FMT_HAS_BUILTIN(__builtin_ctz) || FMT_GCC_VERSION || FMT_ICC_VERSION || \
  133. defined(__NVCOMPILER)
  134. # define FMT_BUILTIN_CTZ(n) __builtin_ctz(n)
  135. # endif
  136. # if FMT_HAS_BUILTIN(__builtin_ctzll) || FMT_GCC_VERSION || \
  137. FMT_ICC_VERSION || defined(__NVCOMPILER)
  138. # define FMT_BUILTIN_CTZLL(n) __builtin_ctzll(n)
  139. # endif
  140. #endif
  141. #if FMT_MSC_VERSION
  142. # include <intrin.h> // _BitScanReverse[64], _BitScanForward[64], _umul128
  143. #endif
  144. // Some compilers masquerade as both MSVC and GCC-likes or otherwise support
  145. // __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the
  146. // MSVC intrinsics if the clz and clzll builtins are not available.
  147. #if FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL) && \
  148. !defined(FMT_BUILTIN_CTZLL)
  149. FMT_BEGIN_NAMESPACE
  150. namespace detail {
  151. // Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning.
  152. # if !defined(__clang__)
  153. # pragma intrinsic(_BitScanForward)
  154. # pragma intrinsic(_BitScanReverse)
  155. # if defined(_WIN64)
  156. # pragma intrinsic(_BitScanForward64)
  157. # pragma intrinsic(_BitScanReverse64)
  158. # endif
  159. # endif
  160. inline auto clz(uint32_t x) -> int {
  161. unsigned long r = 0;
  162. _BitScanReverse(&r, x);
  163. FMT_ASSERT(x != 0, "");
  164. // Static analysis complains about using uninitialized data
  165. // "r", but the only way that can happen is if "x" is 0,
  166. // which the callers guarantee to not happen.
  167. FMT_MSC_WARNING(suppress : 6102)
  168. return 31 ^ static_cast<int>(r);
  169. }
  170. # define FMT_BUILTIN_CLZ(n) detail::clz(n)
  171. inline auto clzll(uint64_t x) -> int {
  172. unsigned long r = 0;
  173. # ifdef _WIN64
  174. _BitScanReverse64(&r, x);
  175. # else
  176. // Scan the high 32 bits.
  177. if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32))) return 63 ^ (r + 32);
  178. // Scan the low 32 bits.
  179. _BitScanReverse(&r, static_cast<uint32_t>(x));
  180. # endif
  181. FMT_ASSERT(x != 0, "");
  182. FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
  183. return 63 ^ static_cast<int>(r);
  184. }
  185. # define FMT_BUILTIN_CLZLL(n) detail::clzll(n)
  186. inline auto ctz(uint32_t x) -> int {
  187. unsigned long r = 0;
  188. _BitScanForward(&r, x);
  189. FMT_ASSERT(x != 0, "");
  190. FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
  191. return static_cast<int>(r);
  192. }
  193. # define FMT_BUILTIN_CTZ(n) detail::ctz(n)
  194. inline auto ctzll(uint64_t x) -> int {
  195. unsigned long r = 0;
  196. FMT_ASSERT(x != 0, "");
  197. FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
  198. # ifdef _WIN64
  199. _BitScanForward64(&r, x);
  200. # else
  201. // Scan the low 32 bits.
  202. if (_BitScanForward(&r, static_cast<uint32_t>(x))) return static_cast<int>(r);
  203. // Scan the high 32 bits.
  204. _BitScanForward(&r, static_cast<uint32_t>(x >> 32));
  205. r += 32;
  206. # endif
  207. return static_cast<int>(r);
  208. }
  209. # define FMT_BUILTIN_CTZLL(n) detail::ctzll(n)
  210. } // namespace detail
  211. FMT_END_NAMESPACE
  212. #endif
  213. FMT_BEGIN_NAMESPACE
  214. namespace detail {
  215. FMT_CONSTEXPR inline void abort_fuzzing_if(bool condition) {
  216. ignore_unused(condition);
  217. #ifdef FMT_FUZZ
  218. if (condition) throw std::runtime_error("fuzzing limit reached");
  219. #endif
  220. }
  221. template <typename CharT, CharT... C> struct string_literal {
  222. static constexpr CharT value[sizeof...(C)] = {C...};
  223. constexpr operator basic_string_view<CharT>() const {
  224. return {value, sizeof...(C)};
  225. }
  226. };
  227. #if FMT_CPLUSPLUS < 201703L
  228. template <typename CharT, CharT... C>
  229. constexpr CharT string_literal<CharT, C...>::value[sizeof...(C)];
  230. #endif
  231. template <typename Streambuf> class formatbuf : public Streambuf {
  232. private:
  233. using char_type = typename Streambuf::char_type;
  234. using streamsize = decltype(std::declval<Streambuf>().sputn(nullptr, 0));
  235. using int_type = typename Streambuf::int_type;
  236. using traits_type = typename Streambuf::traits_type;
  237. buffer<char_type>& buffer_;
  238. public:
  239. explicit formatbuf(buffer<char_type>& buf) : buffer_(buf) {}
  240. protected:
  241. // The put area is always empty. This makes the implementation simpler and has
  242. // the advantage that the streambuf and the buffer are always in sync and
  243. // sputc never writes into uninitialized memory. A disadvantage is that each
  244. // call to sputc always results in a (virtual) call to overflow. There is no
  245. // disadvantage here for sputn since this always results in a call to xsputn.
  246. auto overflow(int_type ch) -> int_type override {
  247. if (!traits_type::eq_int_type(ch, traits_type::eof()))
  248. buffer_.push_back(static_cast<char_type>(ch));
  249. return ch;
  250. }
  251. auto xsputn(const char_type* s, streamsize count) -> streamsize override {
  252. buffer_.append(s, s + count);
  253. return count;
  254. }
  255. };
  256. // Implementation of std::bit_cast for pre-C++20.
  257. template <typename To, typename From, FMT_ENABLE_IF(sizeof(To) == sizeof(From))>
  258. FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To {
  259. #ifdef __cpp_lib_bit_cast
  260. if (is_constant_evaluated()) return std::bit_cast<To>(from);
  261. #endif
  262. auto to = To();
  263. // The cast suppresses a bogus -Wclass-memaccess on GCC.
  264. std::memcpy(static_cast<void*>(&to), &from, sizeof(to));
  265. return to;
  266. }
  267. inline auto is_big_endian() -> bool {
  268. #ifdef _WIN32
  269. return false;
  270. #elif defined(__BIG_ENDIAN__)
  271. return true;
  272. #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)
  273. return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__;
  274. #else
  275. struct bytes {
  276. char data[sizeof(int)];
  277. };
  278. return bit_cast<bytes>(1).data[0] == 0;
  279. #endif
  280. }
  281. class uint128_fallback {
  282. private:
  283. uint64_t lo_, hi_;
  284. friend uint128_fallback umul128(uint64_t x, uint64_t y) noexcept;
  285. public:
  286. constexpr uint128_fallback(uint64_t hi, uint64_t lo) : lo_(lo), hi_(hi) {}
  287. constexpr uint128_fallback(uint64_t value = 0) : lo_(value), hi_(0) {}
  288. constexpr uint64_t high() const noexcept { return hi_; }
  289. constexpr uint64_t low() const noexcept { return lo_; }
  290. template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
  291. constexpr explicit operator T() const {
  292. return static_cast<T>(lo_);
  293. }
  294. friend constexpr auto operator==(const uint128_fallback& lhs,
  295. const uint128_fallback& rhs) -> bool {
  296. return lhs.hi_ == rhs.hi_ && lhs.lo_ == rhs.lo_;
  297. }
  298. friend constexpr auto operator!=(const uint128_fallback& lhs,
  299. const uint128_fallback& rhs) -> bool {
  300. return !(lhs == rhs);
  301. }
  302. friend constexpr auto operator>(const uint128_fallback& lhs,
  303. const uint128_fallback& rhs) -> bool {
  304. return lhs.hi_ != rhs.hi_ ? lhs.hi_ > rhs.hi_ : lhs.lo_ > rhs.lo_;
  305. }
  306. friend constexpr auto operator|(const uint128_fallback& lhs,
  307. const uint128_fallback& rhs)
  308. -> uint128_fallback {
  309. return {lhs.hi_ | rhs.hi_, lhs.lo_ | rhs.lo_};
  310. }
  311. friend constexpr auto operator&(const uint128_fallback& lhs,
  312. const uint128_fallback& rhs)
  313. -> uint128_fallback {
  314. return {lhs.hi_ & rhs.hi_, lhs.lo_ & rhs.lo_};
  315. }
  316. friend auto operator+(const uint128_fallback& lhs,
  317. const uint128_fallback& rhs) -> uint128_fallback {
  318. auto result = uint128_fallback(lhs);
  319. result += rhs;
  320. return result;
  321. }
  322. friend auto operator*(const uint128_fallback& lhs, uint32_t rhs)
  323. -> uint128_fallback {
  324. FMT_ASSERT(lhs.hi_ == 0, "");
  325. uint64_t hi = (lhs.lo_ >> 32) * rhs;
  326. uint64_t lo = (lhs.lo_ & ~uint32_t()) * rhs;
  327. uint64_t new_lo = (hi << 32) + lo;
  328. return {(hi >> 32) + (new_lo < lo ? 1 : 0), new_lo};
  329. }
  330. friend auto operator-(const uint128_fallback& lhs, uint64_t rhs)
  331. -> uint128_fallback {
  332. return {lhs.hi_ - (lhs.lo_ < rhs ? 1 : 0), lhs.lo_ - rhs};
  333. }
  334. FMT_CONSTEXPR auto operator>>(int shift) const -> uint128_fallback {
  335. if (shift == 64) return {0, hi_};
  336. if (shift > 64) return uint128_fallback(0, hi_) >> (shift - 64);
  337. return {hi_ >> shift, (hi_ << (64 - shift)) | (lo_ >> shift)};
  338. }
  339. FMT_CONSTEXPR auto operator<<(int shift) const -> uint128_fallback {
  340. if (shift == 64) return {lo_, 0};
  341. if (shift > 64) return uint128_fallback(lo_, 0) << (shift - 64);
  342. return {hi_ << shift | (lo_ >> (64 - shift)), (lo_ << shift)};
  343. }
  344. FMT_CONSTEXPR auto operator>>=(int shift) -> uint128_fallback& {
  345. return *this = *this >> shift;
  346. }
  347. FMT_CONSTEXPR void operator+=(uint128_fallback n) {
  348. uint64_t new_lo = lo_ + n.lo_;
  349. uint64_t new_hi = hi_ + n.hi_ + (new_lo < lo_ ? 1 : 0);
  350. FMT_ASSERT(new_hi >= hi_, "");
  351. lo_ = new_lo;
  352. hi_ = new_hi;
  353. }
  354. FMT_CONSTEXPR20 uint128_fallback& operator+=(uint64_t n) noexcept {
  355. if (is_constant_evaluated()) {
  356. lo_ += n;
  357. hi_ += (lo_ < n ? 1 : 0);
  358. return *this;
  359. }
  360. #if FMT_HAS_BUILTIN(__builtin_addcll) && !defined(__ibmxl__)
  361. unsigned long long carry;
  362. lo_ = __builtin_addcll(lo_, n, 0, &carry);
  363. hi_ += carry;
  364. #elif FMT_HAS_BUILTIN(__builtin_ia32_addcarryx_u64) && !defined(__ibmxl__)
  365. unsigned long long result;
  366. auto carry = __builtin_ia32_addcarryx_u64(0, lo_, n, &result);
  367. lo_ = result;
  368. hi_ += carry;
  369. #elif defined(_MSC_VER) && defined(_M_X64)
  370. auto carry = _addcarry_u64(0, lo_, n, &lo_);
  371. _addcarry_u64(carry, hi_, 0, &hi_);
  372. #else
  373. lo_ += n;
  374. hi_ += (lo_ < n ? 1 : 0);
  375. #endif
  376. return *this;
  377. }
  378. };
  379. using uint128_t = conditional_t<FMT_USE_INT128, uint128_opt, uint128_fallback>;
  380. #ifdef UINTPTR_MAX
  381. using uintptr_t = ::uintptr_t;
  382. #else
  383. using uintptr_t = uint128_t;
  384. #endif
  385. // Returns the largest possible value for type T. Same as
  386. // std::numeric_limits<T>::max() but shorter and not affected by the max macro.
  387. template <typename T> constexpr auto max_value() -> T {
  388. return (std::numeric_limits<T>::max)();
  389. }
  390. template <typename T> constexpr auto num_bits() -> int {
  391. return std::numeric_limits<T>::digits;
  392. }
  393. // std::numeric_limits<T>::digits may return 0 for 128-bit ints.
  394. template <> constexpr auto num_bits<int128_opt>() -> int { return 128; }
  395. template <> constexpr auto num_bits<uint128_t>() -> int { return 128; }
  396. // A heterogeneous bit_cast used for converting 96-bit long double to uint128_t
  397. // and 128-bit pointers to uint128_fallback.
  398. template <typename To, typename From, FMT_ENABLE_IF(sizeof(To) > sizeof(From))>
  399. inline auto bit_cast(const From& from) -> To {
  400. constexpr auto size = static_cast<int>(sizeof(From) / sizeof(unsigned));
  401. struct data_t {
  402. unsigned value[static_cast<unsigned>(size)];
  403. } data = bit_cast<data_t>(from);
  404. auto result = To();
  405. if (const_check(is_big_endian())) {
  406. for (int i = 0; i < size; ++i)
  407. result = (result << num_bits<unsigned>()) | data.value[i];
  408. } else {
  409. for (int i = size - 1; i >= 0; --i)
  410. result = (result << num_bits<unsigned>()) | data.value[i];
  411. }
  412. return result;
  413. }
  414. FMT_INLINE void assume(bool condition) {
  415. (void)condition;
  416. #if FMT_HAS_BUILTIN(__builtin_assume) && !FMT_ICC_VERSION
  417. __builtin_assume(condition);
  418. #endif
  419. }
  420. // An approximation of iterator_t for pre-C++20 systems.
  421. template <typename T>
  422. using iterator_t = decltype(std::begin(std::declval<T&>()));
  423. template <typename T> using sentinel_t = decltype(std::end(std::declval<T&>()));
  424. // A workaround for std::string not having mutable data() until C++17.
  425. template <typename Char>
  426. inline auto get_data(std::basic_string<Char>& s) -> Char* {
  427. return &s[0];
  428. }
  429. template <typename Container>
  430. inline auto get_data(Container& c) -> typename Container::value_type* {
  431. return c.data();
  432. }
  433. #if defined(_SECURE_SCL) && _SECURE_SCL
  434. // Make a checked iterator to avoid MSVC warnings.
  435. template <typename T> using checked_ptr = stdext::checked_array_iterator<T*>;
  436. template <typename T>
  437. constexpr auto make_checked(T* p, size_t size) -> checked_ptr<T> {
  438. return {p, size};
  439. }
  440. #else
  441. template <typename T> using checked_ptr = T*;
  442. template <typename T> constexpr auto make_checked(T* p, size_t) -> T* {
  443. return p;
  444. }
  445. #endif
  446. // Attempts to reserve space for n extra characters in the output range.
  447. // Returns a pointer to the reserved range or a reference to it.
  448. template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)>
  449. #if FMT_CLANG_VERSION >= 307 && !FMT_ICC_VERSION
  450. __attribute__((no_sanitize("undefined")))
  451. #endif
  452. inline auto
  453. reserve(std::back_insert_iterator<Container> it, size_t n)
  454. -> checked_ptr<typename Container::value_type> {
  455. Container& c = get_container(it);
  456. size_t size = c.size();
  457. c.resize(size + n);
  458. return make_checked(get_data(c) + size, n);
  459. }
  460. template <typename T>
  461. inline auto reserve(buffer_appender<T> it, size_t n) -> buffer_appender<T> {
  462. buffer<T>& buf = get_container(it);
  463. buf.try_reserve(buf.size() + n);
  464. return it;
  465. }
  466. template <typename Iterator>
  467. constexpr auto reserve(Iterator& it, size_t) -> Iterator& {
  468. return it;
  469. }
  470. template <typename OutputIt>
  471. using reserve_iterator =
  472. remove_reference_t<decltype(reserve(std::declval<OutputIt&>(), 0))>;
  473. template <typename T, typename OutputIt>
  474. constexpr auto to_pointer(OutputIt, size_t) -> T* {
  475. return nullptr;
  476. }
  477. template <typename T> auto to_pointer(buffer_appender<T> it, size_t n) -> T* {
  478. buffer<T>& buf = get_container(it);
  479. auto size = buf.size();
  480. if (buf.capacity() < size + n) return nullptr;
  481. buf.try_resize(size + n);
  482. return buf.data() + size;
  483. }
  484. template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)>
  485. inline auto base_iterator(std::back_insert_iterator<Container>& it,
  486. checked_ptr<typename Container::value_type>)
  487. -> std::back_insert_iterator<Container> {
  488. return it;
  489. }
  490. template <typename Iterator>
  491. constexpr auto base_iterator(Iterator, Iterator it) -> Iterator {
  492. return it;
  493. }
  494. // <algorithm> is spectacularly slow to compile in C++20 so use a simple fill_n
  495. // instead (#1998).
  496. template <typename OutputIt, typename Size, typename T>
  497. FMT_CONSTEXPR auto fill_n(OutputIt out, Size count, const T& value)
  498. -> OutputIt {
  499. for (Size i = 0; i < count; ++i) *out++ = value;
  500. return out;
  501. }
  502. template <typename T, typename Size>
  503. FMT_CONSTEXPR20 auto fill_n(T* out, Size count, char value) -> T* {
  504. if (is_constant_evaluated()) {
  505. return fill_n<T*, Size, T>(out, count, value);
  506. }
  507. std::memset(out, value, to_unsigned(count));
  508. return out + count;
  509. }
  510. #ifdef __cpp_char8_t
  511. using char8_type = char8_t;
  512. #else
  513. enum char8_type : unsigned char {};
  514. #endif
  515. template <typename OutChar, typename InputIt, typename OutputIt>
  516. FMT_CONSTEXPR FMT_NOINLINE auto copy_str_noinline(InputIt begin, InputIt end,
  517. OutputIt out) -> OutputIt {
  518. return copy_str<OutChar>(begin, end, out);
  519. }
  520. // A public domain branchless UTF-8 decoder by Christopher Wellons:
  521. // https://github.com/skeeto/branchless-utf8
  522. /* Decode the next character, c, from s, reporting errors in e.
  523. *
  524. * Since this is a branchless decoder, four bytes will be read from the
  525. * buffer regardless of the actual length of the next character. This
  526. * means the buffer _must_ have at least three bytes of zero padding
  527. * following the end of the data stream.
  528. *
  529. * Errors are reported in e, which will be non-zero if the parsed
  530. * character was somehow invalid: invalid byte sequence, non-canonical
  531. * encoding, or a surrogate half.
  532. *
  533. * The function returns a pointer to the next character. When an error
  534. * occurs, this pointer will be a guess that depends on the particular
  535. * error, but it will always advance at least one byte.
  536. */
  537. FMT_CONSTEXPR inline auto utf8_decode(const char* s, uint32_t* c, int* e)
  538. -> const char* {
  539. constexpr const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07};
  540. constexpr const uint32_t mins[] = {4194304, 0, 128, 2048, 65536};
  541. constexpr const int shiftc[] = {0, 18, 12, 6, 0};
  542. constexpr const int shifte[] = {0, 6, 4, 2, 0};
  543. int len = code_point_length_impl(*s);
  544. // Compute the pointer to the next character early so that the next
  545. // iteration can start working on the next character. Neither Clang
  546. // nor GCC figure out this reordering on their own.
  547. const char* next = s + len + !len;
  548. using uchar = unsigned char;
  549. // Assume a four-byte character and load four bytes. Unused bits are
  550. // shifted out.
  551. *c = uint32_t(uchar(s[0]) & masks[len]) << 18;
  552. *c |= uint32_t(uchar(s[1]) & 0x3f) << 12;
  553. *c |= uint32_t(uchar(s[2]) & 0x3f) << 6;
  554. *c |= uint32_t(uchar(s[3]) & 0x3f) << 0;
  555. *c >>= shiftc[len];
  556. // Accumulate the various error conditions.
  557. *e = (*c < mins[len]) << 6; // non-canonical encoding
  558. *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half?
  559. *e |= (*c > 0x10FFFF) << 8; // out of range?
  560. *e |= (uchar(s[1]) & 0xc0) >> 2;
  561. *e |= (uchar(s[2]) & 0xc0) >> 4;
  562. *e |= uchar(s[3]) >> 6;
  563. *e ^= 0x2a; // top two bits of each tail byte correct?
  564. *e >>= shifte[len];
  565. return next;
  566. }
  567. constexpr uint32_t invalid_code_point = ~uint32_t();
  568. // Invokes f(cp, sv) for every code point cp in s with sv being the string view
  569. // corresponding to the code point. cp is invalid_code_point on error.
  570. template <typename F>
  571. FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) {
  572. auto decode = [f](const char* buf_ptr, const char* ptr) {
  573. auto cp = uint32_t();
  574. auto error = 0;
  575. auto end = utf8_decode(buf_ptr, &cp, &error);
  576. bool result = f(error ? invalid_code_point : cp,
  577. string_view(ptr, error ? 1 : to_unsigned(end - buf_ptr)));
  578. return result ? (error ? buf_ptr + 1 : end) : nullptr;
  579. };
  580. auto p = s.data();
  581. const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars.
  582. if (s.size() >= block_size) {
  583. for (auto end = p + s.size() - block_size + 1; p < end;) {
  584. p = decode(p, p);
  585. if (!p) return;
  586. }
  587. }
  588. if (auto num_chars_left = s.data() + s.size() - p) {
  589. char buf[2 * block_size - 1] = {};
  590. copy_str<char>(p, p + num_chars_left, buf);
  591. const char* buf_ptr = buf;
  592. do {
  593. auto end = decode(buf_ptr, p);
  594. if (!end) return;
  595. p += end - buf_ptr;
  596. buf_ptr = end;
  597. } while (buf_ptr - buf < num_chars_left);
  598. }
  599. }
  600. template <typename Char>
  601. inline auto compute_width(basic_string_view<Char> s) -> size_t {
  602. return s.size();
  603. }
  604. // Computes approximate display width of a UTF-8 string.
  605. FMT_CONSTEXPR inline size_t compute_width(string_view s) {
  606. size_t num_code_points = 0;
  607. // It is not a lambda for compatibility with C++14.
  608. struct count_code_points {
  609. size_t* count;
  610. FMT_CONSTEXPR auto operator()(uint32_t cp, string_view) const -> bool {
  611. *count += detail::to_unsigned(
  612. 1 +
  613. (cp >= 0x1100 &&
  614. (cp <= 0x115f || // Hangul Jamo init. consonants
  615. cp == 0x2329 || // LEFT-POINTING ANGLE BRACKET
  616. cp == 0x232a || // RIGHT-POINTING ANGLE BRACKET
  617. // CJK ... Yi except IDEOGRAPHIC HALF FILL SPACE:
  618. (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) ||
  619. (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul Syllables
  620. (cp >= 0xf900 && cp <= 0xfaff) || // CJK Compatibility Ideographs
  621. (cp >= 0xfe10 && cp <= 0xfe19) || // Vertical Forms
  622. (cp >= 0xfe30 && cp <= 0xfe6f) || // CJK Compatibility Forms
  623. (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth Forms
  624. (cp >= 0xffe0 && cp <= 0xffe6) || // Fullwidth Forms
  625. (cp >= 0x20000 && cp <= 0x2fffd) || // CJK
  626. (cp >= 0x30000 && cp <= 0x3fffd) ||
  627. // Miscellaneous Symbols and Pictographs + Emoticons:
  628. (cp >= 0x1f300 && cp <= 0x1f64f) ||
  629. // Supplemental Symbols and Pictographs:
  630. (cp >= 0x1f900 && cp <= 0x1f9ff))));
  631. return true;
  632. }
  633. };
  634. for_each_codepoint(s, count_code_points{&num_code_points});
  635. return num_code_points;
  636. }
  637. inline auto compute_width(basic_string_view<char8_type> s) -> size_t {
  638. return compute_width(
  639. string_view(reinterpret_cast<const char*>(s.data()), s.size()));
  640. }
  641. template <typename Char>
  642. inline auto code_point_index(basic_string_view<Char> s, size_t n) -> size_t {
  643. size_t size = s.size();
  644. return n < size ? n : size;
  645. }
  646. // Calculates the index of the nth code point in a UTF-8 string.
  647. inline auto code_point_index(string_view s, size_t n) -> size_t {
  648. const char* data = s.data();
  649. size_t num_code_points = 0;
  650. for (size_t i = 0, size = s.size(); i != size; ++i) {
  651. if ((data[i] & 0xc0) != 0x80 && ++num_code_points > n) return i;
  652. }
  653. return s.size();
  654. }
  655. inline auto code_point_index(basic_string_view<char8_type> s, size_t n)
  656. -> size_t {
  657. return code_point_index(
  658. string_view(reinterpret_cast<const char*>(s.data()), s.size()), n);
  659. }
  660. #ifndef FMT_USE_FLOAT128
  661. # ifdef __SIZEOF_FLOAT128__
  662. # define FMT_USE_FLOAT128 1
  663. # else
  664. # define FMT_USE_FLOAT128 0
  665. # endif
  666. #endif
  667. #if FMT_USE_FLOAT128
  668. using float128 = __float128;
  669. #else
  670. using float128 = void;
  671. #endif
  672. template <typename T> using is_float128 = std::is_same<T, float128>;
  673. template <typename T>
  674. using is_floating_point =
  675. bool_constant<std::is_floating_point<T>::value || is_float128<T>::value>;
  676. template <typename T, bool = std::is_floating_point<T>::value>
  677. struct is_fast_float : bool_constant<std::numeric_limits<T>::is_iec559 &&
  678. sizeof(T) <= sizeof(double)> {};
  679. template <typename T> struct is_fast_float<T, false> : std::false_type {};
  680. template <typename T>
  681. using is_double_double = bool_constant<std::numeric_limits<T>::digits == 106>;
  682. #ifndef FMT_USE_FULL_CACHE_DRAGONBOX
  683. # define FMT_USE_FULL_CACHE_DRAGONBOX 0
  684. #endif
  685. template <typename T>
  686. template <typename U>
  687. void buffer<T>::append(const U* begin, const U* end) {
  688. while (begin != end) {
  689. auto count = to_unsigned(end - begin);
  690. try_reserve(size_ + count);
  691. auto free_cap = capacity_ - size_;
  692. if (free_cap < count) count = free_cap;
  693. std::uninitialized_copy_n(begin, count, make_checked(ptr_ + size_, count));
  694. size_ += count;
  695. begin += count;
  696. }
  697. }
  698. template <typename T, typename Enable = void>
  699. struct is_locale : std::false_type {};
  700. template <typename T>
  701. struct is_locale<T, void_t<decltype(T::classic())>> : std::true_type {};
  702. } // namespace detail
  703. FMT_MODULE_EXPORT_BEGIN
  704. // The number of characters to store in the basic_memory_buffer object itself
  705. // to avoid dynamic memory allocation.
  706. enum { inline_buffer_size = 500 };
  707. /**
  708. \rst
  709. A dynamically growing memory buffer for trivially copyable/constructible types
  710. with the first ``SIZE`` elements stored in the object itself.
  711. You can use the ``memory_buffer`` type alias for ``char`` instead.
  712. **Example**::
  713. auto out = fmt::memory_buffer();
  714. format_to(std::back_inserter(out), "The answer is {}.", 42);
  715. This will append the following output to the ``out`` object:
  716. .. code-block:: none
  717. The answer is 42.
  718. The output can be converted to an ``std::string`` with ``to_string(out)``.
  719. \endrst
  720. */
  721. template <typename T, size_t SIZE = inline_buffer_size,
  722. typename Allocator = std::allocator<T>>
  723. class basic_memory_buffer final : public detail::buffer<T> {
  724. private:
  725. T store_[SIZE];
  726. // Don't inherit from Allocator avoid generating type_info for it.
  727. Allocator alloc_;
  728. // Deallocate memory allocated by the buffer.
  729. FMT_CONSTEXPR20 void deallocate() {
  730. T* data = this->data();
  731. if (data != store_) alloc_.deallocate(data, this->capacity());
  732. }
  733. protected:
  734. FMT_CONSTEXPR20 void grow(size_t size) override;
  735. public:
  736. using value_type = T;
  737. using const_reference = const T&;
  738. FMT_CONSTEXPR20 explicit basic_memory_buffer(
  739. const Allocator& alloc = Allocator())
  740. : alloc_(alloc) {
  741. this->set(store_, SIZE);
  742. if (detail::is_constant_evaluated()) detail::fill_n(store_, SIZE, T());
  743. }
  744. FMT_CONSTEXPR20 ~basic_memory_buffer() { deallocate(); }
  745. private:
  746. // Move data from other to this buffer.
  747. FMT_CONSTEXPR20 void move(basic_memory_buffer& other) {
  748. alloc_ = std::move(other.alloc_);
  749. T* data = other.data();
  750. size_t size = other.size(), capacity = other.capacity();
  751. if (data == other.store_) {
  752. this->set(store_, capacity);
  753. detail::copy_str<T>(other.store_, other.store_ + size,
  754. detail::make_checked(store_, capacity));
  755. } else {
  756. this->set(data, capacity);
  757. // Set pointer to the inline array so that delete is not called
  758. // when deallocating.
  759. other.set(other.store_, 0);
  760. other.clear();
  761. }
  762. this->resize(size);
  763. }
  764. public:
  765. /**
  766. \rst
  767. Constructs a :class:`fmt::basic_memory_buffer` object moving the content
  768. of the other object to it.
  769. \endrst
  770. */
  771. FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other) noexcept {
  772. move(other);
  773. }
  774. /**
  775. \rst
  776. Moves the content of the other ``basic_memory_buffer`` object to this one.
  777. \endrst
  778. */
  779. auto operator=(basic_memory_buffer&& other) noexcept -> basic_memory_buffer& {
  780. FMT_ASSERT(this != &other, "");
  781. deallocate();
  782. move(other);
  783. return *this;
  784. }
  785. // Returns a copy of the allocator associated with this buffer.
  786. auto get_allocator() const -> Allocator { return alloc_; }
  787. /**
  788. Resizes the buffer to contain *count* elements. If T is a POD type new
  789. elements may not be initialized.
  790. */
  791. FMT_CONSTEXPR20 void resize(size_t count) { this->try_resize(count); }
  792. /** Increases the buffer capacity to *new_capacity*. */
  793. void reserve(size_t new_capacity) { this->try_reserve(new_capacity); }
  794. // Directly append data into the buffer
  795. using detail::buffer<T>::append;
  796. template <typename ContiguousRange>
  797. void append(const ContiguousRange& range) {
  798. append(range.data(), range.data() + range.size());
  799. }
  800. };
  801. template <typename T, size_t SIZE, typename Allocator>
  802. FMT_CONSTEXPR20 void basic_memory_buffer<T, SIZE, Allocator>::grow(
  803. size_t size) {
  804. detail::abort_fuzzing_if(size > 5000);
  805. const size_t max_size = std::allocator_traits<Allocator>::max_size(alloc_);
  806. size_t old_capacity = this->capacity();
  807. size_t new_capacity = old_capacity + old_capacity / 2;
  808. if (size > new_capacity)
  809. new_capacity = size;
  810. else if (new_capacity > max_size)
  811. new_capacity = size > max_size ? size : max_size;
  812. T* old_data = this->data();
  813. T* new_data =
  814. std::allocator_traits<Allocator>::allocate(alloc_, new_capacity);
  815. // The following code doesn't throw, so the raw pointer above doesn't leak.
  816. std::uninitialized_copy(old_data, old_data + this->size(),
  817. detail::make_checked(new_data, new_capacity));
  818. this->set(new_data, new_capacity);
  819. // deallocate must not throw according to the standard, but even if it does,
  820. // the buffer already uses the new storage and will deallocate it in
  821. // destructor.
  822. if (old_data != store_) alloc_.deallocate(old_data, old_capacity);
  823. }
  824. using memory_buffer = basic_memory_buffer<char>;
  825. template <typename T, size_t SIZE, typename Allocator>
  826. struct is_contiguous<basic_memory_buffer<T, SIZE, Allocator>> : std::true_type {
  827. };
  828. namespace detail {
  829. #ifdef _WIN32
  830. FMT_API bool write_console(std::FILE* f, string_view text);
  831. #endif
  832. FMT_API void print(std::FILE*, string_view);
  833. } // namespace detail
  834. /** A formatting error such as invalid format string. */
  835. FMT_CLASS_API
  836. class FMT_API format_error : public std::runtime_error {
  837. public:
  838. explicit format_error(const char* message) : std::runtime_error(message) {}
  839. explicit format_error(const std::string& message)
  840. : std::runtime_error(message) {}
  841. format_error(const format_error&) = default;
  842. format_error& operator=(const format_error&) = default;
  843. format_error(format_error&&) = default;
  844. format_error& operator=(format_error&&) = default;
  845. ~format_error() noexcept override FMT_MSC_DEFAULT;
  846. };
  847. namespace detail_exported {
  848. #if FMT_USE_NONTYPE_TEMPLATE_ARGS
  849. template <typename Char, size_t N> struct fixed_string {
  850. constexpr fixed_string(const Char (&str)[N]) {
  851. detail::copy_str<Char, const Char*, Char*>(static_cast<const Char*>(str),
  852. str + N, data);
  853. }
  854. Char data[N] = {};
  855. };
  856. #endif
  857. // Converts a compile-time string to basic_string_view.
  858. template <typename Char, size_t N>
  859. constexpr auto compile_string_to_view(const Char (&s)[N])
  860. -> basic_string_view<Char> {
  861. // Remove trailing NUL character if needed. Won't be present if this is used
  862. // with a raw character array (i.e. not defined as a string).
  863. return {s, N - (std::char_traits<Char>::to_int_type(s[N - 1]) == 0 ? 1 : 0)};
  864. }
  865. template <typename Char>
  866. constexpr auto compile_string_to_view(detail::std_string_view<Char> s)
  867. -> basic_string_view<Char> {
  868. return {s.data(), s.size()};
  869. }
  870. } // namespace detail_exported
  871. FMT_BEGIN_DETAIL_NAMESPACE
  872. template <typename T> struct is_integral : std::is_integral<T> {};
  873. template <> struct is_integral<int128_opt> : std::true_type {};
  874. template <> struct is_integral<uint128_t> : std::true_type {};
  875. template <typename T>
  876. using is_signed =
  877. std::integral_constant<bool, std::numeric_limits<T>::is_signed ||
  878. std::is_same<T, int128_opt>::value>;
  879. // Returns true if value is negative, false otherwise.
  880. // Same as `value < 0` but doesn't produce warnings if T is an unsigned type.
  881. template <typename T, FMT_ENABLE_IF(is_signed<T>::value)>
  882. constexpr auto is_negative(T value) -> bool {
  883. return value < 0;
  884. }
  885. template <typename T, FMT_ENABLE_IF(!is_signed<T>::value)>
  886. constexpr auto is_negative(T) -> bool {
  887. return false;
  888. }
  889. template <typename T>
  890. FMT_CONSTEXPR auto is_supported_floating_point(T) -> bool {
  891. if (std::is_same<T, float>()) return FMT_USE_FLOAT;
  892. if (std::is_same<T, double>()) return FMT_USE_DOUBLE;
  893. if (std::is_same<T, long double>()) return FMT_USE_LONG_DOUBLE;
  894. return true;
  895. }
  896. // Smallest of uint32_t, uint64_t, uint128_t that is large enough to
  897. // represent all values of an integral type T.
  898. template <typename T>
  899. using uint32_or_64_or_128_t =
  900. conditional_t<num_bits<T>() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS,
  901. uint32_t,
  902. conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>>;
  903. template <typename T>
  904. using uint64_or_128_t = conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>;
  905. #define FMT_POWERS_OF_10(factor) \
  906. factor * 10, (factor)*100, (factor)*1000, (factor)*10000, (factor)*100000, \
  907. (factor)*1000000, (factor)*10000000, (factor)*100000000, \
  908. (factor)*1000000000
  909. // Converts value in the range [0, 100) to a string.
  910. constexpr const char* digits2(size_t value) {
  911. // GCC generates slightly better code when value is pointer-size.
  912. return &"0001020304050607080910111213141516171819"
  913. "2021222324252627282930313233343536373839"
  914. "4041424344454647484950515253545556575859"
  915. "6061626364656667686970717273747576777879"
  916. "8081828384858687888990919293949596979899"[value * 2];
  917. }
  918. // Sign is a template parameter to workaround a bug in gcc 4.8.
  919. template <typename Char, typename Sign> constexpr Char sign(Sign s) {
  920. #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 604
  921. static_assert(std::is_same<Sign, sign_t>::value, "");
  922. #endif
  923. return static_cast<Char>("\0-+ "[s]);
  924. }
  925. template <typename T> FMT_CONSTEXPR auto count_digits_fallback(T n) -> int {
  926. int count = 1;
  927. for (;;) {
  928. // Integer division is slow so do it for a group of four digits instead
  929. // of for every digit. The idea comes from the talk by Alexandrescu
  930. // "Three Optimization Tips for C++". See speed-test for a comparison.
  931. if (n < 10) return count;
  932. if (n < 100) return count + 1;
  933. if (n < 1000) return count + 2;
  934. if (n < 10000) return count + 3;
  935. n /= 10000u;
  936. count += 4;
  937. }
  938. }
  939. #if FMT_USE_INT128
  940. FMT_CONSTEXPR inline auto count_digits(uint128_opt n) -> int {
  941. return count_digits_fallback(n);
  942. }
  943. #endif
  944. #ifdef FMT_BUILTIN_CLZLL
  945. // It is a separate function rather than a part of count_digits to workaround
  946. // the lack of static constexpr in constexpr functions.
  947. inline auto do_count_digits(uint64_t n) -> int {
  948. // This has comparable performance to the version by Kendall Willets
  949. // (https://github.com/fmtlib/format-benchmark/blob/master/digits10)
  950. // but uses smaller tables.
  951. // Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)).
  952. static constexpr uint8_t bsr2log10[] = {
  953. 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5,
  954. 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10,
  955. 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15,
  956. 15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20};
  957. auto t = bsr2log10[FMT_BUILTIN_CLZLL(n | 1) ^ 63];
  958. static constexpr const uint64_t zero_or_powers_of_10[] = {
  959. 0, 0, FMT_POWERS_OF_10(1U), FMT_POWERS_OF_10(1000000000ULL),
  960. 10000000000000000000ULL};
  961. return t - (n < zero_or_powers_of_10[t]);
  962. }
  963. #endif
  964. // Returns the number of decimal digits in n. Leading zeros are not counted
  965. // except for n == 0 in which case count_digits returns 1.
  966. FMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int {
  967. #ifdef FMT_BUILTIN_CLZLL
  968. if (!is_constant_evaluated()) {
  969. return do_count_digits(n);
  970. }
  971. #endif
  972. return count_digits_fallback(n);
  973. }
  974. // Counts the number of digits in n. BITS = log2(radix).
  975. template <int BITS, typename UInt>
  976. FMT_CONSTEXPR auto count_digits(UInt n) -> int {
  977. #ifdef FMT_BUILTIN_CLZ
  978. if (!is_constant_evaluated() && num_bits<UInt>() == 32)
  979. return (FMT_BUILTIN_CLZ(static_cast<uint32_t>(n) | 1) ^ 31) / BITS + 1;
  980. #endif
  981. // Lambda avoids unreachable code warnings from NVHPC.
  982. return [](UInt m) {
  983. int num_digits = 0;
  984. do {
  985. ++num_digits;
  986. } while ((m >>= BITS) != 0);
  987. return num_digits;
  988. }(n);
  989. }
  990. #ifdef FMT_BUILTIN_CLZ
  991. // It is a separate function rather than a part of count_digits to workaround
  992. // the lack of static constexpr in constexpr functions.
  993. FMT_INLINE auto do_count_digits(uint32_t n) -> int {
  994. // An optimization by Kendall Willets from https://bit.ly/3uOIQrB.
  995. // This increments the upper 32 bits (log10(T) - 1) when >= T is added.
  996. # define FMT_INC(T) (((sizeof(# T) - 1ull) << 32) - T)
  997. static constexpr uint64_t table[] = {
  998. FMT_INC(0), FMT_INC(0), FMT_INC(0), // 8
  999. FMT_INC(10), FMT_INC(10), FMT_INC(10), // 64
  1000. FMT_INC(100), FMT_INC(100), FMT_INC(100), // 512
  1001. FMT_INC(1000), FMT_INC(1000), FMT_INC(1000), // 4096
  1002. FMT_INC(10000), FMT_INC(10000), FMT_INC(10000), // 32k
  1003. FMT_INC(100000), FMT_INC(100000), FMT_INC(100000), // 256k
  1004. FMT_INC(1000000), FMT_INC(1000000), FMT_INC(1000000), // 2048k
  1005. FMT_INC(10000000), FMT_INC(10000000), FMT_INC(10000000), // 16M
  1006. FMT_INC(100000000), FMT_INC(100000000), FMT_INC(100000000), // 128M
  1007. FMT_INC(1000000000), FMT_INC(1000000000), FMT_INC(1000000000), // 1024M
  1008. FMT_INC(1000000000), FMT_INC(1000000000) // 4B
  1009. };
  1010. auto inc = table[FMT_BUILTIN_CLZ(n | 1) ^ 31];
  1011. return static_cast<int>((n + inc) >> 32);
  1012. }
  1013. #endif
  1014. // Optional version of count_digits for better performance on 32-bit platforms.
  1015. FMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int {
  1016. #ifdef FMT_BUILTIN_CLZ
  1017. if (!is_constant_evaluated()) {
  1018. return do_count_digits(n);
  1019. }
  1020. #endif
  1021. return count_digits_fallback(n);
  1022. }
  1023. template <typename Int> constexpr auto digits10() noexcept -> int {
  1024. return std::numeric_limits<Int>::digits10;
  1025. }
  1026. template <> constexpr auto digits10<int128_opt>() noexcept -> int { return 38; }
  1027. template <> constexpr auto digits10<uint128_t>() noexcept -> int { return 38; }
  1028. template <typename Char> struct thousands_sep_result {
  1029. std::string grouping;
  1030. Char thousands_sep;
  1031. };
  1032. template <typename Char>
  1033. FMT_API auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char>;
  1034. template <typename Char>
  1035. inline auto thousands_sep(locale_ref loc) -> thousands_sep_result<Char> {
  1036. auto result = thousands_sep_impl<char>(loc);
  1037. return {result.grouping, Char(result.thousands_sep)};
  1038. }
  1039. template <>
  1040. inline auto thousands_sep(locale_ref loc) -> thousands_sep_result<wchar_t> {
  1041. return thousands_sep_impl<wchar_t>(loc);
  1042. }
  1043. template <typename Char>
  1044. FMT_API auto decimal_point_impl(locale_ref loc) -> Char;
  1045. template <typename Char> inline auto decimal_point(locale_ref loc) -> Char {
  1046. return Char(decimal_point_impl<char>(loc));
  1047. }
  1048. template <> inline auto decimal_point(locale_ref loc) -> wchar_t {
  1049. return decimal_point_impl<wchar_t>(loc);
  1050. }
  1051. // Compares two characters for equality.
  1052. template <typename Char> auto equal2(const Char* lhs, const char* rhs) -> bool {
  1053. return lhs[0] == Char(rhs[0]) && lhs[1] == Char(rhs[1]);
  1054. }
  1055. inline auto equal2(const char* lhs, const char* rhs) -> bool {
  1056. return memcmp(lhs, rhs, 2) == 0;
  1057. }
  1058. // Copies two characters from src to dst.
  1059. template <typename Char>
  1060. FMT_CONSTEXPR20 FMT_INLINE void copy2(Char* dst, const char* src) {
  1061. if (!is_constant_evaluated() && sizeof(Char) == sizeof(char)) {
  1062. memcpy(dst, src, 2);
  1063. return;
  1064. }
  1065. *dst++ = static_cast<Char>(*src++);
  1066. *dst = static_cast<Char>(*src);
  1067. }
  1068. template <typename Iterator> struct format_decimal_result {
  1069. Iterator begin;
  1070. Iterator end;
  1071. };
  1072. // Formats a decimal unsigned integer value writing into out pointing to a
  1073. // buffer of specified size. The caller must ensure that the buffer is large
  1074. // enough.
  1075. template <typename Char, typename UInt>
  1076. FMT_CONSTEXPR20 auto format_decimal(Char* out, UInt value, int size)
  1077. -> format_decimal_result<Char*> {
  1078. FMT_ASSERT(size >= count_digits(value), "invalid digit count");
  1079. out += size;
  1080. Char* end = out;
  1081. while (value >= 100) {
  1082. // Integer division is slow so do it for a group of two digits instead
  1083. // of for every digit. The idea comes from the talk by Alexandrescu
  1084. // "Three Optimization Tips for C++". See speed-test for a comparison.
  1085. out -= 2;
  1086. copy2(out, digits2(static_cast<size_t>(value % 100)));
  1087. value /= 100;
  1088. }
  1089. if (value < 10) {
  1090. *--out = static_cast<Char>('0' + value);
  1091. return {out, end};
  1092. }
  1093. out -= 2;
  1094. copy2(out, digits2(static_cast<size_t>(value)));
  1095. return {out, end};
  1096. }
  1097. template <typename Char, typename UInt, typename Iterator,
  1098. FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<Iterator>>::value)>
  1099. FMT_CONSTEXPR inline auto format_decimal(Iterator out, UInt value, int size)
  1100. -> format_decimal_result<Iterator> {
  1101. // Buffer is large enough to hold all digits (digits10 + 1).
  1102. Char buffer[digits10<UInt>() + 1];
  1103. auto end = format_decimal(buffer, value, size).end;
  1104. return {out, detail::copy_str_noinline<Char>(buffer, end, out)};
  1105. }
  1106. template <unsigned BASE_BITS, typename Char, typename UInt>
  1107. FMT_CONSTEXPR auto format_uint(Char* buffer, UInt value, int num_digits,
  1108. bool upper = false) -> Char* {
  1109. buffer += num_digits;
  1110. Char* end = buffer;
  1111. do {
  1112. const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef";
  1113. unsigned digit = static_cast<unsigned>(value & ((1 << BASE_BITS) - 1));
  1114. *--buffer = static_cast<Char>(BASE_BITS < 4 ? static_cast<char>('0' + digit)
  1115. : digits[digit]);
  1116. } while ((value >>= BASE_BITS) != 0);
  1117. return end;
  1118. }
  1119. template <unsigned BASE_BITS, typename Char, typename It, typename UInt>
  1120. inline auto format_uint(It out, UInt value, int num_digits, bool upper = false)
  1121. -> It {
  1122. if (auto ptr = to_pointer<Char>(out, to_unsigned(num_digits))) {
  1123. format_uint<BASE_BITS>(ptr, value, num_digits, upper);
  1124. return out;
  1125. }
  1126. // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1).
  1127. char buffer[num_bits<UInt>() / BASE_BITS + 1];
  1128. format_uint<BASE_BITS>(buffer, value, num_digits, upper);
  1129. return detail::copy_str_noinline<Char>(buffer, buffer + num_digits, out);
  1130. }
  1131. // A converter from UTF-8 to UTF-16.
  1132. class utf8_to_utf16 {
  1133. private:
  1134. basic_memory_buffer<wchar_t> buffer_;
  1135. public:
  1136. FMT_API explicit utf8_to_utf16(string_view s);
  1137. operator basic_string_view<wchar_t>() const { return {&buffer_[0], size()}; }
  1138. auto size() const -> size_t { return buffer_.size() - 1; }
  1139. auto c_str() const -> const wchar_t* { return &buffer_[0]; }
  1140. auto str() const -> std::wstring { return {&buffer_[0], size()}; }
  1141. };
  1142. namespace dragonbox {
  1143. // Type-specific information that Dragonbox uses.
  1144. template <typename T, typename Enable = void> struct float_info;
  1145. template <> struct float_info<float> {
  1146. using carrier_uint = uint32_t;
  1147. static const int exponent_bits = 8;
  1148. static const int kappa = 1;
  1149. static const int big_divisor = 100;
  1150. static const int small_divisor = 10;
  1151. static const int min_k = -31;
  1152. static const int max_k = 46;
  1153. static const int shorter_interval_tie_lower_threshold = -35;
  1154. static const int shorter_interval_tie_upper_threshold = -35;
  1155. };
  1156. template <> struct float_info<double> {
  1157. using carrier_uint = uint64_t;
  1158. static const int exponent_bits = 11;
  1159. static const int kappa = 2;
  1160. static const int big_divisor = 1000;
  1161. static const int small_divisor = 100;
  1162. static const int min_k = -292;
  1163. static const int max_k = 326;
  1164. static const int shorter_interval_tie_lower_threshold = -77;
  1165. static const int shorter_interval_tie_upper_threshold = -77;
  1166. };
  1167. // An 80- or 128-bit floating point number.
  1168. template <typename T>
  1169. struct float_info<T, enable_if_t<std::numeric_limits<T>::digits == 64 ||
  1170. std::numeric_limits<T>::digits == 113 ||
  1171. is_float128<T>::value>> {
  1172. using carrier_uint = detail::uint128_t;
  1173. static const int exponent_bits = 15;
  1174. };
  1175. // A double-double floating point number.
  1176. template <typename T>
  1177. struct float_info<T, enable_if_t<is_double_double<T>::value>> {
  1178. using carrier_uint = detail::uint128_t;
  1179. };
  1180. template <typename T> struct decimal_fp {
  1181. using significand_type = typename float_info<T>::carrier_uint;
  1182. significand_type significand;
  1183. int exponent;
  1184. };
  1185. template <typename T> FMT_API auto to_decimal(T x) noexcept -> decimal_fp<T>;
  1186. } // namespace dragonbox
  1187. // Returns true iff Float has the implicit bit which is not stored.
  1188. template <typename Float> constexpr bool has_implicit_bit() {
  1189. // An 80-bit FP number has a 64-bit significand an no implicit bit.
  1190. return std::numeric_limits<Float>::digits != 64;
  1191. }
  1192. // Returns the number of significand bits stored in Float. The implicit bit is
  1193. // not counted since it is not stored.
  1194. template <typename Float> constexpr int num_significand_bits() {
  1195. // std::numeric_limits may not support __float128.
  1196. return is_float128<Float>() ? 112
  1197. : (std::numeric_limits<Float>::digits -
  1198. (has_implicit_bit<Float>() ? 1 : 0));
  1199. }
  1200. template <typename Float>
  1201. constexpr auto exponent_mask() ->
  1202. typename dragonbox::float_info<Float>::carrier_uint {
  1203. using uint = typename dragonbox::float_info<Float>::carrier_uint;
  1204. return ((uint(1) << dragonbox::float_info<Float>::exponent_bits) - 1)
  1205. << num_significand_bits<Float>();
  1206. }
  1207. template <typename Float> constexpr auto exponent_bias() -> int {
  1208. // std::numeric_limits may not support __float128.
  1209. return is_float128<Float>() ? 16383
  1210. : std::numeric_limits<Float>::max_exponent - 1;
  1211. }
  1212. // Writes the exponent exp in the form "[+-]d{2,3}" to buffer.
  1213. template <typename Char, typename It>
  1214. FMT_CONSTEXPR auto write_exponent(int exp, It it) -> It {
  1215. FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range");
  1216. if (exp < 0) {
  1217. *it++ = static_cast<Char>('-');
  1218. exp = -exp;
  1219. } else {
  1220. *it++ = static_cast<Char>('+');
  1221. }
  1222. if (exp >= 100) {
  1223. const char* top = digits2(to_unsigned(exp / 100));
  1224. if (exp >= 1000) *it++ = static_cast<Char>(top[0]);
  1225. *it++ = static_cast<Char>(top[1]);
  1226. exp %= 100;
  1227. }
  1228. const char* d = digits2(to_unsigned(exp));
  1229. *it++ = static_cast<Char>(d[0]);
  1230. *it++ = static_cast<Char>(d[1]);
  1231. return it;
  1232. }
  1233. // A floating-point number f * pow(2, e) where F is an unsigned type.
  1234. template <typename F> struct basic_fp {
  1235. F f;
  1236. int e;
  1237. static constexpr const int num_significand_bits =
  1238. static_cast<int>(sizeof(F) * num_bits<unsigned char>());
  1239. constexpr basic_fp() : f(0), e(0) {}
  1240. constexpr basic_fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}
  1241. // Constructs fp from an IEEE754 floating-point number.
  1242. template <typename Float> FMT_CONSTEXPR basic_fp(Float n) { assign(n); }
  1243. // Assigns n to this and return true iff predecessor is closer than successor.
  1244. template <typename Float, FMT_ENABLE_IF(!is_double_double<Float>::value)>
  1245. FMT_CONSTEXPR auto assign(Float n) -> bool {
  1246. static_assert(std::numeric_limits<Float>::digits <= 113, "unsupported FP");
  1247. // Assume Float is in the format [sign][exponent][significand].
  1248. using carrier_uint = typename dragonbox::float_info<Float>::carrier_uint;
  1249. const auto num_float_significand_bits =
  1250. detail::num_significand_bits<Float>();
  1251. const auto implicit_bit = carrier_uint(1) << num_float_significand_bits;
  1252. const auto significand_mask = implicit_bit - 1;
  1253. auto u = bit_cast<carrier_uint>(n);
  1254. f = static_cast<F>(u & significand_mask);
  1255. auto biased_e = static_cast<int>((u & exponent_mask<Float>()) >>
  1256. num_float_significand_bits);
  1257. // The predecessor is closer if n is a normalized power of 2 (f == 0)
  1258. // other than the smallest normalized number (biased_e > 1).
  1259. auto is_predecessor_closer = f == 0 && biased_e > 1;
  1260. if (biased_e == 0)
  1261. biased_e = 1; // Subnormals use biased exponent 1 (min exponent).
  1262. else if (has_implicit_bit<Float>())
  1263. f += static_cast<F>(implicit_bit);
  1264. e = biased_e - exponent_bias<Float>() - num_float_significand_bits;
  1265. if (!has_implicit_bit<Float>()) ++e;
  1266. return is_predecessor_closer;
  1267. }
  1268. template <typename Float, FMT_ENABLE_IF(is_double_double<Float>::value)>
  1269. FMT_CONSTEXPR auto assign(Float n) -> bool {
  1270. static_assert(std::numeric_limits<double>::is_iec559, "unsupported FP");
  1271. return assign(static_cast<double>(n));
  1272. }
  1273. };
  1274. using fp = basic_fp<unsigned long long>;
  1275. // Normalizes the value converted from double and multiplied by (1 << SHIFT).
  1276. template <int SHIFT = 0, typename F>
  1277. FMT_CONSTEXPR basic_fp<F> normalize(basic_fp<F> value) {
  1278. // Handle subnormals.
  1279. const auto implicit_bit = F(1) << num_significand_bits<double>();
  1280. const auto shifted_implicit_bit = implicit_bit << SHIFT;
  1281. while ((value.f & shifted_implicit_bit) == 0) {
  1282. value.f <<= 1;
  1283. --value.e;
  1284. }
  1285. // Subtract 1 to account for hidden bit.
  1286. const auto offset = basic_fp<F>::num_significand_bits -
  1287. num_significand_bits<double>() - SHIFT - 1;
  1288. value.f <<= offset;
  1289. value.e -= offset;
  1290. return value;
  1291. }
  1292. // Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking.
  1293. FMT_CONSTEXPR inline uint64_t multiply(uint64_t lhs, uint64_t rhs) {
  1294. #if FMT_USE_INT128
  1295. auto product = static_cast<__uint128_t>(lhs) * rhs;
  1296. auto f = static_cast<uint64_t>(product >> 64);
  1297. return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f;
  1298. #else
  1299. // Multiply 32-bit parts of significands.
  1300. uint64_t mask = (1ULL << 32) - 1;
  1301. uint64_t a = lhs >> 32, b = lhs & mask;
  1302. uint64_t c = rhs >> 32, d = rhs & mask;
  1303. uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d;
  1304. // Compute mid 64-bit of result and round.
  1305. uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31);
  1306. return ac + (ad >> 32) + (bc >> 32) + (mid >> 32);
  1307. #endif
  1308. }
  1309. FMT_CONSTEXPR inline fp operator*(fp x, fp y) {
  1310. return {multiply(x.f, y.f), x.e + y.e + 64};
  1311. }
  1312. template <typename T = void> struct basic_data {
  1313. // Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340.
  1314. // These are generated by support/compute-powers.py.
  1315. static constexpr uint64_t pow10_significands[87] = {
  1316. 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76,
  1317. 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df,
  1318. 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c,
  1319. 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5,
  1320. 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57,
  1321. 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7,
  1322. 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e,
  1323. 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996,
  1324. 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126,
  1325. 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053,
  1326. 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f,
  1327. 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b,
  1328. 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06,
  1329. 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb,
  1330. 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000,
  1331. 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984,
  1332. 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068,
  1333. 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8,
  1334. 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758,
  1335. 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85,
  1336. 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d,
  1337. 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25,
  1338. 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2,
  1339. 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a,
  1340. 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410,
  1341. 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129,
  1342. 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85,
  1343. 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841,
  1344. 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b,
  1345. };
  1346. #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
  1347. # pragma GCC diagnostic push
  1348. # pragma GCC diagnostic ignored "-Wnarrowing"
  1349. #endif
  1350. // Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding
  1351. // to significands above.
  1352. static constexpr int16_t pow10_exponents[87] = {
  1353. -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954,
  1354. -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661,
  1355. -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369,
  1356. -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77,
  1357. -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216,
  1358. 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508,
  1359. 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800,
  1360. 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066};
  1361. #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
  1362. # pragma GCC diagnostic pop
  1363. #endif
  1364. static constexpr uint64_t power_of_10_64[20] = {
  1365. 1, FMT_POWERS_OF_10(1ULL), FMT_POWERS_OF_10(1000000000ULL),
  1366. 10000000000000000000ULL};
  1367. };
  1368. #if FMT_CPLUSPLUS < 201703L
  1369. template <typename T> constexpr uint64_t basic_data<T>::pow10_significands[];
  1370. template <typename T> constexpr int16_t basic_data<T>::pow10_exponents[];
  1371. template <typename T> constexpr uint64_t basic_data<T>::power_of_10_64[];
  1372. #endif
  1373. // This is a struct rather than an alias to avoid shadowing warnings in gcc.
  1374. struct data : basic_data<> {};
  1375. // Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its
  1376. // (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`.
  1377. FMT_CONSTEXPR inline fp get_cached_power(int min_exponent,
  1378. int& pow10_exponent) {
  1379. const int shift = 32;
  1380. // log10(2) = 0x0.4d104d427de7fbcc...
  1381. const int64_t significand = 0x4d104d427de7fbcc;
  1382. int index = static_cast<int>(
  1383. ((min_exponent + fp::num_significand_bits - 1) * (significand >> shift) +
  1384. ((int64_t(1) << shift) - 1)) // ceil
  1385. >> 32 // arithmetic shift
  1386. );
  1387. // Decimal exponent of the first (smallest) cached power of 10.
  1388. const int first_dec_exp = -348;
  1389. // Difference between 2 consecutive decimal exponents in cached powers of 10.
  1390. const int dec_exp_step = 8;
  1391. index = (index - first_dec_exp - 1) / dec_exp_step + 1;
  1392. pow10_exponent = first_dec_exp + index * dec_exp_step;
  1393. // Using *(x + index) instead of x[index] avoids an issue with some compilers
  1394. // using the EDG frontend (e.g. nvhpc/22.3 in C++17 mode).
  1395. return {*(data::pow10_significands + index),
  1396. *(data::pow10_exponents + index)};
  1397. }
  1398. #ifndef _MSC_VER
  1399. # define FMT_SNPRINTF snprintf
  1400. #else
  1401. FMT_API auto fmt_snprintf(char* buf, size_t size, const char* fmt, ...) -> int;
  1402. # define FMT_SNPRINTF fmt_snprintf
  1403. #endif // _MSC_VER
  1404. // Formats a floating-point number with snprintf using the hexfloat format.
  1405. template <typename T>
  1406. auto snprintf_float(T value, int precision, float_specs specs,
  1407. buffer<char>& buf) -> int {
  1408. // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail.
  1409. FMT_ASSERT(buf.capacity() > buf.size(), "empty buffer");
  1410. FMT_ASSERT(specs.format == float_format::hex, "");
  1411. static_assert(!std::is_same<T, float>::value, "");
  1412. // Build the format string.
  1413. char format[7]; // The longest format is "%#.*Le".
  1414. char* format_ptr = format;
  1415. *format_ptr++ = '%';
  1416. if (specs.showpoint) *format_ptr++ = '#';
  1417. if (precision >= 0) {
  1418. *format_ptr++ = '.';
  1419. *format_ptr++ = '*';
  1420. }
  1421. if (std::is_same<T, long double>()) *format_ptr++ = 'L';
  1422. *format_ptr++ = specs.upper ? 'A' : 'a';
  1423. *format_ptr = '\0';
  1424. // Format using snprintf.
  1425. auto offset = buf.size();
  1426. for (;;) {
  1427. auto begin = buf.data() + offset;
  1428. auto capacity = buf.capacity() - offset;
  1429. abort_fuzzing_if(precision > 100000);
  1430. // Suppress the warning about a nonliteral format string.
  1431. // Cannot use auto because of a bug in MinGW (#1532).
  1432. int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF;
  1433. int result = precision >= 0
  1434. ? snprintf_ptr(begin, capacity, format, precision, value)
  1435. : snprintf_ptr(begin, capacity, format, value);
  1436. if (result < 0) {
  1437. // The buffer will grow exponentially.
  1438. buf.try_reserve(buf.capacity() + 1);
  1439. continue;
  1440. }
  1441. auto size = to_unsigned(result);
  1442. // Size equal to capacity means that the last character was truncated.
  1443. if (size < capacity) {
  1444. buf.try_resize(size + offset);
  1445. return 0;
  1446. }
  1447. buf.try_reserve(size + offset + 1); // Add 1 for the terminating '\0'.
  1448. }
  1449. }
  1450. template <typename T>
  1451. using convert_float_result =
  1452. conditional_t<std::is_same<T, float>::value || sizeof(T) == sizeof(double),
  1453. double, T>;
  1454. template <typename T>
  1455. constexpr auto convert_float(T value) -> convert_float_result<T> {
  1456. return static_cast<convert_float_result<T>>(value);
  1457. }
  1458. template <typename OutputIt, typename Char>
  1459. FMT_NOINLINE FMT_CONSTEXPR auto fill(OutputIt it, size_t n,
  1460. const fill_t<Char>& fill) -> OutputIt {
  1461. auto fill_size = fill.size();
  1462. if (fill_size == 1) return detail::fill_n(it, n, fill[0]);
  1463. auto data = fill.data();
  1464. for (size_t i = 0; i < n; ++i)
  1465. it = copy_str<Char>(data, data + fill_size, it);
  1466. return it;
  1467. }
  1468. // Writes the output of f, padded according to format specifications in specs.
  1469. // size: output size in code units.
  1470. // width: output display width in (terminal) column positions.
  1471. template <align::type align = align::left, typename OutputIt, typename Char,
  1472. typename F>
  1473. FMT_CONSTEXPR auto write_padded(OutputIt out,
  1474. const basic_format_specs<Char>& specs,
  1475. size_t size, size_t width, F&& f) -> OutputIt {
  1476. static_assert(align == align::left || align == align::right, "");
  1477. unsigned spec_width = to_unsigned(specs.width);
  1478. size_t padding = spec_width > width ? spec_width - width : 0;
  1479. // Shifts are encoded as string literals because static constexpr is not
  1480. // supported in constexpr functions.
  1481. auto* shifts = align == align::left ? "\x1f\x1f\x00\x01" : "\x00\x1f\x00\x01";
  1482. size_t left_padding = padding >> shifts[specs.align];
  1483. size_t right_padding = padding - left_padding;
  1484. auto it = reserve(out, size + padding * specs.fill.size());
  1485. if (left_padding != 0) it = fill(it, left_padding, specs.fill);
  1486. it = f(it);
  1487. if (right_padding != 0) it = fill(it, right_padding, specs.fill);
  1488. return base_iterator(out, it);
  1489. }
  1490. template <align::type align = align::left, typename OutputIt, typename Char,
  1491. typename F>
  1492. constexpr auto write_padded(OutputIt out, const basic_format_specs<Char>& specs,
  1493. size_t size, F&& f) -> OutputIt {
  1494. return write_padded<align>(out, specs, size, size, f);
  1495. }
  1496. template <align::type align = align::left, typename Char, typename OutputIt>
  1497. FMT_CONSTEXPR auto write_bytes(OutputIt out, string_view bytes,
  1498. const basic_format_specs<Char>& specs)
  1499. -> OutputIt {
  1500. return write_padded<align>(
  1501. out, specs, bytes.size(), [bytes](reserve_iterator<OutputIt> it) {
  1502. const char* data = bytes.data();
  1503. return copy_str<Char>(data, data + bytes.size(), it);
  1504. });
  1505. }
  1506. template <typename Char, typename OutputIt, typename UIntPtr>
  1507. auto write_ptr(OutputIt out, UIntPtr value,
  1508. const basic_format_specs<Char>* specs) -> OutputIt {
  1509. int num_digits = count_digits<4>(value);
  1510. auto size = to_unsigned(num_digits) + size_t(2);
  1511. auto write = [=](reserve_iterator<OutputIt> it) {
  1512. *it++ = static_cast<Char>('0');
  1513. *it++ = static_cast<Char>('x');
  1514. return format_uint<4, Char>(it, value, num_digits);
  1515. };
  1516. return specs ? write_padded<align::right>(out, *specs, size, write)
  1517. : base_iterator(out, write(reserve(out, size)));
  1518. }
  1519. // Returns true iff the code point cp is printable.
  1520. FMT_API auto is_printable(uint32_t cp) -> bool;
  1521. inline auto needs_escape(uint32_t cp) -> bool {
  1522. return cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\' ||
  1523. !is_printable(cp);
  1524. }
  1525. template <typename Char> struct find_escape_result {
  1526. const Char* begin;
  1527. const Char* end;
  1528. uint32_t cp;
  1529. };
  1530. template <typename Char>
  1531. using make_unsigned_char =
  1532. typename conditional_t<std::is_integral<Char>::value,
  1533. std::make_unsigned<Char>,
  1534. type_identity<uint32_t>>::type;
  1535. template <typename Char>
  1536. auto find_escape(const Char* begin, const Char* end)
  1537. -> find_escape_result<Char> {
  1538. for (; begin != end; ++begin) {
  1539. uint32_t cp = static_cast<make_unsigned_char<Char>>(*begin);
  1540. if (const_check(sizeof(Char) == 1) && cp >= 0x80) continue;
  1541. if (needs_escape(cp)) return {begin, begin + 1, cp};
  1542. }
  1543. return {begin, nullptr, 0};
  1544. }
  1545. inline auto find_escape(const char* begin, const char* end)
  1546. -> find_escape_result<char> {
  1547. if (!is_utf8()) return find_escape<char>(begin, end);
  1548. auto result = find_escape_result<char>{end, nullptr, 0};
  1549. for_each_codepoint(string_view(begin, to_unsigned(end - begin)),
  1550. [&](uint32_t cp, string_view sv) {
  1551. if (needs_escape(cp)) {
  1552. result = {sv.begin(), sv.end(), cp};
  1553. return false;
  1554. }
  1555. return true;
  1556. });
  1557. return result;
  1558. }
  1559. #define FMT_STRING_IMPL(s, base, explicit) \
  1560. [] { \
  1561. /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \
  1562. /* Use a macro-like name to avoid shadowing warnings. */ \
  1563. struct FMT_GCC_VISIBILITY_HIDDEN FMT_COMPILE_STRING : base { \
  1564. using char_type FMT_MAYBE_UNUSED = fmt::remove_cvref_t<decltype(s[0])>; \
  1565. FMT_MAYBE_UNUSED FMT_CONSTEXPR explicit \
  1566. operator fmt::basic_string_view<char_type>() const { \
  1567. return fmt::detail_exported::compile_string_to_view<char_type>(s); \
  1568. } \
  1569. }; \
  1570. return FMT_COMPILE_STRING(); \
  1571. }()
  1572. /**
  1573. \rst
  1574. Constructs a compile-time format string from a string literal *s*.
  1575. **Example**::
  1576. // A compile-time error because 'd' is an invalid specifier for strings.
  1577. std::string s = fmt::format(FMT_STRING("{:d}"), "foo");
  1578. \endrst
  1579. */
  1580. #define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::detail::compile_string, )
  1581. template <size_t width, typename Char, typename OutputIt>
  1582. auto write_codepoint(OutputIt out, char prefix, uint32_t cp) -> OutputIt {
  1583. *out++ = static_cast<Char>('\\');
  1584. *out++ = static_cast<Char>(prefix);
  1585. Char buf[width];
  1586. fill_n(buf, width, static_cast<Char>('0'));
  1587. format_uint<4>(buf, cp, width);
  1588. return copy_str<Char>(buf, buf + width, out);
  1589. }
  1590. template <typename OutputIt, typename Char>
  1591. auto write_escaped_cp(OutputIt out, const find_escape_result<Char>& escape)
  1592. -> OutputIt {
  1593. auto c = static_cast<Char>(escape.cp);
  1594. switch (escape.cp) {
  1595. case '\n':
  1596. *out++ = static_cast<Char>('\\');
  1597. c = static_cast<Char>('n');
  1598. break;
  1599. case '\r':
  1600. *out++ = static_cast<Char>('\\');
  1601. c = static_cast<Char>('r');
  1602. break;
  1603. case '\t':
  1604. *out++ = static_cast<Char>('\\');
  1605. c = static_cast<Char>('t');
  1606. break;
  1607. case '"':
  1608. FMT_FALLTHROUGH;
  1609. case '\'':
  1610. FMT_FALLTHROUGH;
  1611. case '\\':
  1612. *out++ = static_cast<Char>('\\');
  1613. break;
  1614. default:
  1615. if (is_utf8()) {
  1616. if (escape.cp < 0x100) {
  1617. return write_codepoint<2, Char>(out, 'x', escape.cp);
  1618. }
  1619. if (escape.cp < 0x10000) {
  1620. return write_codepoint<4, Char>(out, 'u', escape.cp);
  1621. }
  1622. if (escape.cp < 0x110000) {
  1623. return write_codepoint<8, Char>(out, 'U', escape.cp);
  1624. }
  1625. }
  1626. for (Char escape_char : basic_string_view<Char>(
  1627. escape.begin, to_unsigned(escape.end - escape.begin))) {
  1628. out = write_codepoint<2, Char>(out, 'x',
  1629. static_cast<uint32_t>(escape_char) & 0xFF);
  1630. }
  1631. return out;
  1632. }
  1633. *out++ = c;
  1634. return out;
  1635. }
  1636. template <typename Char, typename OutputIt>
  1637. auto write_escaped_string(OutputIt out, basic_string_view<Char> str)
  1638. -> OutputIt {
  1639. *out++ = static_cast<Char>('"');
  1640. auto begin = str.begin(), end = str.end();
  1641. do {
  1642. auto escape = find_escape(begin, end);
  1643. out = copy_str<Char>(begin, escape.begin, out);
  1644. begin = escape.end;
  1645. if (!begin) break;
  1646. out = write_escaped_cp<OutputIt, Char>(out, escape);
  1647. } while (begin != end);
  1648. *out++ = static_cast<Char>('"');
  1649. return out;
  1650. }
  1651. template <typename Char, typename OutputIt>
  1652. auto write_escaped_char(OutputIt out, Char v) -> OutputIt {
  1653. *out++ = static_cast<Char>('\'');
  1654. if ((needs_escape(static_cast<uint32_t>(v)) && v != static_cast<Char>('"')) ||
  1655. v == static_cast<Char>('\'')) {
  1656. out = write_escaped_cp(
  1657. out, find_escape_result<Char>{&v, &v + 1, static_cast<uint32_t>(v)});
  1658. } else {
  1659. *out++ = v;
  1660. }
  1661. *out++ = static_cast<Char>('\'');
  1662. return out;
  1663. }
  1664. template <typename Char, typename OutputIt>
  1665. FMT_CONSTEXPR auto write_char(OutputIt out, Char value,
  1666. const basic_format_specs<Char>& specs)
  1667. -> OutputIt {
  1668. bool is_debug = specs.type == presentation_type::debug;
  1669. return write_padded(out, specs, 1, [=](reserve_iterator<OutputIt> it) {
  1670. if (is_debug) return write_escaped_char(it, value);
  1671. *it++ = value;
  1672. return it;
  1673. });
  1674. }
  1675. template <typename Char, typename OutputIt>
  1676. FMT_CONSTEXPR auto write(OutputIt out, Char value,
  1677. const basic_format_specs<Char>& specs,
  1678. locale_ref loc = {}) -> OutputIt {
  1679. return check_char_specs(specs)
  1680. ? write_char(out, value, specs)
  1681. : write(out, static_cast<int>(value), specs, loc);
  1682. }
  1683. // Data for write_int that doesn't depend on output iterator type. It is used to
  1684. // avoid template code bloat.
  1685. template <typename Char> struct write_int_data {
  1686. size_t size;
  1687. size_t padding;
  1688. FMT_CONSTEXPR write_int_data(int num_digits, unsigned prefix,
  1689. const basic_format_specs<Char>& specs)
  1690. : size((prefix >> 24) + to_unsigned(num_digits)), padding(0) {
  1691. if (specs.align == align::numeric) {
  1692. auto width = to_unsigned(specs.width);
  1693. if (width > size) {
  1694. padding = width - size;
  1695. size = width;
  1696. }
  1697. } else if (specs.precision > num_digits) {
  1698. size = (prefix >> 24) + to_unsigned(specs.precision);
  1699. padding = to_unsigned(specs.precision - num_digits);
  1700. }
  1701. }
  1702. };
  1703. // Writes an integer in the format
  1704. // <left-padding><prefix><numeric-padding><digits><right-padding>
  1705. // where <digits> are written by write_digits(it).
  1706. // prefix contains chars in three lower bytes and the size in the fourth byte.
  1707. template <typename OutputIt, typename Char, typename W>
  1708. FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, int num_digits,
  1709. unsigned prefix,
  1710. const basic_format_specs<Char>& specs,
  1711. W write_digits) -> OutputIt {
  1712. // Slightly faster check for specs.width == 0 && specs.precision == -1.
  1713. if ((specs.width | (specs.precision + 1)) == 0) {
  1714. auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24));
  1715. if (prefix != 0) {
  1716. for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
  1717. *it++ = static_cast<Char>(p & 0xff);
  1718. }
  1719. return base_iterator(out, write_digits(it));
  1720. }
  1721. auto data = write_int_data<Char>(num_digits, prefix, specs);
  1722. return write_padded<align::right>(
  1723. out, specs, data.size, [=](reserve_iterator<OutputIt> it) {
  1724. for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
  1725. *it++ = static_cast<Char>(p & 0xff);
  1726. it = detail::fill_n(it, data.padding, static_cast<Char>('0'));
  1727. return write_digits(it);
  1728. });
  1729. }
  1730. template <typename Char> class digit_grouping {
  1731. private:
  1732. thousands_sep_result<Char> sep_;
  1733. struct next_state {
  1734. std::string::const_iterator group;
  1735. int pos;
  1736. };
  1737. next_state initial_state() const { return {sep_.grouping.begin(), 0}; }
  1738. // Returns the next digit group separator position.
  1739. int next(next_state& state) const {
  1740. if (!sep_.thousands_sep) return max_value<int>();
  1741. if (state.group == sep_.grouping.end())
  1742. return state.pos += sep_.grouping.back();
  1743. if (*state.group <= 0 || *state.group == max_value<char>())
  1744. return max_value<int>();
  1745. state.pos += *state.group++;
  1746. return state.pos;
  1747. }
  1748. public:
  1749. explicit digit_grouping(locale_ref loc, bool localized = true) {
  1750. if (localized)
  1751. sep_ = thousands_sep<Char>(loc);
  1752. else
  1753. sep_.thousands_sep = Char();
  1754. }
  1755. explicit digit_grouping(thousands_sep_result<Char> sep) : sep_(sep) {}
  1756. Char separator() const { return sep_.thousands_sep; }
  1757. int count_separators(int num_digits) const {
  1758. int count = 0;
  1759. auto state = initial_state();
  1760. while (num_digits > next(state)) ++count;
  1761. return count;
  1762. }
  1763. // Applies grouping to digits and write the output to out.
  1764. template <typename Out, typename C>
  1765. Out apply(Out out, basic_string_view<C> digits) const {
  1766. auto num_digits = static_cast<int>(digits.size());
  1767. auto separators = basic_memory_buffer<int>();
  1768. separators.push_back(0);
  1769. auto state = initial_state();
  1770. while (int i = next(state)) {
  1771. if (i >= num_digits) break;
  1772. separators.push_back(i);
  1773. }
  1774. for (int i = 0, sep_index = static_cast<int>(separators.size() - 1);
  1775. i < num_digits; ++i) {
  1776. if (num_digits - i == separators[sep_index]) {
  1777. *out++ = separator();
  1778. --sep_index;
  1779. }
  1780. *out++ = static_cast<Char>(digits[to_unsigned(i)]);
  1781. }
  1782. return out;
  1783. }
  1784. };
  1785. template <typename OutputIt, typename UInt, typename Char>
  1786. auto write_int_localized(OutputIt out, UInt value, unsigned prefix,
  1787. const basic_format_specs<Char>& specs,
  1788. const digit_grouping<Char>& grouping) -> OutputIt {
  1789. static_assert(std::is_same<uint64_or_128_t<UInt>, UInt>::value, "");
  1790. int num_digits = count_digits(value);
  1791. char digits[40];
  1792. format_decimal(digits, value, num_digits);
  1793. unsigned size = to_unsigned((prefix != 0 ? 1 : 0) + num_digits +
  1794. grouping.count_separators(num_digits));
  1795. return write_padded<align::right>(
  1796. out, specs, size, size, [&](reserve_iterator<OutputIt> it) {
  1797. if (prefix != 0) {
  1798. char sign = static_cast<char>(prefix);
  1799. *it++ = static_cast<Char>(sign);
  1800. }
  1801. return grouping.apply(it, string_view(digits, to_unsigned(num_digits)));
  1802. });
  1803. }
  1804. template <typename OutputIt, typename UInt, typename Char>
  1805. auto write_int_localized(OutputIt& out, UInt value, unsigned prefix,
  1806. const basic_format_specs<Char>& specs, locale_ref loc)
  1807. -> bool {
  1808. auto grouping = digit_grouping<Char>(loc);
  1809. out = write_int_localized(out, value, prefix, specs, grouping);
  1810. return true;
  1811. }
  1812. FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) {
  1813. prefix |= prefix != 0 ? value << 8 : value;
  1814. prefix += (1u + (value > 0xff ? 1 : 0)) << 24;
  1815. }
  1816. template <typename UInt> struct write_int_arg {
  1817. UInt abs_value;
  1818. unsigned prefix;
  1819. };
  1820. template <typename T>
  1821. FMT_CONSTEXPR auto make_write_int_arg(T value, sign_t sign)
  1822. -> write_int_arg<uint32_or_64_or_128_t<T>> {
  1823. auto prefix = 0u;
  1824. auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
  1825. if (is_negative(value)) {
  1826. prefix = 0x01000000 | '-';
  1827. abs_value = 0 - abs_value;
  1828. } else {
  1829. constexpr const unsigned prefixes[4] = {0, 0, 0x1000000u | '+',
  1830. 0x1000000u | ' '};
  1831. prefix = prefixes[sign];
  1832. }
  1833. return {abs_value, prefix};
  1834. }
  1835. template <typename Char, typename OutputIt, typename T>
  1836. FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, write_int_arg<T> arg,
  1837. const basic_format_specs<Char>& specs,
  1838. locale_ref loc) -> OutputIt {
  1839. static_assert(std::is_same<T, uint32_or_64_or_128_t<T>>::value, "");
  1840. auto abs_value = arg.abs_value;
  1841. auto prefix = arg.prefix;
  1842. switch (specs.type) {
  1843. case presentation_type::none:
  1844. case presentation_type::dec: {
  1845. if (specs.localized &&
  1846. write_int_localized(out, static_cast<uint64_or_128_t<T>>(abs_value),
  1847. prefix, specs, loc)) {
  1848. return out;
  1849. }
  1850. auto num_digits = count_digits(abs_value);
  1851. return write_int(
  1852. out, num_digits, prefix, specs, [=](reserve_iterator<OutputIt> it) {
  1853. return format_decimal<Char>(it, abs_value, num_digits).end;
  1854. });
  1855. }
  1856. case presentation_type::hex_lower:
  1857. case presentation_type::hex_upper: {
  1858. bool upper = specs.type == presentation_type::hex_upper;
  1859. if (specs.alt)
  1860. prefix_append(prefix, unsigned(upper ? 'X' : 'x') << 8 | '0');
  1861. int num_digits = count_digits<4>(abs_value);
  1862. return write_int(
  1863. out, num_digits, prefix, specs, [=](reserve_iterator<OutputIt> it) {
  1864. return format_uint<4, Char>(it, abs_value, num_digits, upper);
  1865. });
  1866. }
  1867. case presentation_type::bin_lower:
  1868. case presentation_type::bin_upper: {
  1869. bool upper = specs.type == presentation_type::bin_upper;
  1870. if (specs.alt)
  1871. prefix_append(prefix, unsigned(upper ? 'B' : 'b') << 8 | '0');
  1872. int num_digits = count_digits<1>(abs_value);
  1873. return write_int(out, num_digits, prefix, specs,
  1874. [=](reserve_iterator<OutputIt> it) {
  1875. return format_uint<1, Char>(it, abs_value, num_digits);
  1876. });
  1877. }
  1878. case presentation_type::oct: {
  1879. int num_digits = count_digits<3>(abs_value);
  1880. // Octal prefix '0' is counted as a digit, so only add it if precision
  1881. // is not greater than the number of digits.
  1882. if (specs.alt && specs.precision <= num_digits && abs_value != 0)
  1883. prefix_append(prefix, '0');
  1884. return write_int(out, num_digits, prefix, specs,
  1885. [=](reserve_iterator<OutputIt> it) {
  1886. return format_uint<3, Char>(it, abs_value, num_digits);
  1887. });
  1888. }
  1889. case presentation_type::chr:
  1890. return write_char(out, static_cast<Char>(abs_value), specs);
  1891. default:
  1892. throw_format_error("invalid type specifier");
  1893. }
  1894. return out;
  1895. }
  1896. template <typename Char, typename OutputIt, typename T>
  1897. FMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline(
  1898. OutputIt out, write_int_arg<T> arg, const basic_format_specs<Char>& specs,
  1899. locale_ref loc) -> OutputIt {
  1900. return write_int(out, arg, specs, loc);
  1901. }
  1902. template <typename Char, typename OutputIt, typename T,
  1903. FMT_ENABLE_IF(is_integral<T>::value &&
  1904. !std::is_same<T, bool>::value &&
  1905. std::is_same<OutputIt, buffer_appender<Char>>::value)>
  1906. FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value,
  1907. const basic_format_specs<Char>& specs,
  1908. locale_ref loc) -> OutputIt {
  1909. return write_int_noinline(out, make_write_int_arg(value, specs.sign), specs,
  1910. loc);
  1911. }
  1912. // An inlined version of write used in format string compilation.
  1913. template <typename Char, typename OutputIt, typename T,
  1914. FMT_ENABLE_IF(is_integral<T>::value &&
  1915. !std::is_same<T, bool>::value &&
  1916. !std::is_same<OutputIt, buffer_appender<Char>>::value)>
  1917. FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value,
  1918. const basic_format_specs<Char>& specs,
  1919. locale_ref loc) -> OutputIt {
  1920. return write_int(out, make_write_int_arg(value, specs.sign), specs, loc);
  1921. }
  1922. // An output iterator that counts the number of objects written to it and
  1923. // discards them.
  1924. class counting_iterator {
  1925. private:
  1926. size_t count_;
  1927. public:
  1928. using iterator_category = std::output_iterator_tag;
  1929. using difference_type = std::ptrdiff_t;
  1930. using pointer = void;
  1931. using reference = void;
  1932. FMT_UNCHECKED_ITERATOR(counting_iterator);
  1933. struct value_type {
  1934. template <typename T> FMT_CONSTEXPR void operator=(const T&) {}
  1935. };
  1936. FMT_CONSTEXPR counting_iterator() : count_(0) {}
  1937. FMT_CONSTEXPR size_t count() const { return count_; }
  1938. FMT_CONSTEXPR counting_iterator& operator++() {
  1939. ++count_;
  1940. return *this;
  1941. }
  1942. FMT_CONSTEXPR counting_iterator operator++(int) {
  1943. auto it = *this;
  1944. ++*this;
  1945. return it;
  1946. }
  1947. FMT_CONSTEXPR friend counting_iterator operator+(counting_iterator it,
  1948. difference_type n) {
  1949. it.count_ += static_cast<size_t>(n);
  1950. return it;
  1951. }
  1952. FMT_CONSTEXPR value_type operator*() const { return {}; }
  1953. };
  1954. template <typename Char, typename OutputIt>
  1955. FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,
  1956. const basic_format_specs<Char>& specs) -> OutputIt {
  1957. auto data = s.data();
  1958. auto size = s.size();
  1959. if (specs.precision >= 0 && to_unsigned(specs.precision) < size)
  1960. size = code_point_index(s, to_unsigned(specs.precision));
  1961. bool is_debug = specs.type == presentation_type::debug;
  1962. size_t width = 0;
  1963. if (specs.width != 0) {
  1964. if (is_debug)
  1965. width = write_escaped_string(counting_iterator{}, s).count();
  1966. else
  1967. width = compute_width(basic_string_view<Char>(data, size));
  1968. }
  1969. return write_padded(out, specs, size, width,
  1970. [=](reserve_iterator<OutputIt> it) {
  1971. if (is_debug) return write_escaped_string(it, s);
  1972. return copy_str<Char>(data, data + size, it);
  1973. });
  1974. }
  1975. template <typename Char, typename OutputIt>
  1976. FMT_CONSTEXPR auto write(OutputIt out,
  1977. basic_string_view<type_identity_t<Char>> s,
  1978. const basic_format_specs<Char>& specs, locale_ref)
  1979. -> OutputIt {
  1980. check_string_type_spec(specs.type);
  1981. return write(out, s, specs);
  1982. }
  1983. template <typename Char, typename OutputIt>
  1984. FMT_CONSTEXPR auto write(OutputIt out, const Char* s,
  1985. const basic_format_specs<Char>& specs, locale_ref)
  1986. -> OutputIt {
  1987. return check_cstring_type_spec(specs.type)
  1988. ? write(out, basic_string_view<Char>(s), specs, {})
  1989. : write_ptr<Char>(out, bit_cast<uintptr_t>(s), &specs);
  1990. }
  1991. template <typename Char, typename OutputIt, typename T,
  1992. FMT_ENABLE_IF(is_integral<T>::value &&
  1993. !std::is_same<T, bool>::value &&
  1994. !std::is_same<T, Char>::value)>
  1995. FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
  1996. auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
  1997. bool negative = is_negative(value);
  1998. // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer.
  1999. if (negative) abs_value = ~abs_value + 1;
  2000. int num_digits = count_digits(abs_value);
  2001. auto size = (negative ? 1 : 0) + static_cast<size_t>(num_digits);
  2002. auto it = reserve(out, size);
  2003. if (auto ptr = to_pointer<Char>(it, size)) {
  2004. if (negative) *ptr++ = static_cast<Char>('-');
  2005. format_decimal<Char>(ptr, abs_value, num_digits);
  2006. return out;
  2007. }
  2008. if (negative) *it++ = static_cast<Char>('-');
  2009. it = format_decimal<Char>(it, abs_value, num_digits).end;
  2010. return base_iterator(out, it);
  2011. }
  2012. template <typename Char, typename OutputIt>
  2013. FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isnan,
  2014. basic_format_specs<Char> specs,
  2015. const float_specs& fspecs) -> OutputIt {
  2016. auto str =
  2017. isnan ? (fspecs.upper ? "NAN" : "nan") : (fspecs.upper ? "INF" : "inf");
  2018. constexpr size_t str_size = 3;
  2019. auto sign = fspecs.sign;
  2020. auto size = str_size + (sign ? 1 : 0);
  2021. // Replace '0'-padding with space for non-finite values.
  2022. const bool is_zero_fill =
  2023. specs.fill.size() == 1 && *specs.fill.data() == static_cast<Char>('0');
  2024. if (is_zero_fill) specs.fill[0] = static_cast<Char>(' ');
  2025. return write_padded(out, specs, size, [=](reserve_iterator<OutputIt> it) {
  2026. if (sign) *it++ = detail::sign<Char>(sign);
  2027. return copy_str<Char>(str, str + str_size, it);
  2028. });
  2029. }
  2030. // A decimal floating-point number significand * pow(10, exp).
  2031. struct big_decimal_fp {
  2032. const char* significand;
  2033. int significand_size;
  2034. int exponent;
  2035. };
  2036. constexpr auto get_significand_size(const big_decimal_fp& f) -> int {
  2037. return f.significand_size;
  2038. }
  2039. template <typename T>
  2040. inline auto get_significand_size(const dragonbox::decimal_fp<T>& f) -> int {
  2041. return count_digits(f.significand);
  2042. }
  2043. template <typename Char, typename OutputIt>
  2044. constexpr auto write_significand(OutputIt out, const char* significand,
  2045. int significand_size) -> OutputIt {
  2046. return copy_str<Char>(significand, significand + significand_size, out);
  2047. }
  2048. template <typename Char, typename OutputIt, typename UInt>
  2049. inline auto write_significand(OutputIt out, UInt significand,
  2050. int significand_size) -> OutputIt {
  2051. return format_decimal<Char>(out, significand, significand_size).end;
  2052. }
  2053. template <typename Char, typename OutputIt, typename T, typename Grouping>
  2054. FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
  2055. int significand_size, int exponent,
  2056. const Grouping& grouping) -> OutputIt {
  2057. if (!grouping.separator()) {
  2058. out = write_significand<Char>(out, significand, significand_size);
  2059. return detail::fill_n(out, exponent, static_cast<Char>('0'));
  2060. }
  2061. auto buffer = memory_buffer();
  2062. write_significand<char>(appender(buffer), significand, significand_size);
  2063. detail::fill_n(appender(buffer), exponent, '0');
  2064. return grouping.apply(out, string_view(buffer.data(), buffer.size()));
  2065. }
  2066. template <typename Char, typename UInt,
  2067. FMT_ENABLE_IF(std::is_integral<UInt>::value)>
  2068. inline auto write_significand(Char* out, UInt significand, int significand_size,
  2069. int integral_size, Char decimal_point) -> Char* {
  2070. if (!decimal_point)
  2071. return format_decimal(out, significand, significand_size).end;
  2072. out += significand_size + 1;
  2073. Char* end = out;
  2074. int floating_size = significand_size - integral_size;
  2075. for (int i = floating_size / 2; i > 0; --i) {
  2076. out -= 2;
  2077. copy2(out, digits2(static_cast<std::size_t>(significand % 100)));
  2078. significand /= 100;
  2079. }
  2080. if (floating_size % 2 != 0) {
  2081. *--out = static_cast<Char>('0' + significand % 10);
  2082. significand /= 10;
  2083. }
  2084. *--out = decimal_point;
  2085. format_decimal(out - integral_size, significand, integral_size);
  2086. return end;
  2087. }
  2088. template <typename OutputIt, typename UInt, typename Char,
  2089. FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<OutputIt>>::value)>
  2090. inline auto write_significand(OutputIt out, UInt significand,
  2091. int significand_size, int integral_size,
  2092. Char decimal_point) -> OutputIt {
  2093. // Buffer is large enough to hold digits (digits10 + 1) and a decimal point.
  2094. Char buffer[digits10<UInt>() + 2];
  2095. auto end = write_significand(buffer, significand, significand_size,
  2096. integral_size, decimal_point);
  2097. return detail::copy_str_noinline<Char>(buffer, end, out);
  2098. }
  2099. template <typename OutputIt, typename Char>
  2100. FMT_CONSTEXPR auto write_significand(OutputIt out, const char* significand,
  2101. int significand_size, int integral_size,
  2102. Char decimal_point) -> OutputIt {
  2103. out = detail::copy_str_noinline<Char>(significand,
  2104. significand + integral_size, out);
  2105. if (!decimal_point) return out;
  2106. *out++ = decimal_point;
  2107. return detail::copy_str_noinline<Char>(significand + integral_size,
  2108. significand + significand_size, out);
  2109. }
  2110. template <typename OutputIt, typename Char, typename T, typename Grouping>
  2111. FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
  2112. int significand_size, int integral_size,
  2113. Char decimal_point,
  2114. const Grouping& grouping) -> OutputIt {
  2115. if (!grouping.separator()) {
  2116. return write_significand(out, significand, significand_size, integral_size,
  2117. decimal_point);
  2118. }
  2119. auto buffer = basic_memory_buffer<Char>();
  2120. write_significand(buffer_appender<Char>(buffer), significand,
  2121. significand_size, integral_size, decimal_point);
  2122. grouping.apply(
  2123. out, basic_string_view<Char>(buffer.data(), to_unsigned(integral_size)));
  2124. return detail::copy_str_noinline<Char>(buffer.data() + integral_size,
  2125. buffer.end(), out);
  2126. }
  2127. template <typename OutputIt, typename DecimalFP, typename Char,
  2128. typename Grouping = digit_grouping<Char>>
  2129. FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f,
  2130. const basic_format_specs<Char>& specs,
  2131. float_specs fspecs, locale_ref loc)
  2132. -> OutputIt {
  2133. auto significand = f.significand;
  2134. int significand_size = get_significand_size(f);
  2135. const Char zero = static_cast<Char>('0');
  2136. auto sign = fspecs.sign;
  2137. size_t size = to_unsigned(significand_size) + (sign ? 1 : 0);
  2138. using iterator = reserve_iterator<OutputIt>;
  2139. Char decimal_point =
  2140. fspecs.locale ? detail::decimal_point<Char>(loc) : static_cast<Char>('.');
  2141. int output_exp = f.exponent + significand_size - 1;
  2142. auto use_exp_format = [=]() {
  2143. if (fspecs.format == float_format::exp) return true;
  2144. if (fspecs.format != float_format::general) return false;
  2145. // Use the fixed notation if the exponent is in [exp_lower, exp_upper),
  2146. // e.g. 0.0001 instead of 1e-04. Otherwise use the exponent notation.
  2147. const int exp_lower = -4, exp_upper = 16;
  2148. return output_exp < exp_lower ||
  2149. output_exp >= (fspecs.precision > 0 ? fspecs.precision : exp_upper);
  2150. };
  2151. if (use_exp_format()) {
  2152. int num_zeros = 0;
  2153. if (fspecs.showpoint) {
  2154. num_zeros = fspecs.precision - significand_size;
  2155. if (num_zeros < 0) num_zeros = 0;
  2156. size += to_unsigned(num_zeros);
  2157. } else if (significand_size == 1) {
  2158. decimal_point = Char();
  2159. }
  2160. auto abs_output_exp = output_exp >= 0 ? output_exp : -output_exp;
  2161. int exp_digits = 2;
  2162. if (abs_output_exp >= 100) exp_digits = abs_output_exp >= 1000 ? 4 : 3;
  2163. size += to_unsigned((decimal_point ? 1 : 0) + 2 + exp_digits);
  2164. char exp_char = fspecs.upper ? 'E' : 'e';
  2165. auto write = [=](iterator it) {
  2166. if (sign) *it++ = detail::sign<Char>(sign);
  2167. // Insert a decimal point after the first digit and add an exponent.
  2168. it = write_significand(it, significand, significand_size, 1,
  2169. decimal_point);
  2170. if (num_zeros > 0) it = detail::fill_n(it, num_zeros, zero);
  2171. *it++ = static_cast<Char>(exp_char);
  2172. return write_exponent<Char>(output_exp, it);
  2173. };
  2174. return specs.width > 0 ? write_padded<align::right>(out, specs, size, write)
  2175. : base_iterator(out, write(reserve(out, size)));
  2176. }
  2177. int exp = f.exponent + significand_size;
  2178. if (f.exponent >= 0) {
  2179. // 1234e5 -> 123400000[.0+]
  2180. size += to_unsigned(f.exponent);
  2181. int num_zeros = fspecs.precision - exp;
  2182. abort_fuzzing_if(num_zeros > 5000);
  2183. if (fspecs.showpoint) {
  2184. ++size;
  2185. if (num_zeros <= 0 && fspecs.format != float_format::fixed) num_zeros = 1;
  2186. if (num_zeros > 0) size += to_unsigned(num_zeros);
  2187. }
  2188. auto grouping = Grouping(loc, fspecs.locale);
  2189. size += to_unsigned(grouping.count_separators(exp));
  2190. return write_padded<align::right>(out, specs, size, [&](iterator it) {
  2191. if (sign) *it++ = detail::sign<Char>(sign);
  2192. it = write_significand<Char>(it, significand, significand_size,
  2193. f.exponent, grouping);
  2194. if (!fspecs.showpoint) return it;
  2195. *it++ = decimal_point;
  2196. return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it;
  2197. });
  2198. } else if (exp > 0) {
  2199. // 1234e-2 -> 12.34[0+]
  2200. int num_zeros = fspecs.showpoint ? fspecs.precision - significand_size : 0;
  2201. size += 1 + to_unsigned(num_zeros > 0 ? num_zeros : 0);
  2202. auto grouping = Grouping(loc, fspecs.locale);
  2203. size += to_unsigned(grouping.count_separators(significand_size));
  2204. return write_padded<align::right>(out, specs, size, [&](iterator it) {
  2205. if (sign) *it++ = detail::sign<Char>(sign);
  2206. it = write_significand(it, significand, significand_size, exp,
  2207. decimal_point, grouping);
  2208. return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it;
  2209. });
  2210. }
  2211. // 1234e-6 -> 0.001234
  2212. int num_zeros = -exp;
  2213. if (significand_size == 0 && fspecs.precision >= 0 &&
  2214. fspecs.precision < num_zeros) {
  2215. num_zeros = fspecs.precision;
  2216. }
  2217. bool pointy = num_zeros != 0 || significand_size != 0 || fspecs.showpoint;
  2218. size += 1 + (pointy ? 1 : 0) + to_unsigned(num_zeros);
  2219. return write_padded<align::right>(out, specs, size, [&](iterator it) {
  2220. if (sign) *it++ = detail::sign<Char>(sign);
  2221. *it++ = zero;
  2222. if (!pointy) return it;
  2223. *it++ = decimal_point;
  2224. it = detail::fill_n(it, num_zeros, zero);
  2225. return write_significand<Char>(it, significand, significand_size);
  2226. });
  2227. }
  2228. template <typename Char> class fallback_digit_grouping {
  2229. public:
  2230. constexpr fallback_digit_grouping(locale_ref, bool) {}
  2231. constexpr Char separator() const { return Char(); }
  2232. constexpr int count_separators(int) const { return 0; }
  2233. template <typename Out, typename C>
  2234. constexpr Out apply(Out out, basic_string_view<C>) const {
  2235. return out;
  2236. }
  2237. };
  2238. template <typename OutputIt, typename DecimalFP, typename Char>
  2239. FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& f,
  2240. const basic_format_specs<Char>& specs,
  2241. float_specs fspecs, locale_ref loc)
  2242. -> OutputIt {
  2243. if (is_constant_evaluated()) {
  2244. return do_write_float<OutputIt, DecimalFP, Char,
  2245. fallback_digit_grouping<Char>>(out, f, specs, fspecs,
  2246. loc);
  2247. } else {
  2248. return do_write_float(out, f, specs, fspecs, loc);
  2249. }
  2250. }
  2251. template <typename T> constexpr bool isnan(T value) {
  2252. return !(value >= value); // std::isnan doesn't support __float128.
  2253. }
  2254. template <typename T, typename Enable = void>
  2255. struct has_isfinite : std::false_type {};
  2256. template <typename T>
  2257. struct has_isfinite<T, enable_if_t<sizeof(std::isfinite(T())) != 0>>
  2258. : std::true_type {};
  2259. template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value&&
  2260. has_isfinite<T>::value)>
  2261. FMT_CONSTEXPR20 bool isfinite(T value) {
  2262. constexpr T inf = T(std::numeric_limits<double>::infinity());
  2263. if (is_constant_evaluated())
  2264. return !detail::isnan(value) && value != inf && value != -inf;
  2265. return std::isfinite(value);
  2266. }
  2267. template <typename T, FMT_ENABLE_IF(!has_isfinite<T>::value)>
  2268. FMT_CONSTEXPR bool isfinite(T value) {
  2269. T inf = T(std::numeric_limits<double>::infinity());
  2270. // std::isfinite doesn't support __float128.
  2271. return !detail::isnan(value) && value != inf && value != -inf;
  2272. }
  2273. template <typename T, FMT_ENABLE_IF(is_floating_point<T>::value)>
  2274. FMT_INLINE FMT_CONSTEXPR bool signbit(T value) {
  2275. if (is_constant_evaluated()) {
  2276. #ifdef __cpp_if_constexpr
  2277. if constexpr (std::numeric_limits<double>::is_iec559) {
  2278. auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
  2279. return (bits >> (num_bits<uint64_t>() - 1)) != 0;
  2280. }
  2281. #endif
  2282. }
  2283. return std::signbit(static_cast<double>(value));
  2284. }
  2285. enum class round_direction { unknown, up, down };
  2286. // Given the divisor (normally a power of 10), the remainder = v % divisor for
  2287. // some number v and the error, returns whether v should be rounded up, down, or
  2288. // whether the rounding direction can't be determined due to error.
  2289. // error should be less than divisor / 2.
  2290. FMT_CONSTEXPR inline round_direction get_round_direction(uint64_t divisor,
  2291. uint64_t remainder,
  2292. uint64_t error) {
  2293. FMT_ASSERT(remainder < divisor, ""); // divisor - remainder won't overflow.
  2294. FMT_ASSERT(error < divisor, ""); // divisor - error won't overflow.
  2295. FMT_ASSERT(error < divisor - error, ""); // error * 2 won't overflow.
  2296. // Round down if (remainder + error) * 2 <= divisor.
  2297. if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2)
  2298. return round_direction::down;
  2299. // Round up if (remainder - error) * 2 >= divisor.
  2300. if (remainder >= error &&
  2301. remainder - error >= divisor - (remainder - error)) {
  2302. return round_direction::up;
  2303. }
  2304. return round_direction::unknown;
  2305. }
  2306. namespace digits {
  2307. enum result {
  2308. more, // Generate more digits.
  2309. done, // Done generating digits.
  2310. error // Digit generation cancelled due to an error.
  2311. };
  2312. }
  2313. struct gen_digits_handler {
  2314. char* buf;
  2315. int size;
  2316. int precision;
  2317. int exp10;
  2318. bool fixed;
  2319. FMT_CONSTEXPR digits::result on_digit(char digit, uint64_t divisor,
  2320. uint64_t remainder, uint64_t error,
  2321. bool integral) {
  2322. FMT_ASSERT(remainder < divisor, "");
  2323. buf[size++] = digit;
  2324. if (!integral && error >= remainder) return digits::error;
  2325. if (size < precision) return digits::more;
  2326. if (!integral) {
  2327. // Check if error * 2 < divisor with overflow prevention.
  2328. // The check is not needed for the integral part because error = 1
  2329. // and divisor > (1 << 32) there.
  2330. if (error >= divisor || error >= divisor - error) return digits::error;
  2331. } else {
  2332. FMT_ASSERT(error == 1 && divisor > 2, "");
  2333. }
  2334. auto dir = get_round_direction(divisor, remainder, error);
  2335. if (dir != round_direction::up)
  2336. return dir == round_direction::down ? digits::done : digits::error;
  2337. ++buf[size - 1];
  2338. for (int i = size - 1; i > 0 && buf[i] > '9'; --i) {
  2339. buf[i] = '0';
  2340. ++buf[i - 1];
  2341. }
  2342. if (buf[0] > '9') {
  2343. buf[0] = '1';
  2344. if (fixed)
  2345. buf[size++] = '0';
  2346. else
  2347. ++exp10;
  2348. }
  2349. return digits::done;
  2350. }
  2351. };
  2352. inline FMT_CONSTEXPR20 void adjust_precision(int& precision, int exp10) {
  2353. // Adjust fixed precision by exponent because it is relative to decimal
  2354. // point.
  2355. if (exp10 > 0 && precision > max_value<int>() - exp10)
  2356. FMT_THROW(format_error("number is too big"));
  2357. precision += exp10;
  2358. }
  2359. // Generates output using the Grisu digit-gen algorithm.
  2360. // error: the size of the region (lower, upper) outside of which numbers
  2361. // definitely do not round to value (Delta in Grisu3).
  2362. FMT_INLINE FMT_CONSTEXPR20 auto grisu_gen_digits(fp value, uint64_t error,
  2363. int& exp,
  2364. gen_digits_handler& handler)
  2365. -> digits::result {
  2366. const fp one(1ULL << -value.e, value.e);
  2367. // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be
  2368. // zero because it contains a product of two 64-bit numbers with MSB set (due
  2369. // to normalization) - 1, shifted right by at most 60 bits.
  2370. auto integral = static_cast<uint32_t>(value.f >> -one.e);
  2371. FMT_ASSERT(integral != 0, "");
  2372. FMT_ASSERT(integral == value.f >> -one.e, "");
  2373. // The fractional part of scaled value (p2 in Grisu) c = value % one.
  2374. uint64_t fractional = value.f & (one.f - 1);
  2375. exp = count_digits(integral); // kappa in Grisu.
  2376. // Non-fixed formats require at least one digit and no precision adjustment.
  2377. if (handler.fixed) {
  2378. adjust_precision(handler.precision, exp + handler.exp10);
  2379. // Check if precision is satisfied just by leading zeros, e.g.
  2380. // format("{:.2f}", 0.001) gives "0.00" without generating any digits.
  2381. if (handler.precision <= 0) {
  2382. if (handler.precision < 0) return digits::done;
  2383. // Divide by 10 to prevent overflow.
  2384. uint64_t divisor = data::power_of_10_64[exp - 1] << -one.e;
  2385. auto dir = get_round_direction(divisor, value.f / 10, error * 10);
  2386. if (dir == round_direction::unknown) return digits::error;
  2387. handler.buf[handler.size++] = dir == round_direction::up ? '1' : '0';
  2388. return digits::done;
  2389. }
  2390. }
  2391. // Generate digits for the integral part. This can produce up to 10 digits.
  2392. do {
  2393. uint32_t digit = 0;
  2394. auto divmod_integral = [&](uint32_t divisor) {
  2395. digit = integral / divisor;
  2396. integral %= divisor;
  2397. };
  2398. // This optimization by Milo Yip reduces the number of integer divisions by
  2399. // one per iteration.
  2400. switch (exp) {
  2401. case 10:
  2402. divmod_integral(1000000000);
  2403. break;
  2404. case 9:
  2405. divmod_integral(100000000);
  2406. break;
  2407. case 8:
  2408. divmod_integral(10000000);
  2409. break;
  2410. case 7:
  2411. divmod_integral(1000000);
  2412. break;
  2413. case 6:
  2414. divmod_integral(100000);
  2415. break;
  2416. case 5:
  2417. divmod_integral(10000);
  2418. break;
  2419. case 4:
  2420. divmod_integral(1000);
  2421. break;
  2422. case 3:
  2423. divmod_integral(100);
  2424. break;
  2425. case 2:
  2426. divmod_integral(10);
  2427. break;
  2428. case 1:
  2429. digit = integral;
  2430. integral = 0;
  2431. break;
  2432. default:
  2433. FMT_ASSERT(false, "invalid number of digits");
  2434. }
  2435. --exp;
  2436. auto remainder = (static_cast<uint64_t>(integral) << -one.e) + fractional;
  2437. auto result = handler.on_digit(static_cast<char>('0' + digit),
  2438. data::power_of_10_64[exp] << -one.e,
  2439. remainder, error, true);
  2440. if (result != digits::more) return result;
  2441. } while (exp > 0);
  2442. // Generate digits for the fractional part.
  2443. for (;;) {
  2444. fractional *= 10;
  2445. error *= 10;
  2446. char digit = static_cast<char>('0' + (fractional >> -one.e));
  2447. fractional &= one.f - 1;
  2448. --exp;
  2449. auto result = handler.on_digit(digit, one.f, fractional, error, false);
  2450. if (result != digits::more) return result;
  2451. }
  2452. }
  2453. class bigint {
  2454. private:
  2455. // A bigint is stored as an array of bigits (big digits), with bigit at index
  2456. // 0 being the least significant one.
  2457. using bigit = uint32_t;
  2458. using double_bigit = uint64_t;
  2459. enum { bigits_capacity = 32 };
  2460. basic_memory_buffer<bigit, bigits_capacity> bigits_;
  2461. int exp_;
  2462. FMT_CONSTEXPR20 bigit operator[](int index) const {
  2463. return bigits_[to_unsigned(index)];
  2464. }
  2465. FMT_CONSTEXPR20 bigit& operator[](int index) {
  2466. return bigits_[to_unsigned(index)];
  2467. }
  2468. static constexpr const int bigit_bits = num_bits<bigit>();
  2469. friend struct formatter<bigint>;
  2470. FMT_CONSTEXPR20 void subtract_bigits(int index, bigit other, bigit& borrow) {
  2471. auto result = static_cast<double_bigit>((*this)[index]) - other - borrow;
  2472. (*this)[index] = static_cast<bigit>(result);
  2473. borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1));
  2474. }
  2475. FMT_CONSTEXPR20 void remove_leading_zeros() {
  2476. int num_bigits = static_cast<int>(bigits_.size()) - 1;
  2477. while (num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits;
  2478. bigits_.resize(to_unsigned(num_bigits + 1));
  2479. }
  2480. // Computes *this -= other assuming aligned bigints and *this >= other.
  2481. FMT_CONSTEXPR20 void subtract_aligned(const bigint& other) {
  2482. FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints");
  2483. FMT_ASSERT(compare(*this, other) >= 0, "");
  2484. bigit borrow = 0;
  2485. int i = other.exp_ - exp_;
  2486. for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j)
  2487. subtract_bigits(i, other.bigits_[j], borrow);
  2488. while (borrow > 0) subtract_bigits(i, 0, borrow);
  2489. remove_leading_zeros();
  2490. }
  2491. FMT_CONSTEXPR20 void multiply(uint32_t value) {
  2492. const double_bigit wide_value = value;
  2493. bigit carry = 0;
  2494. for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
  2495. double_bigit result = bigits_[i] * wide_value + carry;
  2496. bigits_[i] = static_cast<bigit>(result);
  2497. carry = static_cast<bigit>(result >> bigit_bits);
  2498. }
  2499. if (carry != 0) bigits_.push_back(carry);
  2500. }
  2501. template <typename UInt, FMT_ENABLE_IF(std::is_same<UInt, uint64_t>::value ||
  2502. std::is_same<UInt, uint128_t>::value)>
  2503. FMT_CONSTEXPR20 void multiply(UInt value) {
  2504. using half_uint =
  2505. conditional_t<std::is_same<UInt, uint128_t>::value, uint64_t, uint32_t>;
  2506. const int shift = num_bits<half_uint>() - bigit_bits;
  2507. const UInt lower = static_cast<half_uint>(value);
  2508. const UInt upper = value >> num_bits<half_uint>();
  2509. UInt carry = 0;
  2510. for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
  2511. UInt result = lower * bigits_[i] + static_cast<bigit>(carry);
  2512. carry = (upper * bigits_[i] << shift) + (result >> bigit_bits) +
  2513. (carry >> bigit_bits);
  2514. bigits_[i] = static_cast<bigit>(result);
  2515. }
  2516. while (carry != 0) {
  2517. bigits_.push_back(static_cast<bigit>(carry));
  2518. carry >>= bigit_bits;
  2519. }
  2520. }
  2521. template <typename UInt, FMT_ENABLE_IF(std::is_same<UInt, uint64_t>::value ||
  2522. std::is_same<UInt, uint128_t>::value)>
  2523. FMT_CONSTEXPR20 void assign(UInt n) {
  2524. size_t num_bigits = 0;
  2525. do {
  2526. bigits_[num_bigits++] = static_cast<bigit>(n);
  2527. n >>= bigit_bits;
  2528. } while (n != 0);
  2529. bigits_.resize(num_bigits);
  2530. exp_ = 0;
  2531. }
  2532. public:
  2533. FMT_CONSTEXPR20 bigint() : exp_(0) {}
  2534. explicit bigint(uint64_t n) { assign(n); }
  2535. bigint(const bigint&) = delete;
  2536. void operator=(const bigint&) = delete;
  2537. FMT_CONSTEXPR20 void assign(const bigint& other) {
  2538. auto size = other.bigits_.size();
  2539. bigits_.resize(size);
  2540. auto data = other.bigits_.data();
  2541. std::copy(data, data + size, make_checked(bigits_.data(), size));
  2542. exp_ = other.exp_;
  2543. }
  2544. template <typename Int> FMT_CONSTEXPR20 void operator=(Int n) {
  2545. FMT_ASSERT(n > 0, "");
  2546. assign(uint64_or_128_t<Int>(n));
  2547. }
  2548. FMT_CONSTEXPR20 int num_bigits() const {
  2549. return static_cast<int>(bigits_.size()) + exp_;
  2550. }
  2551. FMT_NOINLINE FMT_CONSTEXPR20 bigint& operator<<=(int shift) {
  2552. FMT_ASSERT(shift >= 0, "");
  2553. exp_ += shift / bigit_bits;
  2554. shift %= bigit_bits;
  2555. if (shift == 0) return *this;
  2556. bigit carry = 0;
  2557. for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
  2558. bigit c = bigits_[i] >> (bigit_bits - shift);
  2559. bigits_[i] = (bigits_[i] << shift) + carry;
  2560. carry = c;
  2561. }
  2562. if (carry != 0) bigits_.push_back(carry);
  2563. return *this;
  2564. }
  2565. template <typename Int> FMT_CONSTEXPR20 bigint& operator*=(Int value) {
  2566. FMT_ASSERT(value > 0, "");
  2567. multiply(uint32_or_64_or_128_t<Int>(value));
  2568. return *this;
  2569. }
  2570. friend FMT_CONSTEXPR20 int compare(const bigint& lhs, const bigint& rhs) {
  2571. int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits();
  2572. if (num_lhs_bigits != num_rhs_bigits)
  2573. return num_lhs_bigits > num_rhs_bigits ? 1 : -1;
  2574. int i = static_cast<int>(lhs.bigits_.size()) - 1;
  2575. int j = static_cast<int>(rhs.bigits_.size()) - 1;
  2576. int end = i - j;
  2577. if (end < 0) end = 0;
  2578. for (; i >= end; --i, --j) {
  2579. bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j];
  2580. if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1;
  2581. }
  2582. if (i != j) return i > j ? 1 : -1;
  2583. return 0;
  2584. }
  2585. // Returns compare(lhs1 + lhs2, rhs).
  2586. friend FMT_CONSTEXPR20 int add_compare(const bigint& lhs1, const bigint& lhs2,
  2587. const bigint& rhs) {
  2588. auto minimum = [](int a, int b) { return a < b ? a : b; };
  2589. auto maximum = [](int a, int b) { return a > b ? a : b; };
  2590. int max_lhs_bigits = maximum(lhs1.num_bigits(), lhs2.num_bigits());
  2591. int num_rhs_bigits = rhs.num_bigits();
  2592. if (max_lhs_bigits + 1 < num_rhs_bigits) return -1;
  2593. if (max_lhs_bigits > num_rhs_bigits) return 1;
  2594. auto get_bigit = [](const bigint& n, int i) -> bigit {
  2595. return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0;
  2596. };
  2597. double_bigit borrow = 0;
  2598. int min_exp = minimum(minimum(lhs1.exp_, lhs2.exp_), rhs.exp_);
  2599. for (int i = num_rhs_bigits - 1; i >= min_exp; --i) {
  2600. double_bigit sum =
  2601. static_cast<double_bigit>(get_bigit(lhs1, i)) + get_bigit(lhs2, i);
  2602. bigit rhs_bigit = get_bigit(rhs, i);
  2603. if (sum > rhs_bigit + borrow) return 1;
  2604. borrow = rhs_bigit + borrow - sum;
  2605. if (borrow > 1) return -1;
  2606. borrow <<= bigit_bits;
  2607. }
  2608. return borrow != 0 ? -1 : 0;
  2609. }
  2610. // Assigns pow(10, exp) to this bigint.
  2611. FMT_CONSTEXPR20 void assign_pow10(int exp) {
  2612. FMT_ASSERT(exp >= 0, "");
  2613. if (exp == 0) return *this = 1;
  2614. // Find the top bit.
  2615. int bitmask = 1;
  2616. while (exp >= bitmask) bitmask <<= 1;
  2617. bitmask >>= 1;
  2618. // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by
  2619. // repeated squaring and multiplication.
  2620. *this = 5;
  2621. bitmask >>= 1;
  2622. while (bitmask != 0) {
  2623. square();
  2624. if ((exp & bitmask) != 0) *this *= 5;
  2625. bitmask >>= 1;
  2626. }
  2627. *this <<= exp; // Multiply by pow(2, exp) by shifting.
  2628. }
  2629. FMT_CONSTEXPR20 void square() {
  2630. int num_bigits = static_cast<int>(bigits_.size());
  2631. int num_result_bigits = 2 * num_bigits;
  2632. basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_));
  2633. bigits_.resize(to_unsigned(num_result_bigits));
  2634. auto sum = uint128_t();
  2635. for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) {
  2636. // Compute bigit at position bigit_index of the result by adding
  2637. // cross-product terms n[i] * n[j] such that i + j == bigit_index.
  2638. for (int i = 0, j = bigit_index; j >= 0; ++i, --j) {
  2639. // Most terms are multiplied twice which can be optimized in the future.
  2640. sum += static_cast<double_bigit>(n[i]) * n[j];
  2641. }
  2642. (*this)[bigit_index] = static_cast<bigit>(sum);
  2643. sum >>= num_bits<bigit>(); // Compute the carry.
  2644. }
  2645. // Do the same for the top half.
  2646. for (int bigit_index = num_bigits; bigit_index < num_result_bigits;
  2647. ++bigit_index) {
  2648. for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;)
  2649. sum += static_cast<double_bigit>(n[i++]) * n[j--];
  2650. (*this)[bigit_index] = static_cast<bigit>(sum);
  2651. sum >>= num_bits<bigit>();
  2652. }
  2653. remove_leading_zeros();
  2654. exp_ *= 2;
  2655. }
  2656. // If this bigint has a bigger exponent than other, adds trailing zero to make
  2657. // exponents equal. This simplifies some operations such as subtraction.
  2658. FMT_CONSTEXPR20 void align(const bigint& other) {
  2659. int exp_difference = exp_ - other.exp_;
  2660. if (exp_difference <= 0) return;
  2661. int num_bigits = static_cast<int>(bigits_.size());
  2662. bigits_.resize(to_unsigned(num_bigits + exp_difference));
  2663. for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j)
  2664. bigits_[j] = bigits_[i];
  2665. std::uninitialized_fill_n(bigits_.data(), exp_difference, 0);
  2666. exp_ -= exp_difference;
  2667. }
  2668. // Divides this bignum by divisor, assigning the remainder to this and
  2669. // returning the quotient.
  2670. FMT_CONSTEXPR20 int divmod_assign(const bigint& divisor) {
  2671. FMT_ASSERT(this != &divisor, "");
  2672. if (compare(*this, divisor) < 0) return 0;
  2673. FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, "");
  2674. align(divisor);
  2675. int quotient = 0;
  2676. do {
  2677. subtract_aligned(divisor);
  2678. ++quotient;
  2679. } while (compare(*this, divisor) >= 0);
  2680. return quotient;
  2681. }
  2682. };
  2683. // format_dragon flags.
  2684. enum dragon {
  2685. predecessor_closer = 1,
  2686. fixup = 2, // Run fixup to correct exp10 which can be off by one.
  2687. fixed = 4,
  2688. };
  2689. // Formats a floating-point number using a variation of the Fixed-Precision
  2690. // Positive Floating-Point Printout ((FPP)^2) algorithm by Steele & White:
  2691. // https://fmt.dev/papers/p372-steele.pdf.
  2692. FMT_CONSTEXPR20 inline void format_dragon(basic_fp<uint128_t> value,
  2693. unsigned flags, int num_digits,
  2694. buffer<char>& buf, int& exp10) {
  2695. bigint numerator; // 2 * R in (FPP)^2.
  2696. bigint denominator; // 2 * S in (FPP)^2.
  2697. // lower and upper are differences between value and corresponding boundaries.
  2698. bigint lower; // (M^- in (FPP)^2).
  2699. bigint upper_store; // upper's value if different from lower.
  2700. bigint* upper = nullptr; // (M^+ in (FPP)^2).
  2701. // Shift numerator and denominator by an extra bit or two (if lower boundary
  2702. // is closer) to make lower and upper integers. This eliminates multiplication
  2703. // by 2 during later computations.
  2704. bool is_predecessor_closer = (flags & dragon::predecessor_closer) != 0;
  2705. int shift = is_predecessor_closer ? 2 : 1;
  2706. if (value.e >= 0) {
  2707. numerator = value.f;
  2708. numerator <<= value.e + shift;
  2709. lower = 1;
  2710. lower <<= value.e;
  2711. if (is_predecessor_closer) {
  2712. upper_store = 1;
  2713. upper_store <<= value.e + 1;
  2714. upper = &upper_store;
  2715. }
  2716. denominator.assign_pow10(exp10);
  2717. denominator <<= shift;
  2718. } else if (exp10 < 0) {
  2719. numerator.assign_pow10(-exp10);
  2720. lower.assign(numerator);
  2721. if (is_predecessor_closer) {
  2722. upper_store.assign(numerator);
  2723. upper_store <<= 1;
  2724. upper = &upper_store;
  2725. }
  2726. numerator *= value.f;
  2727. numerator <<= shift;
  2728. denominator = 1;
  2729. denominator <<= shift - value.e;
  2730. } else {
  2731. numerator = value.f;
  2732. numerator <<= shift;
  2733. denominator.assign_pow10(exp10);
  2734. denominator <<= shift - value.e;
  2735. lower = 1;
  2736. if (is_predecessor_closer) {
  2737. upper_store = 1ULL << 1;
  2738. upper = &upper_store;
  2739. }
  2740. }
  2741. int even = static_cast<int>((value.f & 1) == 0);
  2742. if (!upper) upper = &lower;
  2743. if ((flags & dragon::fixup) != 0) {
  2744. if (add_compare(numerator, *upper, denominator) + even <= 0) {
  2745. --exp10;
  2746. numerator *= 10;
  2747. if (num_digits < 0) {
  2748. lower *= 10;
  2749. if (upper != &lower) *upper *= 10;
  2750. }
  2751. }
  2752. if ((flags & dragon::fixed) != 0) adjust_precision(num_digits, exp10 + 1);
  2753. }
  2754. // Invariant: value == (numerator / denominator) * pow(10, exp10).
  2755. if (num_digits < 0) {
  2756. // Generate the shortest representation.
  2757. num_digits = 0;
  2758. char* data = buf.data();
  2759. for (;;) {
  2760. int digit = numerator.divmod_assign(denominator);
  2761. bool low = compare(numerator, lower) - even < 0; // numerator <[=] lower.
  2762. // numerator + upper >[=] pow10:
  2763. bool high = add_compare(numerator, *upper, denominator) + even > 0;
  2764. data[num_digits++] = static_cast<char>('0' + digit);
  2765. if (low || high) {
  2766. if (!low) {
  2767. ++data[num_digits - 1];
  2768. } else if (high) {
  2769. int result = add_compare(numerator, numerator, denominator);
  2770. // Round half to even.
  2771. if (result > 0 || (result == 0 && (digit % 2) != 0))
  2772. ++data[num_digits - 1];
  2773. }
  2774. buf.try_resize(to_unsigned(num_digits));
  2775. exp10 -= num_digits - 1;
  2776. return;
  2777. }
  2778. numerator *= 10;
  2779. lower *= 10;
  2780. if (upper != &lower) *upper *= 10;
  2781. }
  2782. }
  2783. // Generate the given number of digits.
  2784. exp10 -= num_digits - 1;
  2785. if (num_digits == 0) {
  2786. denominator *= 10;
  2787. auto digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0';
  2788. buf.push_back(digit);
  2789. return;
  2790. }
  2791. buf.try_resize(to_unsigned(num_digits));
  2792. for (int i = 0; i < num_digits - 1; ++i) {
  2793. int digit = numerator.divmod_assign(denominator);
  2794. buf[i] = static_cast<char>('0' + digit);
  2795. numerator *= 10;
  2796. }
  2797. int digit = numerator.divmod_assign(denominator);
  2798. auto result = add_compare(numerator, numerator, denominator);
  2799. if (result > 0 || (result == 0 && (digit % 2) != 0)) {
  2800. if (digit == 9) {
  2801. const auto overflow = '0' + 10;
  2802. buf[num_digits - 1] = overflow;
  2803. // Propagate the carry.
  2804. for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) {
  2805. buf[i] = '0';
  2806. ++buf[i - 1];
  2807. }
  2808. if (buf[0] == overflow) {
  2809. buf[0] = '1';
  2810. ++exp10;
  2811. }
  2812. return;
  2813. }
  2814. ++digit;
  2815. }
  2816. buf[num_digits - 1] = static_cast<char>('0' + digit);
  2817. }
  2818. template <typename Float>
  2819. FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs,
  2820. buffer<char>& buf) -> int {
  2821. // float is passed as double to reduce the number of instantiations.
  2822. static_assert(!std::is_same<Float, float>::value, "");
  2823. FMT_ASSERT(value >= 0, "value is negative");
  2824. auto converted_value = convert_float(value);
  2825. const bool fixed = specs.format == float_format::fixed;
  2826. if (value <= 0) { // <= instead of == to silence a warning.
  2827. if (precision <= 0 || !fixed) {
  2828. buf.push_back('0');
  2829. return 0;
  2830. }
  2831. buf.try_resize(to_unsigned(precision));
  2832. fill_n(buf.data(), precision, '0');
  2833. return -precision;
  2834. }
  2835. int exp = 0;
  2836. bool use_dragon = true;
  2837. unsigned dragon_flags = 0;
  2838. if (!is_fast_float<Float>()) {
  2839. const auto inv_log2_10 = 0.3010299956639812; // 1 / log2(10)
  2840. using info = dragonbox::float_info<decltype(converted_value)>;
  2841. const auto f = basic_fp<typename info::carrier_uint>(converted_value);
  2842. // Compute exp, an approximate power of 10, such that
  2843. // 10^(exp - 1) <= value < 10^exp or 10^exp <= value < 10^(exp + 1).
  2844. // This is based on log10(value) == log2(value) / log2(10) and approximation
  2845. // of log2(value) by e + num_fraction_bits idea from double-conversion.
  2846. exp = static_cast<int>(
  2847. std::ceil((f.e + count_digits<1>(f.f) - 1) * inv_log2_10 - 1e-10));
  2848. dragon_flags = dragon::fixup;
  2849. } else if (!is_constant_evaluated() && precision < 0) {
  2850. // Use Dragonbox for the shortest format.
  2851. if (specs.binary32) {
  2852. auto dec = dragonbox::to_decimal(static_cast<float>(value));
  2853. write<char>(buffer_appender<char>(buf), dec.significand);
  2854. return dec.exponent;
  2855. }
  2856. auto dec = dragonbox::to_decimal(static_cast<double>(value));
  2857. write<char>(buffer_appender<char>(buf), dec.significand);
  2858. return dec.exponent;
  2859. } else {
  2860. // Use Grisu + Dragon4 for the given precision:
  2861. // https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf.
  2862. const int min_exp = -60; // alpha in Grisu.
  2863. int cached_exp10 = 0; // K in Grisu.
  2864. fp normalized = normalize(fp(converted_value));
  2865. const auto cached_pow = get_cached_power(
  2866. min_exp - (normalized.e + fp::num_significand_bits), cached_exp10);
  2867. normalized = normalized * cached_pow;
  2868. gen_digits_handler handler{buf.data(), 0, precision, -cached_exp10, fixed};
  2869. if (grisu_gen_digits(normalized, 1, exp, handler) != digits::error &&
  2870. !is_constant_evaluated()) {
  2871. exp += handler.exp10;
  2872. buf.try_resize(to_unsigned(handler.size));
  2873. use_dragon = false;
  2874. } else {
  2875. exp += handler.size - cached_exp10 - 1;
  2876. precision = handler.precision;
  2877. }
  2878. }
  2879. if (use_dragon) {
  2880. auto f = basic_fp<uint128_t>();
  2881. bool is_predecessor_closer = specs.binary32
  2882. ? f.assign(static_cast<float>(value))
  2883. : f.assign(converted_value);
  2884. if (is_predecessor_closer) dragon_flags |= dragon::predecessor_closer;
  2885. if (fixed) dragon_flags |= dragon::fixed;
  2886. // Limit precision to the maximum possible number of significant digits in
  2887. // an IEEE754 double because we don't need to generate zeros.
  2888. const int max_double_digits = 767;
  2889. if (precision > max_double_digits) precision = max_double_digits;
  2890. format_dragon(f, dragon_flags, precision, buf, exp);
  2891. }
  2892. if (!fixed && !specs.showpoint) {
  2893. // Remove trailing zeros.
  2894. auto num_digits = buf.size();
  2895. while (num_digits > 0 && buf[num_digits - 1] == '0') {
  2896. --num_digits;
  2897. ++exp;
  2898. }
  2899. buf.try_resize(num_digits);
  2900. }
  2901. return exp;
  2902. }
  2903. template <typename Char, typename OutputIt, typename T,
  2904. FMT_ENABLE_IF(is_floating_point<T>::value)>
  2905. FMT_CONSTEXPR20 auto write(OutputIt out, T value,
  2906. basic_format_specs<Char> specs, locale_ref loc = {})
  2907. -> OutputIt {
  2908. if (const_check(!is_supported_floating_point(value))) return out;
  2909. float_specs fspecs = parse_float_type_spec(specs);
  2910. fspecs.sign = specs.sign;
  2911. if (detail::signbit(value)) { // value < 0 is false for NaN so use signbit.
  2912. fspecs.sign = sign::minus;
  2913. value = -value;
  2914. } else if (fspecs.sign == sign::minus) {
  2915. fspecs.sign = sign::none;
  2916. }
  2917. if (!detail::isfinite(value))
  2918. return write_nonfinite(out, detail::isnan(value), specs, fspecs);
  2919. if (specs.align == align::numeric && fspecs.sign) {
  2920. auto it = reserve(out, 1);
  2921. *it++ = detail::sign<Char>(fspecs.sign);
  2922. out = base_iterator(out, it);
  2923. fspecs.sign = sign::none;
  2924. if (specs.width != 0) --specs.width;
  2925. }
  2926. memory_buffer buffer;
  2927. if (fspecs.format == float_format::hex) {
  2928. if (fspecs.sign) buffer.push_back(detail::sign<char>(fspecs.sign));
  2929. snprintf_float(convert_float(value), specs.precision, fspecs, buffer);
  2930. return write_bytes<align::right>(out, {buffer.data(), buffer.size()},
  2931. specs);
  2932. }
  2933. int precision = specs.precision >= 0 || specs.type == presentation_type::none
  2934. ? specs.precision
  2935. : 6;
  2936. if (fspecs.format == float_format::exp) {
  2937. if (precision == max_value<int>())
  2938. throw_format_error("number is too big");
  2939. else
  2940. ++precision;
  2941. } else if (fspecs.format != float_format::fixed && precision == 0) {
  2942. precision = 1;
  2943. }
  2944. if (const_check(std::is_same<T, float>())) fspecs.binary32 = true;
  2945. int exp = format_float(convert_float(value), precision, fspecs, buffer);
  2946. fspecs.precision = precision;
  2947. auto f = big_decimal_fp{buffer.data(), static_cast<int>(buffer.size()), exp};
  2948. return write_float(out, f, specs, fspecs, loc);
  2949. }
  2950. template <typename Char, typename OutputIt, typename T,
  2951. FMT_ENABLE_IF(is_fast_float<T>::value)>
  2952. FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt {
  2953. if (is_constant_evaluated())
  2954. return write(out, value, basic_format_specs<Char>());
  2955. if (const_check(!is_supported_floating_point(value))) return out;
  2956. auto fspecs = float_specs();
  2957. if (detail::signbit(value)) {
  2958. fspecs.sign = sign::minus;
  2959. value = -value;
  2960. }
  2961. constexpr auto specs = basic_format_specs<Char>();
  2962. using floaty = conditional_t<std::is_same<T, long double>::value, double, T>;
  2963. using uint = typename dragonbox::float_info<floaty>::carrier_uint;
  2964. uint mask = exponent_mask<floaty>();
  2965. if ((bit_cast<uint>(value) & mask) == mask)
  2966. return write_nonfinite(out, std::isnan(value), specs, fspecs);
  2967. auto dec = dragonbox::to_decimal(static_cast<floaty>(value));
  2968. return write_float(out, dec, specs, fspecs, {});
  2969. }
  2970. template <typename Char, typename OutputIt, typename T,
  2971. FMT_ENABLE_IF(is_floating_point<T>::value &&
  2972. !is_fast_float<T>::value)>
  2973. inline auto write(OutputIt out, T value) -> OutputIt {
  2974. return write(out, value, basic_format_specs<Char>());
  2975. }
  2976. template <typename Char, typename OutputIt>
  2977. auto write(OutputIt out, monostate, basic_format_specs<Char> = {},
  2978. locale_ref = {}) -> OutputIt {
  2979. FMT_ASSERT(false, "");
  2980. return out;
  2981. }
  2982. template <typename Char, typename OutputIt>
  2983. FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> value)
  2984. -> OutputIt {
  2985. auto it = reserve(out, value.size());
  2986. it = copy_str_noinline<Char>(value.begin(), value.end(), it);
  2987. return base_iterator(out, it);
  2988. }
  2989. template <typename Char, typename OutputIt, typename T,
  2990. FMT_ENABLE_IF(is_string<T>::value)>
  2991. constexpr auto write(OutputIt out, const T& value) -> OutputIt {
  2992. return write<Char>(out, to_string_view(value));
  2993. }
  2994. // FMT_ENABLE_IF() condition separated to workaround an MSVC bug.
  2995. template <
  2996. typename Char, typename OutputIt, typename T,
  2997. bool check =
  2998. std::is_enum<T>::value && !std::is_same<T, Char>::value &&
  2999. mapped_type_constant<T, basic_format_context<OutputIt, Char>>::value !=
  3000. type::custom_type,
  3001. FMT_ENABLE_IF(check)>
  3002. FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
  3003. return write<Char>(out, static_cast<underlying_t<T>>(value));
  3004. }
  3005. template <typename Char, typename OutputIt, typename T,
  3006. FMT_ENABLE_IF(std::is_same<T, bool>::value)>
  3007. FMT_CONSTEXPR auto write(OutputIt out, T value,
  3008. const basic_format_specs<Char>& specs = {},
  3009. locale_ref = {}) -> OutputIt {
  3010. return specs.type != presentation_type::none &&
  3011. specs.type != presentation_type::string
  3012. ? write(out, value ? 1 : 0, specs, {})
  3013. : write_bytes(out, value ? "true" : "false", specs);
  3014. }
  3015. template <typename Char, typename OutputIt>
  3016. FMT_CONSTEXPR auto write(OutputIt out, Char value) -> OutputIt {
  3017. auto it = reserve(out, 1);
  3018. *it++ = value;
  3019. return base_iterator(out, it);
  3020. }
  3021. template <typename Char, typename OutputIt>
  3022. FMT_CONSTEXPR_CHAR_TRAITS auto write(OutputIt out, const Char* value)
  3023. -> OutputIt {
  3024. if (!value) {
  3025. throw_format_error("string pointer is null");
  3026. } else {
  3027. out = write(out, basic_string_view<Char>(value));
  3028. }
  3029. return out;
  3030. }
  3031. template <typename Char, typename OutputIt, typename T,
  3032. FMT_ENABLE_IF(std::is_same<T, void>::value)>
  3033. auto write(OutputIt out, const T* value,
  3034. const basic_format_specs<Char>& specs = {}, locale_ref = {})
  3035. -> OutputIt {
  3036. check_pointer_type_spec(specs.type, error_handler());
  3037. return write_ptr<Char>(out, bit_cast<uintptr_t>(value), &specs);
  3038. }
  3039. // A write overload that handles implicit conversions.
  3040. template <typename Char, typename OutputIt, typename T,
  3041. typename Context = basic_format_context<OutputIt, Char>>
  3042. FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> enable_if_t<
  3043. std::is_class<T>::value && !is_string<T>::value &&
  3044. !is_floating_point<T>::value && !std::is_same<T, Char>::value &&
  3045. !std::is_same<const T&,
  3046. decltype(arg_mapper<Context>().map(value))>::value,
  3047. OutputIt> {
  3048. return write<Char>(out, arg_mapper<Context>().map(value));
  3049. }
  3050. template <typename Char, typename OutputIt, typename T,
  3051. typename Context = basic_format_context<OutputIt, Char>>
  3052. FMT_CONSTEXPR auto write(OutputIt out, const T& value)
  3053. -> enable_if_t<mapped_type_constant<T, Context>::value == type::custom_type,
  3054. OutputIt> {
  3055. using formatter_type =
  3056. conditional_t<has_formatter<T, Context>::value,
  3057. typename Context::template formatter_type<T>,
  3058. fallback_formatter<T, Char>>;
  3059. auto ctx = Context(out, {}, {});
  3060. return formatter_type().format(value, ctx);
  3061. }
  3062. // An argument visitor that formats the argument and writes it via the output
  3063. // iterator. It's a class and not a generic lambda for compatibility with C++11.
  3064. template <typename Char> struct default_arg_formatter {
  3065. using iterator = buffer_appender<Char>;
  3066. using context = buffer_context<Char>;
  3067. iterator out;
  3068. basic_format_args<context> args;
  3069. locale_ref loc;
  3070. template <typename T> auto operator()(T value) -> iterator {
  3071. return write<Char>(out, value);
  3072. }
  3073. auto operator()(typename basic_format_arg<context>::handle h) -> iterator {
  3074. basic_format_parse_context<Char> parse_ctx({});
  3075. context format_ctx(out, args, loc);
  3076. h.format(parse_ctx, format_ctx);
  3077. return format_ctx.out();
  3078. }
  3079. };
  3080. template <typename Char> struct arg_formatter {
  3081. using iterator = buffer_appender<Char>;
  3082. using context = buffer_context<Char>;
  3083. iterator out;
  3084. const basic_format_specs<Char>& specs;
  3085. locale_ref locale;
  3086. template <typename T>
  3087. FMT_CONSTEXPR FMT_INLINE auto operator()(T value) -> iterator {
  3088. return detail::write(out, value, specs, locale);
  3089. }
  3090. auto operator()(typename basic_format_arg<context>::handle) -> iterator {
  3091. // User-defined types are handled separately because they require access
  3092. // to the parse context.
  3093. return out;
  3094. }
  3095. };
  3096. template <typename Char> struct custom_formatter {
  3097. basic_format_parse_context<Char>& parse_ctx;
  3098. buffer_context<Char>& ctx;
  3099. void operator()(
  3100. typename basic_format_arg<buffer_context<Char>>::handle h) const {
  3101. h.format(parse_ctx, ctx);
  3102. }
  3103. template <typename T> void operator()(T) const {}
  3104. };
  3105. template <typename T>
  3106. using is_integer =
  3107. bool_constant<is_integral<T>::value && !std::is_same<T, bool>::value &&
  3108. !std::is_same<T, char>::value &&
  3109. !std::is_same<T, wchar_t>::value>;
  3110. template <typename ErrorHandler> class width_checker {
  3111. public:
  3112. explicit FMT_CONSTEXPR width_checker(ErrorHandler& eh) : handler_(eh) {}
  3113. template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
  3114. FMT_CONSTEXPR auto operator()(T value) -> unsigned long long {
  3115. if (is_negative(value)) handler_.on_error("negative width");
  3116. return static_cast<unsigned long long>(value);
  3117. }
  3118. template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
  3119. FMT_CONSTEXPR auto operator()(T) -> unsigned long long {
  3120. handler_.on_error("width is not integer");
  3121. return 0;
  3122. }
  3123. private:
  3124. ErrorHandler& handler_;
  3125. };
  3126. template <typename ErrorHandler> class precision_checker {
  3127. public:
  3128. explicit FMT_CONSTEXPR precision_checker(ErrorHandler& eh) : handler_(eh) {}
  3129. template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
  3130. FMT_CONSTEXPR auto operator()(T value) -> unsigned long long {
  3131. if (is_negative(value)) handler_.on_error("negative precision");
  3132. return static_cast<unsigned long long>(value);
  3133. }
  3134. template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
  3135. FMT_CONSTEXPR auto operator()(T) -> unsigned long long {
  3136. handler_.on_error("precision is not integer");
  3137. return 0;
  3138. }
  3139. private:
  3140. ErrorHandler& handler_;
  3141. };
  3142. template <template <typename> class Handler, typename FormatArg,
  3143. typename ErrorHandler>
  3144. FMT_CONSTEXPR auto get_dynamic_spec(FormatArg arg, ErrorHandler eh) -> int {
  3145. unsigned long long value = visit_format_arg(Handler<ErrorHandler>(eh), arg);
  3146. if (value > to_unsigned(max_value<int>())) eh.on_error("number is too big");
  3147. return static_cast<int>(value);
  3148. }
  3149. template <typename Context, typename ID>
  3150. FMT_CONSTEXPR auto get_arg(Context& ctx, ID id) ->
  3151. typename Context::format_arg {
  3152. auto arg = ctx.arg(id);
  3153. if (!arg) ctx.on_error("argument not found");
  3154. return arg;
  3155. }
  3156. // The standard format specifier handler with checking.
  3157. template <typename Char> class specs_handler : public specs_setter<Char> {
  3158. private:
  3159. basic_format_parse_context<Char>& parse_context_;
  3160. buffer_context<Char>& context_;
  3161. // This is only needed for compatibility with gcc 4.4.
  3162. using format_arg = basic_format_arg<buffer_context<Char>>;
  3163. FMT_CONSTEXPR auto get_arg(auto_id) -> format_arg {
  3164. return detail::get_arg(context_, parse_context_.next_arg_id());
  3165. }
  3166. FMT_CONSTEXPR auto get_arg(int arg_id) -> format_arg {
  3167. parse_context_.check_arg_id(arg_id);
  3168. return detail::get_arg(context_, arg_id);
  3169. }
  3170. FMT_CONSTEXPR auto get_arg(basic_string_view<Char> arg_id) -> format_arg {
  3171. parse_context_.check_arg_id(arg_id);
  3172. return detail::get_arg(context_, arg_id);
  3173. }
  3174. public:
  3175. FMT_CONSTEXPR specs_handler(basic_format_specs<Char>& specs,
  3176. basic_format_parse_context<Char>& parse_ctx,
  3177. buffer_context<Char>& ctx)
  3178. : specs_setter<Char>(specs), parse_context_(parse_ctx), context_(ctx) {}
  3179. template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
  3180. this->specs_.width = get_dynamic_spec<width_checker>(
  3181. get_arg(arg_id), context_.error_handler());
  3182. }
  3183. template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
  3184. this->specs_.precision = get_dynamic_spec<precision_checker>(
  3185. get_arg(arg_id), context_.error_handler());
  3186. }
  3187. void on_error(const char* message) { context_.on_error(message); }
  3188. };
  3189. template <template <typename> class Handler, typename Context>
  3190. FMT_CONSTEXPR void handle_dynamic_spec(int& value,
  3191. arg_ref<typename Context::char_type> ref,
  3192. Context& ctx) {
  3193. switch (ref.kind) {
  3194. case arg_id_kind::none:
  3195. break;
  3196. case arg_id_kind::index:
  3197. value = detail::get_dynamic_spec<Handler>(ctx.arg(ref.val.index),
  3198. ctx.error_handler());
  3199. break;
  3200. case arg_id_kind::name:
  3201. value = detail::get_dynamic_spec<Handler>(ctx.arg(ref.val.name),
  3202. ctx.error_handler());
  3203. break;
  3204. }
  3205. }
  3206. #if FMT_USE_USER_DEFINED_LITERALS
  3207. template <typename Char> struct udl_formatter {
  3208. basic_string_view<Char> str;
  3209. template <typename... T>
  3210. auto operator()(T&&... args) const -> std::basic_string<Char> {
  3211. return vformat(str, fmt::make_format_args<buffer_context<Char>>(args...));
  3212. }
  3213. };
  3214. # if FMT_USE_NONTYPE_TEMPLATE_ARGS
  3215. template <typename T, typename Char, size_t N,
  3216. fmt::detail_exported::fixed_string<Char, N> Str>
  3217. struct statically_named_arg : view {
  3218. static constexpr auto name = Str.data;
  3219. const T& value;
  3220. statically_named_arg(const T& v) : value(v) {}
  3221. };
  3222. template <typename T, typename Char, size_t N,
  3223. fmt::detail_exported::fixed_string<Char, N> Str>
  3224. struct is_named_arg<statically_named_arg<T, Char, N, Str>> : std::true_type {};
  3225. template <typename T, typename Char, size_t N,
  3226. fmt::detail_exported::fixed_string<Char, N> Str>
  3227. struct is_statically_named_arg<statically_named_arg<T, Char, N, Str>>
  3228. : std::true_type {};
  3229. template <typename Char, size_t N,
  3230. fmt::detail_exported::fixed_string<Char, N> Str>
  3231. struct udl_arg {
  3232. template <typename T> auto operator=(T&& value) const {
  3233. return statically_named_arg<T, Char, N, Str>(std::forward<T>(value));
  3234. }
  3235. };
  3236. # else
  3237. template <typename Char> struct udl_arg {
  3238. const Char* str;
  3239. template <typename T> auto operator=(T&& value) const -> named_arg<Char, T> {
  3240. return {str, std::forward<T>(value)};
  3241. }
  3242. };
  3243. # endif
  3244. #endif // FMT_USE_USER_DEFINED_LITERALS
  3245. template <typename Locale, typename Char>
  3246. auto vformat(const Locale& loc, basic_string_view<Char> format_str,
  3247. basic_format_args<buffer_context<type_identity_t<Char>>> args)
  3248. -> std::basic_string<Char> {
  3249. basic_memory_buffer<Char> buffer;
  3250. detail::vformat_to(buffer, format_str, args, detail::locale_ref(loc));
  3251. return {buffer.data(), buffer.size()};
  3252. }
  3253. using format_func = void (*)(detail::buffer<char>&, int, const char*);
  3254. FMT_API void format_error_code(buffer<char>& out, int error_code,
  3255. string_view message) noexcept;
  3256. FMT_API void report_error(format_func func, int error_code,
  3257. const char* message) noexcept;
  3258. FMT_END_DETAIL_NAMESPACE
  3259. FMT_API auto vsystem_error(int error_code, string_view format_str,
  3260. format_args args) -> std::system_error;
  3261. /**
  3262. \rst
  3263. Constructs :class:`std::system_error` with a message formatted with
  3264. ``fmt::format(fmt, args...)``.
  3265. *error_code* is a system error code as given by ``errno``.
  3266. **Example**::
  3267. // This throws std::system_error with the description
  3268. // cannot open file 'madeup': No such file or directory
  3269. // or similar (system message may vary).
  3270. const char* filename = "madeup";
  3271. std::FILE* file = std::fopen(filename, "r");
  3272. if (!file)
  3273. throw fmt::system_error(errno, "cannot open file '{}'", filename);
  3274. \endrst
  3275. */
  3276. template <typename... T>
  3277. auto system_error(int error_code, format_string<T...> fmt, T&&... args)
  3278. -> std::system_error {
  3279. return vsystem_error(error_code, fmt, fmt::make_format_args(args...));
  3280. }
  3281. /**
  3282. \rst
  3283. Formats an error message for an error returned by an operating system or a
  3284. language runtime, for example a file opening error, and writes it to *out*.
  3285. The format is the same as the one used by ``std::system_error(ec, message)``
  3286. where ``ec`` is ``std::error_code(error_code, std::generic_category()})``.
  3287. It is implementation-defined but normally looks like:
  3288. .. parsed-literal::
  3289. *<message>*: *<system-message>*
  3290. where *<message>* is the passed message and *<system-message>* is the system
  3291. message corresponding to the error code.
  3292. *error_code* is a system error code as given by ``errno``.
  3293. \endrst
  3294. */
  3295. FMT_API void format_system_error(detail::buffer<char>& out, int error_code,
  3296. const char* message) noexcept;
  3297. // Reports a system error without throwing an exception.
  3298. // Can be used to report errors from destructors.
  3299. FMT_API void report_system_error(int error_code, const char* message) noexcept;
  3300. /** Fast integer formatter. */
  3301. class format_int {
  3302. private:
  3303. // Buffer should be large enough to hold all digits (digits10 + 1),
  3304. // a sign and a null character.
  3305. enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 };
  3306. mutable char buffer_[buffer_size];
  3307. char* str_;
  3308. template <typename UInt> auto format_unsigned(UInt value) -> char* {
  3309. auto n = static_cast<detail::uint32_or_64_or_128_t<UInt>>(value);
  3310. return detail::format_decimal(buffer_, n, buffer_size - 1).begin;
  3311. }
  3312. template <typename Int> auto format_signed(Int value) -> char* {
  3313. auto abs_value = static_cast<detail::uint32_or_64_or_128_t<Int>>(value);
  3314. bool negative = value < 0;
  3315. if (negative) abs_value = 0 - abs_value;
  3316. auto begin = format_unsigned(abs_value);
  3317. if (negative) *--begin = '-';
  3318. return begin;
  3319. }
  3320. public:
  3321. explicit format_int(int value) : str_(format_signed(value)) {}
  3322. explicit format_int(long value) : str_(format_signed(value)) {}
  3323. explicit format_int(long long value) : str_(format_signed(value)) {}
  3324. explicit format_int(unsigned value) : str_(format_unsigned(value)) {}
  3325. explicit format_int(unsigned long value) : str_(format_unsigned(value)) {}
  3326. explicit format_int(unsigned long long value)
  3327. : str_(format_unsigned(value)) {}
  3328. /** Returns the number of characters written to the output buffer. */
  3329. auto size() const -> size_t {
  3330. return detail::to_unsigned(buffer_ - str_ + buffer_size - 1);
  3331. }
  3332. /**
  3333. Returns a pointer to the output buffer content. No terminating null
  3334. character is appended.
  3335. */
  3336. auto data() const -> const char* { return str_; }
  3337. /**
  3338. Returns a pointer to the output buffer content with terminating null
  3339. character appended.
  3340. */
  3341. auto c_str() const -> const char* {
  3342. buffer_[buffer_size - 1] = '\0';
  3343. return str_;
  3344. }
  3345. /**
  3346. \rst
  3347. Returns the content of the output buffer as an ``std::string``.
  3348. \endrst
  3349. */
  3350. auto str() const -> std::string { return std::string(str_, size()); }
  3351. };
  3352. template <typename T, typename Char>
  3353. template <typename FormatContext>
  3354. FMT_CONSTEXPR FMT_INLINE auto
  3355. formatter<T, Char,
  3356. enable_if_t<detail::type_constant<T, Char>::value !=
  3357. detail::type::custom_type>>::format(const T& val,
  3358. FormatContext& ctx)
  3359. const -> decltype(ctx.out()) {
  3360. if (specs_.width_ref.kind != detail::arg_id_kind::none ||
  3361. specs_.precision_ref.kind != detail::arg_id_kind::none) {
  3362. auto specs = specs_;
  3363. detail::handle_dynamic_spec<detail::width_checker>(specs.width,
  3364. specs.width_ref, ctx);
  3365. detail::handle_dynamic_spec<detail::precision_checker>(
  3366. specs.precision, specs.precision_ref, ctx);
  3367. return detail::write<Char>(ctx.out(), val, specs, ctx.locale());
  3368. }
  3369. return detail::write<Char>(ctx.out(), val, specs_, ctx.locale());
  3370. }
  3371. template <typename Char>
  3372. struct formatter<void*, Char> : formatter<const void*, Char> {
  3373. template <typename FormatContext>
  3374. auto format(void* val, FormatContext& ctx) const -> decltype(ctx.out()) {
  3375. return formatter<const void*, Char>::format(val, ctx);
  3376. }
  3377. };
  3378. template <typename Char, size_t N>
  3379. struct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> {
  3380. template <typename FormatContext>
  3381. FMT_CONSTEXPR auto format(const Char* val, FormatContext& ctx) const
  3382. -> decltype(ctx.out()) {
  3383. return formatter<basic_string_view<Char>, Char>::format(val, ctx);
  3384. }
  3385. };
  3386. // A formatter for types known only at run time such as variant alternatives.
  3387. //
  3388. // Usage:
  3389. // using variant = std::variant<int, std::string>;
  3390. // template <>
  3391. // struct formatter<variant>: dynamic_formatter<> {
  3392. // auto format(const variant& v, format_context& ctx) {
  3393. // return visit([&](const auto& val) {
  3394. // return dynamic_formatter<>::format(val, ctx);
  3395. // }, v);
  3396. // }
  3397. // };
  3398. template <typename Char = char> class dynamic_formatter {
  3399. private:
  3400. detail::dynamic_format_specs<Char> specs_;
  3401. const Char* format_str_;
  3402. struct null_handler : detail::error_handler {
  3403. void on_align(align_t) {}
  3404. void on_sign(sign_t) {}
  3405. void on_hash() {}
  3406. };
  3407. template <typename Context> void handle_specs(Context& ctx) {
  3408. detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
  3409. specs_.width_ref, ctx);
  3410. detail::handle_dynamic_spec<detail::precision_checker>(
  3411. specs_.precision, specs_.precision_ref, ctx);
  3412. }
  3413. public:
  3414. template <typename ParseContext>
  3415. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  3416. format_str_ = ctx.begin();
  3417. // Checks are deferred to formatting time when the argument type is known.
  3418. detail::dynamic_specs_handler<ParseContext> handler(specs_, ctx);
  3419. return detail::parse_format_specs(ctx.begin(), ctx.end(), handler);
  3420. }
  3421. template <typename T, typename FormatContext>
  3422. auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) {
  3423. handle_specs(ctx);
  3424. detail::specs_checker<null_handler> checker(
  3425. null_handler(), detail::mapped_type_constant<T, FormatContext>::value);
  3426. checker.on_align(specs_.align);
  3427. if (specs_.sign != sign::none) checker.on_sign(specs_.sign);
  3428. if (specs_.alt) checker.on_hash();
  3429. if (specs_.precision >= 0) checker.end_precision();
  3430. return detail::write<Char>(ctx.out(), val, specs_, ctx.locale());
  3431. }
  3432. };
  3433. /**
  3434. \rst
  3435. Converts ``p`` to ``const void*`` for pointer formatting.
  3436. **Example**::
  3437. auto s = fmt::format("{}", fmt::ptr(p));
  3438. \endrst
  3439. */
  3440. template <typename T> auto ptr(T p) -> const void* {
  3441. static_assert(std::is_pointer<T>::value, "");
  3442. return detail::bit_cast<const void*>(p);
  3443. }
  3444. template <typename T> auto ptr(const std::unique_ptr<T>& p) -> const void* {
  3445. return p.get();
  3446. }
  3447. template <typename T> auto ptr(const std::shared_ptr<T>& p) -> const void* {
  3448. return p.get();
  3449. }
  3450. /**
  3451. \rst
  3452. Converts ``e`` to the underlying type.
  3453. **Example**::
  3454. enum class color { red, green, blue };
  3455. auto s = fmt::format("{}", fmt::underlying(color::red));
  3456. \endrst
  3457. */
  3458. template <typename Enum>
  3459. constexpr auto underlying(Enum e) noexcept -> underlying_t<Enum> {
  3460. return static_cast<underlying_t<Enum>>(e);
  3461. }
  3462. namespace enums {
  3463. template <typename Enum, FMT_ENABLE_IF(std::is_enum<Enum>::value)>
  3464. constexpr auto format_as(Enum e) noexcept -> underlying_t<Enum> {
  3465. return static_cast<underlying_t<Enum>>(e);
  3466. }
  3467. } // namespace enums
  3468. class bytes {
  3469. private:
  3470. string_view data_;
  3471. friend struct formatter<bytes>;
  3472. public:
  3473. explicit bytes(string_view data) : data_(data) {}
  3474. };
  3475. template <> struct formatter<bytes> {
  3476. private:
  3477. detail::dynamic_format_specs<char> specs_;
  3478. public:
  3479. template <typename ParseContext>
  3480. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  3481. using handler_type = detail::dynamic_specs_handler<ParseContext>;
  3482. detail::specs_checker<handler_type> handler(handler_type(specs_, ctx),
  3483. detail::type::string_type);
  3484. auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
  3485. detail::check_string_type_spec(specs_.type, ctx.error_handler());
  3486. return it;
  3487. }
  3488. template <typename FormatContext>
  3489. auto format(bytes b, FormatContext& ctx) -> decltype(ctx.out()) {
  3490. detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
  3491. specs_.width_ref, ctx);
  3492. detail::handle_dynamic_spec<detail::precision_checker>(
  3493. specs_.precision, specs_.precision_ref, ctx);
  3494. return detail::write_bytes(ctx.out(), b.data_, specs_);
  3495. }
  3496. };
  3497. // group_digits_view is not derived from view because it copies the argument.
  3498. template <typename T> struct group_digits_view { T value; };
  3499. /**
  3500. \rst
  3501. Returns a view that formats an integer value using ',' as a locale-independent
  3502. thousands separator.
  3503. **Example**::
  3504. fmt::print("{}", fmt::group_digits(12345));
  3505. // Output: "12,345"
  3506. \endrst
  3507. */
  3508. template <typename T> auto group_digits(T value) -> group_digits_view<T> {
  3509. return {value};
  3510. }
  3511. template <typename T> struct formatter<group_digits_view<T>> : formatter<T> {
  3512. private:
  3513. detail::dynamic_format_specs<char> specs_;
  3514. public:
  3515. template <typename ParseContext>
  3516. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  3517. using handler_type = detail::dynamic_specs_handler<ParseContext>;
  3518. detail::specs_checker<handler_type> handler(handler_type(specs_, ctx),
  3519. detail::type::int_type);
  3520. auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
  3521. detail::check_string_type_spec(specs_.type, ctx.error_handler());
  3522. return it;
  3523. }
  3524. template <typename FormatContext>
  3525. auto format(group_digits_view<T> t, FormatContext& ctx)
  3526. -> decltype(ctx.out()) {
  3527. detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
  3528. specs_.width_ref, ctx);
  3529. detail::handle_dynamic_spec<detail::precision_checker>(
  3530. specs_.precision, specs_.precision_ref, ctx);
  3531. return detail::write_int_localized(
  3532. ctx.out(), static_cast<detail::uint64_or_128_t<T>>(t.value), 0, specs_,
  3533. detail::digit_grouping<char>({"\3", ','}));
  3534. }
  3535. };
  3536. template <typename It, typename Sentinel, typename Char = char>
  3537. struct join_view : detail::view {
  3538. It begin;
  3539. Sentinel end;
  3540. basic_string_view<Char> sep;
  3541. join_view(It b, Sentinel e, basic_string_view<Char> s)
  3542. : begin(b), end(e), sep(s) {}
  3543. };
  3544. template <typename It, typename Sentinel, typename Char>
  3545. struct formatter<join_view<It, Sentinel, Char>, Char> {
  3546. private:
  3547. using value_type =
  3548. #ifdef __cpp_lib_ranges
  3549. std::iter_value_t<It>;
  3550. #else
  3551. typename std::iterator_traits<It>::value_type;
  3552. #endif
  3553. using context = buffer_context<Char>;
  3554. using mapper = detail::arg_mapper<context>;
  3555. template <typename T, FMT_ENABLE_IF(has_formatter<T, context>::value)>
  3556. static auto map(const T& value) -> const T& {
  3557. return value;
  3558. }
  3559. template <typename T, FMT_ENABLE_IF(!has_formatter<T, context>::value)>
  3560. static auto map(const T& value) -> decltype(mapper().map(value)) {
  3561. return mapper().map(value);
  3562. }
  3563. using formatter_type =
  3564. conditional_t<is_formattable<value_type, Char>::value,
  3565. formatter<remove_cvref_t<decltype(map(
  3566. std::declval<const value_type&>()))>,
  3567. Char>,
  3568. detail::fallback_formatter<value_type, Char>>;
  3569. formatter_type value_formatter_;
  3570. public:
  3571. template <typename ParseContext>
  3572. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  3573. return value_formatter_.parse(ctx);
  3574. }
  3575. template <typename FormatContext>
  3576. auto format(const join_view<It, Sentinel, Char>& value,
  3577. FormatContext& ctx) const -> decltype(ctx.out()) {
  3578. auto it = value.begin;
  3579. auto out = ctx.out();
  3580. if (it != value.end) {
  3581. out = value_formatter_.format(map(*it), ctx);
  3582. ++it;
  3583. while (it != value.end) {
  3584. out = detail::copy_str<Char>(value.sep.begin(), value.sep.end(), out);
  3585. ctx.advance_to(out);
  3586. out = value_formatter_.format(map(*it), ctx);
  3587. ++it;
  3588. }
  3589. }
  3590. return out;
  3591. }
  3592. };
  3593. /**
  3594. Returns a view that formats the iterator range `[begin, end)` with elements
  3595. separated by `sep`.
  3596. */
  3597. template <typename It, typename Sentinel>
  3598. auto join(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel> {
  3599. return {begin, end, sep};
  3600. }
  3601. /**
  3602. \rst
  3603. Returns a view that formats `range` with elements separated by `sep`.
  3604. **Example**::
  3605. std::vector<int> v = {1, 2, 3};
  3606. fmt::print("{}", fmt::join(v, ", "));
  3607. // Output: "1, 2, 3"
  3608. ``fmt::join`` applies passed format specifiers to the range elements::
  3609. fmt::print("{:02}", fmt::join(v, ", "));
  3610. // Output: "01, 02, 03"
  3611. \endrst
  3612. */
  3613. template <typename Range>
  3614. auto join(Range&& range, string_view sep)
  3615. -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>> {
  3616. return join(std::begin(range), std::end(range), sep);
  3617. }
  3618. /**
  3619. \rst
  3620. Converts *value* to ``std::string`` using the default format for type *T*.
  3621. **Example**::
  3622. #include <fmt/format.h>
  3623. std::string answer = fmt::to_string(42);
  3624. \endrst
  3625. */
  3626. template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
  3627. inline auto to_string(const T& value) -> std::string {
  3628. auto result = std::string();
  3629. detail::write<char>(std::back_inserter(result), value);
  3630. return result;
  3631. }
  3632. template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
  3633. FMT_NODISCARD inline auto to_string(T value) -> std::string {
  3634. // The buffer should be large enough to store the number including the sign
  3635. // or "false" for bool.
  3636. constexpr int max_size = detail::digits10<T>() + 2;
  3637. char buffer[max_size > 5 ? static_cast<unsigned>(max_size) : 5];
  3638. char* begin = buffer;
  3639. return std::string(begin, detail::write<char>(begin, value));
  3640. }
  3641. template <typename Char, size_t SIZE>
  3642. FMT_NODISCARD auto to_string(const basic_memory_buffer<Char, SIZE>& buf)
  3643. -> std::basic_string<Char> {
  3644. auto size = buf.size();
  3645. detail::assume(size < std::basic_string<Char>().max_size());
  3646. return std::basic_string<Char>(buf.data(), size);
  3647. }
  3648. FMT_BEGIN_DETAIL_NAMESPACE
  3649. template <typename Char>
  3650. void vformat_to(
  3651. buffer<Char>& buf, basic_string_view<Char> fmt,
  3652. basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args,
  3653. locale_ref loc) {
  3654. // workaround for msvc bug regarding name-lookup in module
  3655. // link names into function scope
  3656. using detail::arg_formatter;
  3657. using detail::buffer_appender;
  3658. using detail::custom_formatter;
  3659. using detail::default_arg_formatter;
  3660. using detail::get_arg;
  3661. using detail::locale_ref;
  3662. using detail::parse_format_specs;
  3663. using detail::specs_checker;
  3664. using detail::specs_handler;
  3665. using detail::to_unsigned;
  3666. using detail::type;
  3667. using detail::write;
  3668. auto out = buffer_appender<Char>(buf);
  3669. if (fmt.size() == 2 && equal2(fmt.data(), "{}")) {
  3670. auto arg = args.get(0);
  3671. if (!arg) error_handler().on_error("argument not found");
  3672. visit_format_arg(default_arg_formatter<Char>{out, args, loc}, arg);
  3673. return;
  3674. }
  3675. struct format_handler : error_handler {
  3676. basic_format_parse_context<Char> parse_context;
  3677. buffer_context<Char> context;
  3678. format_handler(buffer_appender<Char> p_out, basic_string_view<Char> str,
  3679. basic_format_args<buffer_context<Char>> p_args,
  3680. locale_ref p_loc)
  3681. : parse_context(str), context(p_out, p_args, p_loc) {}
  3682. void on_text(const Char* begin, const Char* end) {
  3683. auto text = basic_string_view<Char>(begin, to_unsigned(end - begin));
  3684. context.advance_to(write<Char>(context.out(), text));
  3685. }
  3686. FMT_CONSTEXPR auto on_arg_id() -> int {
  3687. return parse_context.next_arg_id();
  3688. }
  3689. FMT_CONSTEXPR auto on_arg_id(int id) -> int {
  3690. return parse_context.check_arg_id(id), id;
  3691. }
  3692. FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
  3693. int arg_id = context.arg_id(id);
  3694. if (arg_id < 0) on_error("argument not found");
  3695. return arg_id;
  3696. }
  3697. FMT_INLINE void on_replacement_field(int id, const Char*) {
  3698. auto arg = get_arg(context, id);
  3699. context.advance_to(visit_format_arg(
  3700. default_arg_formatter<Char>{context.out(), context.args(),
  3701. context.locale()},
  3702. arg));
  3703. }
  3704. auto on_format_specs(int id, const Char* begin, const Char* end)
  3705. -> const Char* {
  3706. auto arg = get_arg(context, id);
  3707. if (arg.type() == type::custom_type) {
  3708. parse_context.advance_to(parse_context.begin() +
  3709. (begin - &*parse_context.begin()));
  3710. visit_format_arg(custom_formatter<Char>{parse_context, context}, arg);
  3711. return parse_context.begin();
  3712. }
  3713. auto specs = basic_format_specs<Char>();
  3714. specs_checker<specs_handler<Char>> handler(
  3715. specs_handler<Char>(specs, parse_context, context), arg.type());
  3716. begin = parse_format_specs(begin, end, handler);
  3717. if (begin == end || *begin != '}')
  3718. on_error("missing '}' in format string");
  3719. auto f = arg_formatter<Char>{context.out(), specs, context.locale()};
  3720. context.advance_to(visit_format_arg(f, arg));
  3721. return begin;
  3722. }
  3723. };
  3724. detail::parse_format_string<false>(fmt, format_handler(out, fmt, args, loc));
  3725. }
  3726. #ifndef FMT_HEADER_ONLY
  3727. extern template FMT_API auto thousands_sep_impl<char>(locale_ref)
  3728. -> thousands_sep_result<char>;
  3729. extern template FMT_API auto thousands_sep_impl<wchar_t>(locale_ref)
  3730. -> thousands_sep_result<wchar_t>;
  3731. extern template FMT_API auto decimal_point_impl(locale_ref) -> char;
  3732. extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t;
  3733. #endif // FMT_HEADER_ONLY
  3734. FMT_END_DETAIL_NAMESPACE
  3735. #if FMT_USE_USER_DEFINED_LITERALS
  3736. inline namespace literals {
  3737. /**
  3738. \rst
  3739. User-defined literal equivalent of :func:`fmt::arg`.
  3740. **Example**::
  3741. using namespace fmt::literals;
  3742. fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);
  3743. \endrst
  3744. */
  3745. # if FMT_USE_NONTYPE_TEMPLATE_ARGS
  3746. template <detail_exported::fixed_string Str> constexpr auto operator""_a() {
  3747. using char_t = remove_cvref_t<decltype(Str.data[0])>;
  3748. return detail::udl_arg<char_t, sizeof(Str.data) / sizeof(char_t), Str>();
  3749. }
  3750. # else
  3751. constexpr auto operator"" _a(const char* s, size_t) -> detail::udl_arg<char> {
  3752. return {s};
  3753. }
  3754. # endif
  3755. } // namespace literals
  3756. #endif // FMT_USE_USER_DEFINED_LITERALS
  3757. template <typename Locale, FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
  3758. inline auto vformat(const Locale& loc, string_view fmt, format_args args)
  3759. -> std::string {
  3760. return detail::vformat(loc, fmt, args);
  3761. }
  3762. template <typename Locale, typename... T,
  3763. FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
  3764. inline auto format(const Locale& loc, format_string<T...> fmt, T&&... args)
  3765. -> std::string {
  3766. return vformat(loc, string_view(fmt), fmt::make_format_args(args...));
  3767. }
  3768. template <typename OutputIt, typename Locale,
  3769. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value&&
  3770. detail::is_locale<Locale>::value)>
  3771. auto vformat_to(OutputIt out, const Locale& loc, string_view fmt,
  3772. format_args args) -> OutputIt {
  3773. using detail::get_buffer;
  3774. auto&& buf = get_buffer<char>(out);
  3775. detail::vformat_to(buf, fmt, args, detail::locale_ref(loc));
  3776. return detail::get_iterator(buf);
  3777. }
  3778. template <typename OutputIt, typename Locale, typename... T,
  3779. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value&&
  3780. detail::is_locale<Locale>::value)>
  3781. FMT_INLINE auto format_to(OutputIt out, const Locale& loc,
  3782. format_string<T...> fmt, T&&... args) -> OutputIt {
  3783. return vformat_to(out, loc, fmt, fmt::make_format_args(args...));
  3784. }
  3785. FMT_MODULE_EXPORT_END
  3786. FMT_END_NAMESPACE
  3787. #ifdef FMT_HEADER_ONLY
  3788. # define FMT_FUNC inline
  3789. # include "format-inl.h"
  3790. #else
  3791. # define FMT_FUNC
  3792. #endif
  3793. #endif // FMT_FORMAT_H_