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.

2122 lines
70 KiB

1 year ago
  1. // Formatting library for C++ - the core API
  2. //
  3. // Copyright (c) 2012 - present, Victor Zverovich
  4. // All rights reserved.
  5. //
  6. // For the license information refer to format.h.
  7. #ifndef FMT_CORE_H_
  8. #define FMT_CORE_H_
  9. #include <cstdio> // std::FILE
  10. #include <cstring>
  11. #include <functional>
  12. #include <iterator>
  13. #include <memory>
  14. #include <string>
  15. #include <type_traits>
  16. #include <vector>
  17. // The fmt library version in the form major * 10000 + minor * 100 + patch.
  18. #define FMT_VERSION 70103
  19. #ifdef __clang__
  20. # define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
  21. #else
  22. # define FMT_CLANG_VERSION 0
  23. #endif
  24. #if defined(__GNUC__) && !defined(__clang__)
  25. # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  26. #else
  27. # define FMT_GCC_VERSION 0
  28. #endif
  29. #if defined(__INTEL_COMPILER)
  30. # define FMT_ICC_VERSION __INTEL_COMPILER
  31. #else
  32. # define FMT_ICC_VERSION 0
  33. #endif
  34. #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
  35. # define FMT_HAS_GXX_CXX11 FMT_GCC_VERSION
  36. #else
  37. # define FMT_HAS_GXX_CXX11 0
  38. #endif
  39. #ifdef __NVCC__
  40. # define FMT_NVCC __NVCC__
  41. #else
  42. # define FMT_NVCC 0
  43. #endif
  44. #ifdef _MSC_VER
  45. # define FMT_MSC_VER _MSC_VER
  46. # define FMT_SUPPRESS_MSC_WARNING(n) __pragma(warning(suppress : n))
  47. #else
  48. # define FMT_MSC_VER 0
  49. # define FMT_SUPPRESS_MSC_WARNING(n)
  50. #endif
  51. #ifdef __has_feature
  52. # define FMT_HAS_FEATURE(x) __has_feature(x)
  53. #else
  54. # define FMT_HAS_FEATURE(x) 0
  55. #endif
  56. #if defined(__has_include) && !defined(__INTELLISENSE__) && \
  57. (!FMT_ICC_VERSION || FMT_ICC_VERSION >= 1600)
  58. # define FMT_HAS_INCLUDE(x) __has_include(x)
  59. #else
  60. # define FMT_HAS_INCLUDE(x) 0
  61. #endif
  62. #ifdef __has_cpp_attribute
  63. # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
  64. #else
  65. # define FMT_HAS_CPP_ATTRIBUTE(x) 0
  66. #endif
  67. #define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
  68. (__cplusplus >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
  69. #define FMT_HAS_CPP17_ATTRIBUTE(attribute) \
  70. (__cplusplus >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))
  71. // Check if relaxed C++14 constexpr is supported.
  72. // GCC doesn't allow throw in constexpr until version 6 (bug 67371).
  73. #ifndef FMT_USE_CONSTEXPR
  74. # define FMT_USE_CONSTEXPR \
  75. (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1910 || \
  76. (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) && \
  77. !FMT_NVCC && !FMT_ICC_VERSION
  78. #endif
  79. #if FMT_USE_CONSTEXPR
  80. # define FMT_CONSTEXPR constexpr
  81. # define FMT_CONSTEXPR_DECL constexpr
  82. #else
  83. # define FMT_CONSTEXPR inline
  84. # define FMT_CONSTEXPR_DECL
  85. #endif
  86. #ifndef FMT_OVERRIDE
  87. # if FMT_HAS_FEATURE(cxx_override_control) || \
  88. (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900
  89. # define FMT_OVERRIDE override
  90. # else
  91. # define FMT_OVERRIDE
  92. # endif
  93. #endif
  94. // Check if exceptions are disabled.
  95. #ifndef FMT_EXCEPTIONS
  96. # if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \
  97. FMT_MSC_VER && !_HAS_EXCEPTIONS
  98. # define FMT_EXCEPTIONS 0
  99. # else
  100. # define FMT_EXCEPTIONS 1
  101. # endif
  102. #endif
  103. // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature).
  104. #ifndef FMT_USE_NOEXCEPT
  105. # define FMT_USE_NOEXCEPT 0
  106. #endif
  107. #if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
  108. (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900
  109. # define FMT_DETECTED_NOEXCEPT noexcept
  110. # define FMT_HAS_CXX11_NOEXCEPT 1
  111. #else
  112. # define FMT_DETECTED_NOEXCEPT throw()
  113. # define FMT_HAS_CXX11_NOEXCEPT 0
  114. #endif
  115. #ifndef FMT_NOEXCEPT
  116. # if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT
  117. # define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT
  118. # else
  119. # define FMT_NOEXCEPT
  120. # endif
  121. #endif
  122. // [[noreturn]] is disabled on MSVC and NVCC because of bogus unreachable code
  123. // warnings.
  124. #if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VER && \
  125. !FMT_NVCC
  126. # define FMT_NORETURN [[noreturn]]
  127. #else
  128. # define FMT_NORETURN
  129. #endif
  130. #ifndef FMT_DEPRECATED
  131. # if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VER >= 1900
  132. # define FMT_DEPRECATED [[deprecated]]
  133. # else
  134. # if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__)
  135. # define FMT_DEPRECATED __attribute__((deprecated))
  136. # elif FMT_MSC_VER
  137. # define FMT_DEPRECATED __declspec(deprecated)
  138. # else
  139. # define FMT_DEPRECATED /* deprecated */
  140. # endif
  141. # endif
  142. #endif
  143. // Workaround broken [[deprecated]] in the Intel, PGI and NVCC compilers.
  144. #if FMT_ICC_VERSION || defined(__PGI) || FMT_NVCC
  145. # define FMT_DEPRECATED_ALIAS
  146. #else
  147. # define FMT_DEPRECATED_ALIAS FMT_DEPRECATED
  148. #endif
  149. #ifndef FMT_INLINE
  150. # if FMT_GCC_VERSION || FMT_CLANG_VERSION
  151. # define FMT_INLINE inline __attribute__((always_inline))
  152. # else
  153. # define FMT_INLINE inline
  154. # endif
  155. #endif
  156. #ifndef FMT_USE_INLINE_NAMESPACES
  157. # if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \
  158. (FMT_MSC_VER >= 1900 && !_MANAGED)
  159. # define FMT_USE_INLINE_NAMESPACES 1
  160. # else
  161. # define FMT_USE_INLINE_NAMESPACES 0
  162. # endif
  163. #endif
  164. #ifndef FMT_BEGIN_NAMESPACE
  165. # if FMT_USE_INLINE_NAMESPACES
  166. # define FMT_INLINE_NAMESPACE inline namespace
  167. # define FMT_END_NAMESPACE \
  168. } \
  169. }
  170. # else
  171. # define FMT_INLINE_NAMESPACE namespace
  172. # define FMT_END_NAMESPACE \
  173. } \
  174. using namespace v7; \
  175. }
  176. # endif
  177. # define FMT_BEGIN_NAMESPACE \
  178. namespace fmt { \
  179. FMT_INLINE_NAMESPACE v7 {
  180. #endif
  181. #if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
  182. # define FMT_CLASS_API FMT_SUPPRESS_MSC_WARNING(4275)
  183. # ifdef FMT_EXPORT
  184. # define FMT_API __declspec(dllexport)
  185. # define FMT_EXTERN_TEMPLATE_API FMT_API
  186. # define FMT_EXPORTED
  187. # elif defined(FMT_SHARED)
  188. # define FMT_API __declspec(dllimport)
  189. # define FMT_EXTERN_TEMPLATE_API FMT_API
  190. # endif
  191. #else
  192. # define FMT_CLASS_API
  193. #endif
  194. #ifndef FMT_API
  195. # define FMT_API
  196. #endif
  197. #ifndef FMT_EXTERN_TEMPLATE_API
  198. # define FMT_EXTERN_TEMPLATE_API
  199. #endif
  200. #ifndef FMT_INSTANTIATION_DEF_API
  201. # define FMT_INSTANTIATION_DEF_API FMT_API
  202. #endif
  203. #ifndef FMT_HEADER_ONLY
  204. # define FMT_EXTERN extern
  205. #else
  206. # define FMT_EXTERN
  207. #endif
  208. // libc++ supports string_view in pre-c++17.
  209. #if (FMT_HAS_INCLUDE(<string_view>) && \
  210. (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \
  211. (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910)
  212. # include <string_view>
  213. # define FMT_USE_STRING_VIEW
  214. #elif FMT_HAS_INCLUDE("experimental/string_view") && __cplusplus >= 201402L
  215. # include <experimental/string_view>
  216. # define FMT_USE_EXPERIMENTAL_STRING_VIEW
  217. #endif
  218. #ifndef FMT_UNICODE
  219. # define FMT_UNICODE !FMT_MSC_VER
  220. #endif
  221. #if FMT_UNICODE && FMT_MSC_VER
  222. # pragma execution_character_set("utf-8")
  223. #endif
  224. FMT_BEGIN_NAMESPACE
  225. // Implementations of enable_if_t and other metafunctions for older systems.
  226. template <bool B, class T = void>
  227. using enable_if_t = typename std::enable_if<B, T>::type;
  228. template <bool B, class T, class F>
  229. using conditional_t = typename std::conditional<B, T, F>::type;
  230. template <bool B> using bool_constant = std::integral_constant<bool, B>;
  231. template <typename T>
  232. using remove_reference_t = typename std::remove_reference<T>::type;
  233. template <typename T>
  234. using remove_const_t = typename std::remove_const<T>::type;
  235. template <typename T>
  236. using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
  237. template <typename T> struct type_identity { using type = T; };
  238. template <typename T> using type_identity_t = typename type_identity<T>::type;
  239. struct monostate {};
  240. // An enable_if helper to be used in template parameters which results in much
  241. // shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed
  242. // to workaround a bug in MSVC 2019 (see #1140 and #1186).
  243. #define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0
  244. namespace detail {
  245. // A helper function to suppress "conditional expression is constant" warnings.
  246. template <typename T> constexpr T const_check(T value) { return value; }
  247. FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
  248. const char* message);
  249. #ifndef FMT_ASSERT
  250. # ifdef NDEBUG
  251. // FMT_ASSERT is not empty to avoid -Werror=empty-body.
  252. # define FMT_ASSERT(condition, message) ((void)0)
  253. # else
  254. # define FMT_ASSERT(condition, message) \
  255. ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
  256. ? (void)0 \
  257. : ::fmt::detail::assert_fail(__FILE__, __LINE__, (message)))
  258. # endif
  259. #endif
  260. #if defined(FMT_USE_STRING_VIEW)
  261. template <typename Char> using std_string_view = std::basic_string_view<Char>;
  262. #elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW)
  263. template <typename Char>
  264. using std_string_view = std::experimental::basic_string_view<Char>;
  265. #else
  266. template <typename T> struct std_string_view {};
  267. #endif
  268. #ifdef FMT_USE_INT128
  269. // Do nothing.
  270. #elif defined(__SIZEOF_INT128__) && !FMT_NVCC && \
  271. !(FMT_CLANG_VERSION && FMT_MSC_VER)
  272. # define FMT_USE_INT128 1
  273. using int128_t = __int128_t;
  274. using uint128_t = __uint128_t;
  275. #else
  276. # define FMT_USE_INT128 0
  277. #endif
  278. #if !FMT_USE_INT128
  279. struct int128_t {};
  280. struct uint128_t {};
  281. #endif
  282. // Casts a nonnegative integer to unsigned.
  283. template <typename Int>
  284. FMT_CONSTEXPR typename std::make_unsigned<Int>::type to_unsigned(Int value) {
  285. FMT_ASSERT(value >= 0, "negative value");
  286. return static_cast<typename std::make_unsigned<Int>::type>(value);
  287. }
  288. FMT_SUPPRESS_MSC_WARNING(4566) constexpr unsigned char micro[] = "\u00B5";
  289. template <typename Char> constexpr bool is_unicode() {
  290. return FMT_UNICODE || sizeof(Char) != 1 ||
  291. (sizeof(micro) == 3 && micro[0] == 0xC2 && micro[1] == 0xB5);
  292. }
  293. #ifdef __cpp_char8_t
  294. using char8_type = char8_t;
  295. #else
  296. enum char8_type : unsigned char {};
  297. #endif
  298. } // namespace detail
  299. #ifdef FMT_USE_INTERNAL
  300. namespace internal = detail; // DEPRECATED
  301. #endif
  302. /**
  303. An implementation of ``std::basic_string_view`` for pre-C++17. It provides a
  304. subset of the API. ``fmt::basic_string_view`` is used for format strings even
  305. if ``std::string_view`` is available to prevent issues when a library is
  306. compiled with a different ``-std`` option than the client code (which is not
  307. recommended).
  308. */
  309. template <typename Char> class basic_string_view {
  310. private:
  311. const Char* data_;
  312. size_t size_;
  313. public:
  314. using value_type = Char;
  315. using iterator = const Char*;
  316. constexpr basic_string_view() FMT_NOEXCEPT : data_(nullptr), size_(0) {}
  317. /** Constructs a string reference object from a C string and a size. */
  318. constexpr basic_string_view(const Char* s, size_t count) FMT_NOEXCEPT
  319. : data_(s),
  320. size_(count) {}
  321. /**
  322. \rst
  323. Constructs a string reference object from a C string computing
  324. the size with ``std::char_traits<Char>::length``.
  325. \endrst
  326. */
  327. #if __cplusplus >= 201703L // C++17's char_traits::length() is constexpr.
  328. FMT_CONSTEXPR
  329. #endif
  330. basic_string_view(const Char* s)
  331. : data_(s), size_(std::char_traits<Char>::length(s)) {}
  332. /** Constructs a string reference from a ``std::basic_string`` object. */
  333. template <typename Traits, typename Alloc>
  334. FMT_CONSTEXPR basic_string_view(
  335. const std::basic_string<Char, Traits, Alloc>& s) FMT_NOEXCEPT
  336. : data_(s.data()),
  337. size_(s.size()) {}
  338. template <typename S, FMT_ENABLE_IF(std::is_same<
  339. S, detail::std_string_view<Char>>::value)>
  340. FMT_CONSTEXPR basic_string_view(S s) FMT_NOEXCEPT : data_(s.data()),
  341. size_(s.size()) {}
  342. /** Returns a pointer to the string data. */
  343. constexpr const Char* data() const { return data_; }
  344. /** Returns the string size. */
  345. constexpr size_t size() const { return size_; }
  346. constexpr iterator begin() const { return data_; }
  347. constexpr iterator end() const { return data_ + size_; }
  348. constexpr const Char& operator[](size_t pos) const { return data_[pos]; }
  349. FMT_CONSTEXPR void remove_prefix(size_t n) {
  350. data_ += n;
  351. size_ -= n;
  352. }
  353. // Lexicographically compare this string reference to other.
  354. int compare(basic_string_view other) const {
  355. size_t str_size = size_ < other.size_ ? size_ : other.size_;
  356. int result = std::char_traits<Char>::compare(data_, other.data_, str_size);
  357. if (result == 0)
  358. result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
  359. return result;
  360. }
  361. friend bool operator==(basic_string_view lhs, basic_string_view rhs) {
  362. return lhs.compare(rhs) == 0;
  363. }
  364. friend bool operator!=(basic_string_view lhs, basic_string_view rhs) {
  365. return lhs.compare(rhs) != 0;
  366. }
  367. friend bool operator<(basic_string_view lhs, basic_string_view rhs) {
  368. return lhs.compare(rhs) < 0;
  369. }
  370. friend bool operator<=(basic_string_view lhs, basic_string_view rhs) {
  371. return lhs.compare(rhs) <= 0;
  372. }
  373. friend bool operator>(basic_string_view lhs, basic_string_view rhs) {
  374. return lhs.compare(rhs) > 0;
  375. }
  376. friend bool operator>=(basic_string_view lhs, basic_string_view rhs) {
  377. return lhs.compare(rhs) >= 0;
  378. }
  379. };
  380. using string_view = basic_string_view<char>;
  381. using wstring_view = basic_string_view<wchar_t>;
  382. /** Specifies if ``T`` is a character type. Can be specialized by users. */
  383. template <typename T> struct is_char : std::false_type {};
  384. template <> struct is_char<char> : std::true_type {};
  385. template <> struct is_char<wchar_t> : std::true_type {};
  386. template <> struct is_char<detail::char8_type> : std::true_type {};
  387. template <> struct is_char<char16_t> : std::true_type {};
  388. template <> struct is_char<char32_t> : std::true_type {};
  389. /**
  390. \rst
  391. Returns a string view of `s`. In order to add custom string type support to
  392. {fmt} provide an overload of `to_string_view` for it in the same namespace as
  393. the type for the argument-dependent lookup to work.
  394. **Example**::
  395. namespace my_ns {
  396. inline string_view to_string_view(const my_string& s) {
  397. return {s.data(), s.length()};
  398. }
  399. }
  400. std::string message = fmt::format(my_string("The answer is {}"), 42);
  401. \endrst
  402. */
  403. template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
  404. inline basic_string_view<Char> to_string_view(const Char* s) {
  405. return s;
  406. }
  407. template <typename Char, typename Traits, typename Alloc>
  408. inline basic_string_view<Char> to_string_view(
  409. const std::basic_string<Char, Traits, Alloc>& s) {
  410. return s;
  411. }
  412. template <typename Char>
  413. inline basic_string_view<Char> to_string_view(basic_string_view<Char> s) {
  414. return s;
  415. }
  416. template <typename Char,
  417. FMT_ENABLE_IF(!std::is_empty<detail::std_string_view<Char>>::value)>
  418. inline basic_string_view<Char> to_string_view(detail::std_string_view<Char> s) {
  419. return s;
  420. }
  421. // A base class for compile-time strings. It is defined in the fmt namespace to
  422. // make formatting functions visible via ADL, e.g. format(FMT_STRING("{}"), 42).
  423. struct compile_string {};
  424. template <typename S>
  425. struct is_compile_string : std::is_base_of<compile_string, S> {};
  426. template <typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
  427. constexpr basic_string_view<typename S::char_type> to_string_view(const S& s) {
  428. return s;
  429. }
  430. namespace detail {
  431. void to_string_view(...);
  432. using fmt::v7::to_string_view;
  433. // Specifies whether S is a string type convertible to fmt::basic_string_view.
  434. // It should be a constexpr function but MSVC 2017 fails to compile it in
  435. // enable_if and MSVC 2015 fails to compile it as an alias template.
  436. template <typename S>
  437. struct is_string : std::is_class<decltype(to_string_view(std::declval<S>()))> {
  438. };
  439. template <typename S, typename = void> struct char_t_impl {};
  440. template <typename S> struct char_t_impl<S, enable_if_t<is_string<S>::value>> {
  441. using result = decltype(to_string_view(std::declval<S>()));
  442. using type = typename result::value_type;
  443. };
  444. // Reports a compile-time error if S is not a valid format string.
  445. template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
  446. FMT_INLINE void check_format_string(const S&) {
  447. #ifdef FMT_ENFORCE_COMPILE_STRING
  448. static_assert(is_compile_string<S>::value,
  449. "FMT_ENFORCE_COMPILE_STRING requires all format strings to use "
  450. "FMT_STRING.");
  451. #endif
  452. }
  453. template <typename..., typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
  454. void check_format_string(S);
  455. struct error_handler {
  456. constexpr error_handler() = default;
  457. constexpr error_handler(const error_handler&) = default;
  458. // This function is intentionally not constexpr to give a compile-time error.
  459. FMT_NORETURN FMT_API void on_error(const char* message);
  460. };
  461. } // namespace detail
  462. /** String's character type. */
  463. template <typename S> using char_t = typename detail::char_t_impl<S>::type;
  464. /**
  465. \rst
  466. Parsing context consisting of a format string range being parsed and an
  467. argument counter for automatic indexing.
  468. You can use one of the following type aliases for common character types:
  469. +-----------------------+-------------------------------------+
  470. | Type | Definition |
  471. +=======================+=====================================+
  472. | format_parse_context | basic_format_parse_context<char> |
  473. +-----------------------+-------------------------------------+
  474. | wformat_parse_context | basic_format_parse_context<wchar_t> |
  475. +-----------------------+-------------------------------------+
  476. \endrst
  477. */
  478. template <typename Char, typename ErrorHandler = detail::error_handler>
  479. class basic_format_parse_context : private ErrorHandler {
  480. private:
  481. basic_string_view<Char> format_str_;
  482. int next_arg_id_;
  483. public:
  484. using char_type = Char;
  485. using iterator = typename basic_string_view<Char>::iterator;
  486. explicit constexpr basic_format_parse_context(
  487. basic_string_view<Char> format_str, ErrorHandler eh = {},
  488. int next_arg_id = 0)
  489. : ErrorHandler(eh), format_str_(format_str), next_arg_id_(next_arg_id) {}
  490. /**
  491. Returns an iterator to the beginning of the format string range being
  492. parsed.
  493. */
  494. constexpr iterator begin() const FMT_NOEXCEPT { return format_str_.begin(); }
  495. /**
  496. Returns an iterator past the end of the format string range being parsed.
  497. */
  498. constexpr iterator end() const FMT_NOEXCEPT { return format_str_.end(); }
  499. /** Advances the begin iterator to ``it``. */
  500. FMT_CONSTEXPR void advance_to(iterator it) {
  501. format_str_.remove_prefix(detail::to_unsigned(it - begin()));
  502. }
  503. /**
  504. Reports an error if using the manual argument indexing; otherwise returns
  505. the next argument index and switches to the automatic indexing.
  506. */
  507. FMT_CONSTEXPR int next_arg_id() {
  508. // Don't check if the argument id is valid to avoid overhead and because it
  509. // will be checked during formatting anyway.
  510. if (next_arg_id_ >= 0) return next_arg_id_++;
  511. on_error("cannot switch from manual to automatic argument indexing");
  512. return 0;
  513. }
  514. /**
  515. Reports an error if using the automatic argument indexing; otherwise
  516. switches to the manual indexing.
  517. */
  518. FMT_CONSTEXPR void check_arg_id(int) {
  519. if (next_arg_id_ > 0)
  520. on_error("cannot switch from automatic to manual argument indexing");
  521. else
  522. next_arg_id_ = -1;
  523. }
  524. FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {}
  525. FMT_CONSTEXPR void on_error(const char* message) {
  526. ErrorHandler::on_error(message);
  527. }
  528. constexpr ErrorHandler error_handler() const { return *this; }
  529. };
  530. using format_parse_context = basic_format_parse_context<char>;
  531. using wformat_parse_context = basic_format_parse_context<wchar_t>;
  532. template <typename Context> class basic_format_arg;
  533. template <typename Context> class basic_format_args;
  534. template <typename Context> class dynamic_format_arg_store;
  535. // A formatter for objects of type T.
  536. template <typename T, typename Char = char, typename Enable = void>
  537. struct formatter {
  538. // A deleted default constructor indicates a disabled formatter.
  539. formatter() = delete;
  540. };
  541. // Specifies if T has an enabled formatter specialization. A type can be
  542. // formattable even if it doesn't have a formatter e.g. via a conversion.
  543. template <typename T, typename Context>
  544. using has_formatter =
  545. std::is_constructible<typename Context::template formatter_type<T>>;
  546. // Checks whether T is a container with contiguous storage.
  547. template <typename T> struct is_contiguous : std::false_type {};
  548. template <typename Char>
  549. struct is_contiguous<std::basic_string<Char>> : std::true_type {};
  550. namespace detail {
  551. // Extracts a reference to the container from back_insert_iterator.
  552. template <typename Container>
  553. inline Container& get_container(std::back_insert_iterator<Container> it) {
  554. using bi_iterator = std::back_insert_iterator<Container>;
  555. struct accessor : bi_iterator {
  556. accessor(bi_iterator iter) : bi_iterator(iter) {}
  557. using bi_iterator::container;
  558. };
  559. return *accessor(it).container;
  560. }
  561. /**
  562. \rst
  563. A contiguous memory buffer with an optional growing ability. It is an internal
  564. class and shouldn't be used directly, only via `~fmt::basic_memory_buffer`.
  565. \endrst
  566. */
  567. template <typename T> class buffer {
  568. private:
  569. T* ptr_;
  570. size_t size_;
  571. size_t capacity_;
  572. protected:
  573. // Don't initialize ptr_ since it is not accessed to save a few cycles.
  574. FMT_SUPPRESS_MSC_WARNING(26495)
  575. buffer(size_t sz) FMT_NOEXCEPT : size_(sz), capacity_(sz) {}
  576. buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) FMT_NOEXCEPT
  577. : ptr_(p),
  578. size_(sz),
  579. capacity_(cap) {}
  580. ~buffer() = default;
  581. /** Sets the buffer data and capacity. */
  582. void set(T* buf_data, size_t buf_capacity) FMT_NOEXCEPT {
  583. ptr_ = buf_data;
  584. capacity_ = buf_capacity;
  585. }
  586. /** Increases the buffer capacity to hold at least *capacity* elements. */
  587. virtual void grow(size_t capacity) = 0;
  588. public:
  589. using value_type = T;
  590. using const_reference = const T&;
  591. buffer(const buffer&) = delete;
  592. void operator=(const buffer&) = delete;
  593. T* begin() FMT_NOEXCEPT { return ptr_; }
  594. T* end() FMT_NOEXCEPT { return ptr_ + size_; }
  595. const T* begin() const FMT_NOEXCEPT { return ptr_; }
  596. const T* end() const FMT_NOEXCEPT { return ptr_ + size_; }
  597. /** Returns the size of this buffer. */
  598. size_t size() const FMT_NOEXCEPT { return size_; }
  599. /** Returns the capacity of this buffer. */
  600. size_t capacity() const FMT_NOEXCEPT { return capacity_; }
  601. /** Returns a pointer to the buffer data. */
  602. T* data() FMT_NOEXCEPT { return ptr_; }
  603. /** Returns a pointer to the buffer data. */
  604. const T* data() const FMT_NOEXCEPT { return ptr_; }
  605. /** Clears this buffer. */
  606. void clear() { size_ = 0; }
  607. // Tries resizing the buffer to contain *count* elements. If T is a POD type
  608. // the new elements may not be initialized.
  609. void try_resize(size_t count) {
  610. try_reserve(count);
  611. size_ = count <= capacity_ ? count : capacity_;
  612. }
  613. // Tries increasing the buffer capacity to *new_capacity*. It can increase the
  614. // capacity by a smaller amount than requested but guarantees there is space
  615. // for at least one additional element either by increasing the capacity or by
  616. // flushing the buffer if it is full.
  617. void try_reserve(size_t new_capacity) {
  618. if (new_capacity > capacity_) grow(new_capacity);
  619. }
  620. void push_back(const T& value) {
  621. try_reserve(size_ + 1);
  622. ptr_[size_++] = value;
  623. }
  624. /** Appends data to the end of the buffer. */
  625. template <typename U> void append(const U* begin, const U* end);
  626. template <typename I> T& operator[](I index) { return ptr_[index]; }
  627. template <typename I> const T& operator[](I index) const {
  628. return ptr_[index];
  629. }
  630. };
  631. struct buffer_traits {
  632. explicit buffer_traits(size_t) {}
  633. size_t count() const { return 0; }
  634. size_t limit(size_t size) { return size; }
  635. };
  636. class fixed_buffer_traits {
  637. private:
  638. size_t count_ = 0;
  639. size_t limit_;
  640. public:
  641. explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}
  642. size_t count() const { return count_; }
  643. size_t limit(size_t size) {
  644. size_t n = limit_ > count_ ? limit_ - count_ : 0;
  645. count_ += size;
  646. return size < n ? size : n;
  647. }
  648. };
  649. // A buffer that writes to an output iterator when flushed.
  650. template <typename OutputIt, typename T, typename Traits = buffer_traits>
  651. class iterator_buffer final : public Traits, public buffer<T> {
  652. private:
  653. OutputIt out_;
  654. enum { buffer_size = 256 };
  655. T data_[buffer_size];
  656. protected:
  657. void grow(size_t) final FMT_OVERRIDE {
  658. if (this->size() == buffer_size) flush();
  659. }
  660. void flush();
  661. public:
  662. explicit iterator_buffer(OutputIt out, size_t n = buffer_size)
  663. : Traits(n),
  664. buffer<T>(data_, 0, buffer_size),
  665. out_(out) {}
  666. ~iterator_buffer() { flush(); }
  667. OutputIt out() {
  668. flush();
  669. return out_;
  670. }
  671. size_t count() const { return Traits::count() + this->size(); }
  672. };
  673. template <typename T> class iterator_buffer<T*, T> final : public buffer<T> {
  674. protected:
  675. void grow(size_t) final FMT_OVERRIDE {}
  676. public:
  677. explicit iterator_buffer(T* out, size_t = 0) : buffer<T>(out, 0, ~size_t()) {}
  678. T* out() { return &*this->end(); }
  679. };
  680. // A buffer that writes to a container with the contiguous storage.
  681. template <typename Container>
  682. class iterator_buffer<std::back_insert_iterator<Container>,
  683. enable_if_t<is_contiguous<Container>::value,
  684. typename Container::value_type>>
  685. final : public buffer<typename Container::value_type> {
  686. private:
  687. Container& container_;
  688. protected:
  689. void grow(size_t capacity) final FMT_OVERRIDE {
  690. container_.resize(capacity);
  691. this->set(&container_[0], capacity);
  692. }
  693. public:
  694. explicit iterator_buffer(Container& c)
  695. : buffer<typename Container::value_type>(c.size()), container_(c) {}
  696. explicit iterator_buffer(std::back_insert_iterator<Container> out, size_t = 0)
  697. : iterator_buffer(get_container(out)) {}
  698. std::back_insert_iterator<Container> out() {
  699. return std::back_inserter(container_);
  700. }
  701. };
  702. // A buffer that counts the number of code units written discarding the output.
  703. template <typename T = char> class counting_buffer final : public buffer<T> {
  704. private:
  705. enum { buffer_size = 256 };
  706. T data_[buffer_size];
  707. size_t count_ = 0;
  708. protected:
  709. void grow(size_t) final FMT_OVERRIDE {
  710. if (this->size() != buffer_size) return;
  711. count_ += this->size();
  712. this->clear();
  713. }
  714. public:
  715. counting_buffer() : buffer<T>(data_, 0, buffer_size) {}
  716. size_t count() { return count_ + this->size(); }
  717. };
  718. // An output iterator that appends to the buffer.
  719. // It is used to reduce symbol sizes for the common case.
  720. template <typename T>
  721. class buffer_appender : public std::back_insert_iterator<buffer<T>> {
  722. using base = std::back_insert_iterator<buffer<T>>;
  723. public:
  724. explicit buffer_appender(buffer<T>& buf) : base(buf) {}
  725. buffer_appender(base it) : base(it) {}
  726. buffer_appender& operator++() {
  727. base::operator++();
  728. return *this;
  729. }
  730. buffer_appender operator++(int) {
  731. buffer_appender tmp = *this;
  732. ++*this;
  733. return tmp;
  734. }
  735. };
  736. // Maps an output iterator into a buffer.
  737. template <typename T, typename OutputIt>
  738. iterator_buffer<OutputIt, T> get_buffer(OutputIt);
  739. template <typename T> buffer<T>& get_buffer(buffer_appender<T>);
  740. template <typename OutputIt> OutputIt get_buffer_init(OutputIt out) {
  741. return out;
  742. }
  743. template <typename T> buffer<T>& get_buffer_init(buffer_appender<T> out) {
  744. return get_container(out);
  745. }
  746. template <typename Buffer>
  747. auto get_iterator(Buffer& buf) -> decltype(buf.out()) {
  748. return buf.out();
  749. }
  750. template <typename T> buffer_appender<T> get_iterator(buffer<T>& buf) {
  751. return buffer_appender<T>(buf);
  752. }
  753. template <typename T, typename Char = char, typename Enable = void>
  754. struct fallback_formatter {
  755. fallback_formatter() = delete;
  756. };
  757. // Specifies if T has an enabled fallback_formatter specialization.
  758. template <typename T, typename Context>
  759. using has_fallback_formatter =
  760. std::is_constructible<fallback_formatter<T, typename Context::char_type>>;
  761. struct view {};
  762. template <typename Char, typename T> struct named_arg : view {
  763. const Char* name;
  764. const T& value;
  765. named_arg(const Char* n, const T& v) : name(n), value(v) {}
  766. };
  767. template <typename Char> struct named_arg_info {
  768. const Char* name;
  769. int id;
  770. };
  771. template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
  772. struct arg_data {
  773. // args_[0].named_args points to named_args_ to avoid bloating format_args.
  774. // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
  775. T args_[1 + (NUM_ARGS != 0 ? NUM_ARGS : +1)];
  776. named_arg_info<Char> named_args_[NUM_NAMED_ARGS];
  777. template <typename... U>
  778. arg_data(const U&... init) : args_{T(named_args_, NUM_NAMED_ARGS), init...} {}
  779. arg_data(const arg_data& other) = delete;
  780. const T* args() const { return args_ + 1; }
  781. named_arg_info<Char>* named_args() { return named_args_; }
  782. };
  783. template <typename T, typename Char, size_t NUM_ARGS>
  784. struct arg_data<T, Char, NUM_ARGS, 0> {
  785. // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
  786. T args_[NUM_ARGS != 0 ? NUM_ARGS : +1];
  787. template <typename... U>
  788. FMT_INLINE arg_data(const U&... init) : args_{init...} {}
  789. FMT_INLINE const T* args() const { return args_; }
  790. FMT_INLINE std::nullptr_t named_args() { return nullptr; }
  791. };
  792. template <typename Char>
  793. inline void init_named_args(named_arg_info<Char>*, int, int) {}
  794. template <typename Char, typename T, typename... Tail>
  795. void init_named_args(named_arg_info<Char>* named_args, int arg_count,
  796. int named_arg_count, const T&, const Tail&... args) {
  797. init_named_args(named_args, arg_count + 1, named_arg_count, args...);
  798. }
  799. template <typename Char, typename T, typename... Tail>
  800. void init_named_args(named_arg_info<Char>* named_args, int arg_count,
  801. int named_arg_count, const named_arg<Char, T>& arg,
  802. const Tail&... args) {
  803. named_args[named_arg_count++] = {arg.name, arg_count};
  804. init_named_args(named_args, arg_count + 1, named_arg_count, args...);
  805. }
  806. template <typename... Args>
  807. FMT_INLINE void init_named_args(std::nullptr_t, int, int, const Args&...) {}
  808. template <typename T> struct is_named_arg : std::false_type {};
  809. template <typename T, typename Char>
  810. struct is_named_arg<named_arg<Char, T>> : std::true_type {};
  811. template <bool B = false> constexpr size_t count() { return B ? 1 : 0; }
  812. template <bool B1, bool B2, bool... Tail> constexpr size_t count() {
  813. return (B1 ? 1 : 0) + count<B2, Tail...>();
  814. }
  815. template <typename... Args> constexpr size_t count_named_args() {
  816. return count<is_named_arg<Args>::value...>();
  817. }
  818. enum class type {
  819. none_type,
  820. // Integer types should go first,
  821. int_type,
  822. uint_type,
  823. long_long_type,
  824. ulong_long_type,
  825. int128_type,
  826. uint128_type,
  827. bool_type,
  828. char_type,
  829. last_integer_type = char_type,
  830. // followed by floating-point types.
  831. float_type,
  832. double_type,
  833. long_double_type,
  834. last_numeric_type = long_double_type,
  835. cstring_type,
  836. string_type,
  837. pointer_type,
  838. custom_type
  839. };
  840. // Maps core type T to the corresponding type enum constant.
  841. template <typename T, typename Char>
  842. struct type_constant : std::integral_constant<type, type::custom_type> {};
  843. #define FMT_TYPE_CONSTANT(Type, constant) \
  844. template <typename Char> \
  845. struct type_constant<Type, Char> \
  846. : std::integral_constant<type, type::constant> {}
  847. FMT_TYPE_CONSTANT(int, int_type);
  848. FMT_TYPE_CONSTANT(unsigned, uint_type);
  849. FMT_TYPE_CONSTANT(long long, long_long_type);
  850. FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
  851. FMT_TYPE_CONSTANT(int128_t, int128_type);
  852. FMT_TYPE_CONSTANT(uint128_t, uint128_type);
  853. FMT_TYPE_CONSTANT(bool, bool_type);
  854. FMT_TYPE_CONSTANT(Char, char_type);
  855. FMT_TYPE_CONSTANT(float, float_type);
  856. FMT_TYPE_CONSTANT(double, double_type);
  857. FMT_TYPE_CONSTANT(long double, long_double_type);
  858. FMT_TYPE_CONSTANT(const Char*, cstring_type);
  859. FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
  860. FMT_TYPE_CONSTANT(const void*, pointer_type);
  861. constexpr bool is_integral_type(type t) {
  862. return t > type::none_type && t <= type::last_integer_type;
  863. }
  864. constexpr bool is_arithmetic_type(type t) {
  865. return t > type::none_type && t <= type::last_numeric_type;
  866. }
  867. template <typename Char> struct string_value {
  868. const Char* data;
  869. size_t size;
  870. };
  871. template <typename Char> struct named_arg_value {
  872. const named_arg_info<Char>* data;
  873. size_t size;
  874. };
  875. template <typename Context> struct custom_value {
  876. using parse_context = typename Context::parse_context_type;
  877. const void* value;
  878. void (*format)(const void* arg, parse_context& parse_ctx, Context& ctx);
  879. };
  880. // A formatting argument value.
  881. template <typename Context> class value {
  882. public:
  883. using char_type = typename Context::char_type;
  884. union {
  885. int int_value;
  886. unsigned uint_value;
  887. long long long_long_value;
  888. unsigned long long ulong_long_value;
  889. int128_t int128_value;
  890. uint128_t uint128_value;
  891. bool bool_value;
  892. char_type char_value;
  893. float float_value;
  894. double double_value;
  895. long double long_double_value;
  896. const void* pointer;
  897. string_value<char_type> string;
  898. custom_value<Context> custom;
  899. named_arg_value<char_type> named_args;
  900. };
  901. constexpr FMT_INLINE value(int val = 0) : int_value(val) {}
  902. constexpr FMT_INLINE value(unsigned val) : uint_value(val) {}
  903. FMT_INLINE value(long long val) : long_long_value(val) {}
  904. FMT_INLINE value(unsigned long long val) : ulong_long_value(val) {}
  905. FMT_INLINE value(int128_t val) : int128_value(val) {}
  906. FMT_INLINE value(uint128_t val) : uint128_value(val) {}
  907. FMT_INLINE value(float val) : float_value(val) {}
  908. FMT_INLINE value(double val) : double_value(val) {}
  909. FMT_INLINE value(long double val) : long_double_value(val) {}
  910. FMT_INLINE value(bool val) : bool_value(val) {}
  911. FMT_INLINE value(char_type val) : char_value(val) {}
  912. FMT_INLINE value(const char_type* val) { string.data = val; }
  913. FMT_INLINE value(basic_string_view<char_type> val) {
  914. string.data = val.data();
  915. string.size = val.size();
  916. }
  917. FMT_INLINE value(const void* val) : pointer(val) {}
  918. FMT_INLINE value(const named_arg_info<char_type>* args, size_t size)
  919. : named_args{args, size} {}
  920. template <typename T> FMT_INLINE value(const T& val) {
  921. custom.value = &val;
  922. // Get the formatter type through the context to allow different contexts
  923. // have different extension points, e.g. `formatter<T>` for `format` and
  924. // `printf_formatter<T>` for `printf`.
  925. custom.format = format_custom_arg<
  926. T, conditional_t<has_formatter<T, Context>::value,
  927. typename Context::template formatter_type<T>,
  928. fallback_formatter<T, char_type>>>;
  929. }
  930. private:
  931. // Formats an argument of a custom type, such as a user-defined class.
  932. template <typename T, typename Formatter>
  933. static void format_custom_arg(const void* arg,
  934. typename Context::parse_context_type& parse_ctx,
  935. Context& ctx) {
  936. Formatter f;
  937. parse_ctx.advance_to(f.parse(parse_ctx));
  938. ctx.advance_to(f.format(*static_cast<const T*>(arg), ctx));
  939. }
  940. };
  941. template <typename Context, typename T>
  942. FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value);
  943. // To minimize the number of types we need to deal with, long is translated
  944. // either to int or to long long depending on its size.
  945. enum { long_short = sizeof(long) == sizeof(int) };
  946. using long_type = conditional_t<long_short, int, long long>;
  947. using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
  948. struct unformattable {};
  949. // Maps formatting arguments to core types.
  950. template <typename Context> struct arg_mapper {
  951. using char_type = typename Context::char_type;
  952. FMT_CONSTEXPR int map(signed char val) { return val; }
  953. FMT_CONSTEXPR unsigned map(unsigned char val) { return val; }
  954. FMT_CONSTEXPR int map(short val) { return val; }
  955. FMT_CONSTEXPR unsigned map(unsigned short val) { return val; }
  956. FMT_CONSTEXPR int map(int val) { return val; }
  957. FMT_CONSTEXPR unsigned map(unsigned val) { return val; }
  958. FMT_CONSTEXPR long_type map(long val) { return val; }
  959. FMT_CONSTEXPR ulong_type map(unsigned long val) { return val; }
  960. FMT_CONSTEXPR long long map(long long val) { return val; }
  961. FMT_CONSTEXPR unsigned long long map(unsigned long long val) { return val; }
  962. FMT_CONSTEXPR int128_t map(int128_t val) { return val; }
  963. FMT_CONSTEXPR uint128_t map(uint128_t val) { return val; }
  964. FMT_CONSTEXPR bool map(bool val) { return val; }
  965. template <typename T, FMT_ENABLE_IF(is_char<T>::value)>
  966. FMT_CONSTEXPR char_type map(T val) {
  967. static_assert(
  968. std::is_same<T, char>::value || std::is_same<T, char_type>::value,
  969. "mixing character types is disallowed");
  970. return val;
  971. }
  972. FMT_CONSTEXPR float map(float val) { return val; }
  973. FMT_CONSTEXPR double map(double val) { return val; }
  974. FMT_CONSTEXPR long double map(long double val) { return val; }
  975. FMT_CONSTEXPR const char_type* map(char_type* val) { return val; }
  976. FMT_CONSTEXPR const char_type* map(const char_type* val) { return val; }
  977. template <typename T, FMT_ENABLE_IF(is_string<T>::value)>
  978. FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
  979. static_assert(std::is_same<char_type, char_t<T>>::value,
  980. "mixing character types is disallowed");
  981. return to_string_view(val);
  982. }
  983. template <typename T,
  984. FMT_ENABLE_IF(
  985. std::is_constructible<basic_string_view<char_type>, T>::value &&
  986. !is_string<T>::value && !has_formatter<T, Context>::value &&
  987. !has_fallback_formatter<T, Context>::value)>
  988. FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
  989. return basic_string_view<char_type>(val);
  990. }
  991. template <
  992. typename T,
  993. FMT_ENABLE_IF(
  994. std::is_constructible<std_string_view<char_type>, T>::value &&
  995. !std::is_constructible<basic_string_view<char_type>, T>::value &&
  996. !is_string<T>::value && !has_formatter<T, Context>::value &&
  997. !has_fallback_formatter<T, Context>::value)>
  998. FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
  999. return std_string_view<char_type>(val);
  1000. }
  1001. FMT_CONSTEXPR const char* map(const signed char* val) {
  1002. static_assert(std::is_same<char_type, char>::value, "invalid string type");
  1003. return reinterpret_cast<const char*>(val);
  1004. }
  1005. FMT_CONSTEXPR const char* map(const unsigned char* val) {
  1006. static_assert(std::is_same<char_type, char>::value, "invalid string type");
  1007. return reinterpret_cast<const char*>(val);
  1008. }
  1009. FMT_CONSTEXPR const char* map(signed char* val) {
  1010. const auto* const_val = val;
  1011. return map(const_val);
  1012. }
  1013. FMT_CONSTEXPR const char* map(unsigned char* val) {
  1014. const auto* const_val = val;
  1015. return map(const_val);
  1016. }
  1017. FMT_CONSTEXPR const void* map(void* val) { return val; }
  1018. FMT_CONSTEXPR const void* map(const void* val) { return val; }
  1019. FMT_CONSTEXPR const void* map(std::nullptr_t val) { return val; }
  1020. template <typename T> FMT_CONSTEXPR int map(const T*) {
  1021. // Formatting of arbitrary pointers is disallowed. If you want to output
  1022. // a pointer cast it to "void *" or "const void *". In particular, this
  1023. // forbids formatting of "[const] volatile char *" which is printed as bool
  1024. // by iostreams.
  1025. static_assert(!sizeof(T), "formatting of non-void pointers is disallowed");
  1026. return 0;
  1027. }
  1028. template <typename T,
  1029. FMT_ENABLE_IF(std::is_enum<T>::value &&
  1030. !has_formatter<T, Context>::value &&
  1031. !has_fallback_formatter<T, Context>::value)>
  1032. FMT_CONSTEXPR auto map(const T& val)
  1033. -> decltype(std::declval<arg_mapper>().map(
  1034. static_cast<typename std::underlying_type<T>::type>(val))) {
  1035. return map(static_cast<typename std::underlying_type<T>::type>(val));
  1036. }
  1037. template <typename T,
  1038. FMT_ENABLE_IF(!is_string<T>::value && !is_char<T>::value &&
  1039. (has_formatter<T, Context>::value ||
  1040. has_fallback_formatter<T, Context>::value))>
  1041. FMT_CONSTEXPR const T& map(const T& val) {
  1042. return val;
  1043. }
  1044. template <typename T>
  1045. FMT_CONSTEXPR auto map(const named_arg<char_type, T>& val)
  1046. -> decltype(std::declval<arg_mapper>().map(val.value)) {
  1047. return map(val.value);
  1048. }
  1049. unformattable map(...) { return {}; }
  1050. };
  1051. // A type constant after applying arg_mapper<Context>.
  1052. template <typename T, typename Context>
  1053. using mapped_type_constant =
  1054. type_constant<decltype(arg_mapper<Context>().map(std::declval<const T&>())),
  1055. typename Context::char_type>;
  1056. enum { packed_arg_bits = 4 };
  1057. // Maximum number of arguments with packed types.
  1058. enum { max_packed_args = 62 / packed_arg_bits };
  1059. enum : unsigned long long { is_unpacked_bit = 1ULL << 63 };
  1060. enum : unsigned long long { has_named_args_bit = 1ULL << 62 };
  1061. } // namespace detail
  1062. // A formatting argument. It is a trivially copyable/constructible type to
  1063. // allow storage in basic_memory_buffer.
  1064. template <typename Context> class basic_format_arg {
  1065. private:
  1066. detail::value<Context> value_;
  1067. detail::type type_;
  1068. template <typename ContextType, typename T>
  1069. friend FMT_CONSTEXPR basic_format_arg<ContextType> detail::make_arg(
  1070. const T& value);
  1071. template <typename Visitor, typename Ctx>
  1072. friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis,
  1073. const basic_format_arg<Ctx>& arg)
  1074. -> decltype(vis(0));
  1075. friend class basic_format_args<Context>;
  1076. friend class dynamic_format_arg_store<Context>;
  1077. using char_type = typename Context::char_type;
  1078. template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
  1079. friend struct detail::arg_data;
  1080. basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)
  1081. : value_(args, size) {}
  1082. public:
  1083. class handle {
  1084. public:
  1085. explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}
  1086. void format(typename Context::parse_context_type& parse_ctx,
  1087. Context& ctx) const {
  1088. custom_.format(custom_.value, parse_ctx, ctx);
  1089. }
  1090. private:
  1091. detail::custom_value<Context> custom_;
  1092. };
  1093. constexpr basic_format_arg() : type_(detail::type::none_type) {}
  1094. constexpr explicit operator bool() const FMT_NOEXCEPT {
  1095. return type_ != detail::type::none_type;
  1096. }
  1097. detail::type type() const { return type_; }
  1098. bool is_integral() const { return detail::is_integral_type(type_); }
  1099. bool is_arithmetic() const { return detail::is_arithmetic_type(type_); }
  1100. };
  1101. /**
  1102. \rst
  1103. Visits an argument dispatching to the appropriate visit method based on
  1104. the argument type. For example, if the argument type is ``double`` then
  1105. ``vis(value)`` will be called with the value of type ``double``.
  1106. \endrst
  1107. */
  1108. template <typename Visitor, typename Context>
  1109. FMT_CONSTEXPR_DECL FMT_INLINE auto visit_format_arg(
  1110. Visitor&& vis, const basic_format_arg<Context>& arg) -> decltype(vis(0)) {
  1111. using char_type = typename Context::char_type;
  1112. switch (arg.type_) {
  1113. case detail::type::none_type:
  1114. break;
  1115. case detail::type::int_type:
  1116. return vis(arg.value_.int_value);
  1117. case detail::type::uint_type:
  1118. return vis(arg.value_.uint_value);
  1119. case detail::type::long_long_type:
  1120. return vis(arg.value_.long_long_value);
  1121. case detail::type::ulong_long_type:
  1122. return vis(arg.value_.ulong_long_value);
  1123. #if FMT_USE_INT128
  1124. case detail::type::int128_type:
  1125. return vis(arg.value_.int128_value);
  1126. case detail::type::uint128_type:
  1127. return vis(arg.value_.uint128_value);
  1128. #else
  1129. case detail::type::int128_type:
  1130. case detail::type::uint128_type:
  1131. break;
  1132. #endif
  1133. case detail::type::bool_type:
  1134. return vis(arg.value_.bool_value);
  1135. case detail::type::char_type:
  1136. return vis(arg.value_.char_value);
  1137. case detail::type::float_type:
  1138. return vis(arg.value_.float_value);
  1139. case detail::type::double_type:
  1140. return vis(arg.value_.double_value);
  1141. case detail::type::long_double_type:
  1142. return vis(arg.value_.long_double_value);
  1143. case detail::type::cstring_type:
  1144. return vis(arg.value_.string.data);
  1145. case detail::type::string_type:
  1146. return vis(basic_string_view<char_type>(arg.value_.string.data,
  1147. arg.value_.string.size));
  1148. case detail::type::pointer_type:
  1149. return vis(arg.value_.pointer);
  1150. case detail::type::custom_type:
  1151. return vis(typename basic_format_arg<Context>::handle(arg.value_.custom));
  1152. }
  1153. return vis(monostate());
  1154. }
  1155. template <typename T> struct formattable : std::false_type {};
  1156. namespace detail {
  1157. // A workaround for gcc 4.8 to make void_t work in a SFINAE context.
  1158. template <typename... Ts> struct void_t_impl { using type = void; };
  1159. template <typename... Ts>
  1160. using void_t = typename detail::void_t_impl<Ts...>::type;
  1161. template <typename It, typename T, typename Enable = void>
  1162. struct is_output_iterator : std::false_type {};
  1163. template <typename It, typename T>
  1164. struct is_output_iterator<
  1165. It, T,
  1166. void_t<typename std::iterator_traits<It>::iterator_category,
  1167. decltype(*std::declval<It>() = std::declval<T>())>>
  1168. : std::true_type {};
  1169. template <typename OutputIt>
  1170. struct is_back_insert_iterator : std::false_type {};
  1171. template <typename Container>
  1172. struct is_back_insert_iterator<std::back_insert_iterator<Container>>
  1173. : std::true_type {};
  1174. template <typename OutputIt>
  1175. struct is_contiguous_back_insert_iterator : std::false_type {};
  1176. template <typename Container>
  1177. struct is_contiguous_back_insert_iterator<std::back_insert_iterator<Container>>
  1178. : is_contiguous<Container> {};
  1179. template <typename Char>
  1180. struct is_contiguous_back_insert_iterator<buffer_appender<Char>>
  1181. : std::true_type {};
  1182. // A type-erased reference to an std::locale to avoid heavy <locale> include.
  1183. class locale_ref {
  1184. private:
  1185. const void* locale_; // A type-erased pointer to std::locale.
  1186. public:
  1187. locale_ref() : locale_(nullptr) {}
  1188. template <typename Locale> explicit locale_ref(const Locale& loc);
  1189. explicit operator bool() const FMT_NOEXCEPT { return locale_ != nullptr; }
  1190. template <typename Locale> Locale get() const;
  1191. };
  1192. template <typename> constexpr unsigned long long encode_types() { return 0; }
  1193. template <typename Context, typename Arg, typename... Args>
  1194. constexpr unsigned long long encode_types() {
  1195. return static_cast<unsigned>(mapped_type_constant<Arg, Context>::value) |
  1196. (encode_types<Context, Args...>() << packed_arg_bits);
  1197. }
  1198. template <typename Context, typename T>
  1199. FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value) {
  1200. basic_format_arg<Context> arg;
  1201. arg.type_ = mapped_type_constant<T, Context>::value;
  1202. arg.value_ = arg_mapper<Context>().map(value);
  1203. return arg;
  1204. }
  1205. template <typename T> int check(unformattable) {
  1206. static_assert(
  1207. formattable<T>(),
  1208. "Cannot format an argument. To make type T formattable provide a "
  1209. "formatter<T> specialization: https://fmt.dev/latest/api.html#udt");
  1210. return 0;
  1211. }
  1212. template <typename T, typename U> inline const U& check(const U& val) {
  1213. return val;
  1214. }
  1215. // The type template parameter is there to avoid an ODR violation when using
  1216. // a fallback formatter in one translation unit and an implicit conversion in
  1217. // another (not recommended).
  1218. template <bool IS_PACKED, typename Context, type, typename T,
  1219. FMT_ENABLE_IF(IS_PACKED)>
  1220. inline value<Context> make_arg(const T& val) {
  1221. return check<T>(arg_mapper<Context>().map(val));
  1222. }
  1223. template <bool IS_PACKED, typename Context, type, typename T,
  1224. FMT_ENABLE_IF(!IS_PACKED)>
  1225. inline basic_format_arg<Context> make_arg(const T& value) {
  1226. return make_arg<Context>(value);
  1227. }
  1228. template <typename T> struct is_reference_wrapper : std::false_type {};
  1229. template <typename T>
  1230. struct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type {};
  1231. template <typename T> const T& unwrap(const T& v) { return v; }
  1232. template <typename T> const T& unwrap(const std::reference_wrapper<T>& v) {
  1233. return static_cast<const T&>(v);
  1234. }
  1235. class dynamic_arg_list {
  1236. // Workaround for clang's -Wweak-vtables. Unlike for regular classes, for
  1237. // templates it doesn't complain about inability to deduce single translation
  1238. // unit for placing vtable. So storage_node_base is made a fake template.
  1239. template <typename = void> struct node {
  1240. virtual ~node() = default;
  1241. std::unique_ptr<node<>> next;
  1242. };
  1243. template <typename T> struct typed_node : node<> {
  1244. T value;
  1245. template <typename Arg>
  1246. FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {}
  1247. template <typename Char>
  1248. FMT_CONSTEXPR typed_node(const basic_string_view<Char>& arg)
  1249. : value(arg.data(), arg.size()) {}
  1250. };
  1251. std::unique_ptr<node<>> head_;
  1252. public:
  1253. template <typename T, typename Arg> const T& push(const Arg& arg) {
  1254. auto new_node = std::unique_ptr<typed_node<T>>(new typed_node<T>(arg));
  1255. auto& value = new_node->value;
  1256. new_node->next = std::move(head_);
  1257. head_ = std::move(new_node);
  1258. return value;
  1259. }
  1260. };
  1261. } // namespace detail
  1262. // Formatting context.
  1263. template <typename OutputIt, typename Char> class basic_format_context {
  1264. public:
  1265. /** The character type for the output. */
  1266. using char_type = Char;
  1267. private:
  1268. OutputIt out_;
  1269. basic_format_args<basic_format_context> args_;
  1270. detail::locale_ref loc_;
  1271. public:
  1272. using iterator = OutputIt;
  1273. using format_arg = basic_format_arg<basic_format_context>;
  1274. using parse_context_type = basic_format_parse_context<Char>;
  1275. template <typename T> using formatter_type = formatter<T, char_type>;
  1276. basic_format_context(const basic_format_context&) = delete;
  1277. void operator=(const basic_format_context&) = delete;
  1278. /**
  1279. Constructs a ``basic_format_context`` object. References to the arguments are
  1280. stored in the object so make sure they have appropriate lifetimes.
  1281. */
  1282. basic_format_context(OutputIt out,
  1283. basic_format_args<basic_format_context> ctx_args,
  1284. detail::locale_ref loc = detail::locale_ref())
  1285. : out_(out), args_(ctx_args), loc_(loc) {}
  1286. format_arg arg(int id) const { return args_.get(id); }
  1287. format_arg arg(basic_string_view<char_type> name) { return args_.get(name); }
  1288. int arg_id(basic_string_view<char_type> name) { return args_.get_id(name); }
  1289. const basic_format_args<basic_format_context>& args() const { return args_; }
  1290. detail::error_handler error_handler() { return {}; }
  1291. void on_error(const char* message) { error_handler().on_error(message); }
  1292. // Returns an iterator to the beginning of the output range.
  1293. iterator out() { return out_; }
  1294. // Advances the begin iterator to ``it``.
  1295. void advance_to(iterator it) {
  1296. if (!detail::is_back_insert_iterator<iterator>()) out_ = it;
  1297. }
  1298. detail::locale_ref locale() { return loc_; }
  1299. };
  1300. template <typename Char>
  1301. using buffer_context =
  1302. basic_format_context<detail::buffer_appender<Char>, Char>;
  1303. using format_context = buffer_context<char>;
  1304. using wformat_context = buffer_context<wchar_t>;
  1305. // Workaround an alias issue: https://stackoverflow.com/q/62767544/471164.
  1306. #define FMT_BUFFER_CONTEXT(Char) \
  1307. basic_format_context<detail::buffer_appender<Char>, Char>
  1308. /**
  1309. \rst
  1310. An array of references to arguments. It can be implicitly converted into
  1311. `~fmt::basic_format_args` for passing into type-erased formatting functions
  1312. such as `~fmt::vformat`.
  1313. \endrst
  1314. */
  1315. template <typename Context, typename... Args>
  1316. class format_arg_store
  1317. #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
  1318. // Workaround a GCC template argument substitution bug.
  1319. : public basic_format_args<Context>
  1320. #endif
  1321. {
  1322. private:
  1323. static const size_t num_args = sizeof...(Args);
  1324. static const size_t num_named_args = detail::count_named_args<Args...>();
  1325. static const bool is_packed = num_args <= detail::max_packed_args;
  1326. using value_type = conditional_t<is_packed, detail::value<Context>,
  1327. basic_format_arg<Context>>;
  1328. detail::arg_data<value_type, typename Context::char_type, num_args,
  1329. num_named_args>
  1330. data_;
  1331. friend class basic_format_args<Context>;
  1332. static constexpr unsigned long long desc =
  1333. (is_packed ? detail::encode_types<Context, Args...>()
  1334. : detail::is_unpacked_bit | num_args) |
  1335. (num_named_args != 0
  1336. ? static_cast<unsigned long long>(detail::has_named_args_bit)
  1337. : 0);
  1338. public:
  1339. format_arg_store(const Args&... args)
  1340. :
  1341. #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
  1342. basic_format_args<Context>(*this),
  1343. #endif
  1344. data_{detail::make_arg<
  1345. is_packed, Context,
  1346. detail::mapped_type_constant<Args, Context>::value>(args)...} {
  1347. detail::init_named_args(data_.named_args(), 0, 0, args...);
  1348. }
  1349. };
  1350. /**
  1351. \rst
  1352. Constructs a `~fmt::format_arg_store` object that contains references to
  1353. arguments and can be implicitly converted to `~fmt::format_args`. `Context`
  1354. can be omitted in which case it defaults to `~fmt::context`.
  1355. See `~fmt::arg` for lifetime considerations.
  1356. \endrst
  1357. */
  1358. template <typename Context = format_context, typename... Args>
  1359. inline format_arg_store<Context, Args...> make_format_args(
  1360. const Args&... args) {
  1361. return {args...};
  1362. }
  1363. /**
  1364. \rst
  1365. Constructs a `~fmt::format_arg_store` object that contains references
  1366. to arguments and can be implicitly converted to `~fmt::format_args`.
  1367. If ``format_str`` is a compile-time string then `make_args_checked` checks
  1368. its validity at compile time.
  1369. \endrst
  1370. */
  1371. template <typename... Args, typename S, typename Char = char_t<S>>
  1372. inline auto make_args_checked(const S& format_str,
  1373. const remove_reference_t<Args>&... args)
  1374. -> format_arg_store<buffer_context<Char>, remove_reference_t<Args>...> {
  1375. static_assert(
  1376. detail::count<(
  1377. std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
  1378. std::is_reference<Args>::value)...>() == 0,
  1379. "passing views as lvalues is disallowed");
  1380. detail::check_format_string<Args...>(format_str);
  1381. return {args...};
  1382. }
  1383. /**
  1384. \rst
  1385. Returns a named argument to be used in a formatting function. It should only
  1386. be used in a call to a formatting function.
  1387. **Example**::
  1388. fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23));
  1389. \endrst
  1390. */
  1391. template <typename Char, typename T>
  1392. inline detail::named_arg<Char, T> arg(const Char* name, const T& arg) {
  1393. static_assert(!detail::is_named_arg<T>(), "nested named arguments");
  1394. return {name, arg};
  1395. }
  1396. /**
  1397. \rst
  1398. A dynamic version of `fmt::format_arg_store`.
  1399. It's equipped with a storage to potentially temporary objects which lifetimes
  1400. could be shorter than the format arguments object.
  1401. It can be implicitly converted into `~fmt::basic_format_args` for passing
  1402. into type-erased formatting functions such as `~fmt::vformat`.
  1403. \endrst
  1404. */
  1405. template <typename Context>
  1406. class dynamic_format_arg_store
  1407. #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
  1408. // Workaround a GCC template argument substitution bug.
  1409. : public basic_format_args<Context>
  1410. #endif
  1411. {
  1412. private:
  1413. using char_type = typename Context::char_type;
  1414. template <typename T> struct need_copy {
  1415. static constexpr detail::type mapped_type =
  1416. detail::mapped_type_constant<T, Context>::value;
  1417. enum {
  1418. value = !(detail::is_reference_wrapper<T>::value ||
  1419. std::is_same<T, basic_string_view<char_type>>::value ||
  1420. std::is_same<T, detail::std_string_view<char_type>>::value ||
  1421. (mapped_type != detail::type::cstring_type &&
  1422. mapped_type != detail::type::string_type &&
  1423. mapped_type != detail::type::custom_type))
  1424. };
  1425. };
  1426. template <typename T>
  1427. using stored_type = conditional_t<detail::is_string<T>::value,
  1428. std::basic_string<char_type>, T>;
  1429. // Storage of basic_format_arg must be contiguous.
  1430. std::vector<basic_format_arg<Context>> data_;
  1431. std::vector<detail::named_arg_info<char_type>> named_info_;
  1432. // Storage of arguments not fitting into basic_format_arg must grow
  1433. // without relocation because items in data_ refer to it.
  1434. detail::dynamic_arg_list dynamic_args_;
  1435. friend class basic_format_args<Context>;
  1436. unsigned long long get_types() const {
  1437. return detail::is_unpacked_bit | data_.size() |
  1438. (named_info_.empty()
  1439. ? 0ULL
  1440. : static_cast<unsigned long long>(detail::has_named_args_bit));
  1441. }
  1442. const basic_format_arg<Context>* data() const {
  1443. return named_info_.empty() ? data_.data() : data_.data() + 1;
  1444. }
  1445. template <typename T> void emplace_arg(const T& arg) {
  1446. data_.emplace_back(detail::make_arg<Context>(arg));
  1447. }
  1448. template <typename T>
  1449. void emplace_arg(const detail::named_arg<char_type, T>& arg) {
  1450. if (named_info_.empty()) {
  1451. constexpr const detail::named_arg_info<char_type>* zero_ptr{nullptr};
  1452. data_.insert(data_.begin(), {zero_ptr, 0});
  1453. }
  1454. data_.emplace_back(detail::make_arg<Context>(detail::unwrap(arg.value)));
  1455. auto pop_one = [](std::vector<basic_format_arg<Context>>* data) {
  1456. data->pop_back();
  1457. };
  1458. std::unique_ptr<std::vector<basic_format_arg<Context>>, decltype(pop_one)>
  1459. guard{&data_, pop_one};
  1460. named_info_.push_back({arg.name, static_cast<int>(data_.size() - 2u)});
  1461. data_[0].value_.named_args = {named_info_.data(), named_info_.size()};
  1462. guard.release();
  1463. }
  1464. public:
  1465. /**
  1466. \rst
  1467. Adds an argument into the dynamic store for later passing to a formatting
  1468. function.
  1469. Note that custom types and string types (but not string views) are copied
  1470. into the store dynamically allocating memory if necessary.
  1471. **Example**::
  1472. fmt::dynamic_format_arg_store<fmt::format_context> store;
  1473. store.push_back(42);
  1474. store.push_back("abc");
  1475. store.push_back(1.5f);
  1476. std::string result = fmt::vformat("{} and {} and {}", store);
  1477. \endrst
  1478. */
  1479. template <typename T> void push_back(const T& arg) {
  1480. if (detail::const_check(need_copy<T>::value))
  1481. emplace_arg(dynamic_args_.push<stored_type<T>>(arg));
  1482. else
  1483. emplace_arg(detail::unwrap(arg));
  1484. }
  1485. /**
  1486. \rst
  1487. Adds a reference to the argument into the dynamic store for later passing to
  1488. a formatting function. Supports named arguments wrapped in
  1489. ``std::reference_wrapper`` via ``std::ref()``/``std::cref()``.
  1490. **Example**::
  1491. fmt::dynamic_format_arg_store<fmt::format_context> store;
  1492. char str[] = "1234567890";
  1493. store.push_back(std::cref(str));
  1494. int a1_val{42};
  1495. auto a1 = fmt::arg("a1_", a1_val);
  1496. store.push_back(std::cref(a1));
  1497. // Changing str affects the output but only for string and custom types.
  1498. str[0] = 'X';
  1499. std::string result = fmt::vformat("{} and {a1_}");
  1500. assert(result == "X234567890 and 42");
  1501. \endrst
  1502. */
  1503. template <typename T> void push_back(std::reference_wrapper<T> arg) {
  1504. static_assert(
  1505. detail::is_named_arg<typename std::remove_cv<T>::type>::value ||
  1506. need_copy<T>::value,
  1507. "objects of built-in types and string views are always copied");
  1508. emplace_arg(arg.get());
  1509. }
  1510. /**
  1511. Adds named argument into the dynamic store for later passing to a formatting
  1512. function. ``std::reference_wrapper`` is supported to avoid copying of the
  1513. argument.
  1514. */
  1515. template <typename T>
  1516. void push_back(const detail::named_arg<char_type, T>& arg) {
  1517. const char_type* arg_name =
  1518. dynamic_args_.push<std::basic_string<char_type>>(arg.name).c_str();
  1519. if (detail::const_check(need_copy<T>::value)) {
  1520. emplace_arg(
  1521. fmt::arg(arg_name, dynamic_args_.push<stored_type<T>>(arg.value)));
  1522. } else {
  1523. emplace_arg(fmt::arg(arg_name, arg.value));
  1524. }
  1525. }
  1526. /** Erase all elements from the store */
  1527. void clear() {
  1528. data_.clear();
  1529. named_info_.clear();
  1530. dynamic_args_ = detail::dynamic_arg_list();
  1531. }
  1532. /**
  1533. \rst
  1534. Reserves space to store at least *new_cap* arguments including
  1535. *new_cap_named* named arguments.
  1536. \endrst
  1537. */
  1538. void reserve(size_t new_cap, size_t new_cap_named) {
  1539. FMT_ASSERT(new_cap >= new_cap_named,
  1540. "Set of arguments includes set of named arguments");
  1541. data_.reserve(new_cap);
  1542. named_info_.reserve(new_cap_named);
  1543. }
  1544. };
  1545. /**
  1546. \rst
  1547. A view of a collection of formatting arguments. To avoid lifetime issues it
  1548. should only be used as a parameter type in type-erased functions such as
  1549. ``vformat``::
  1550. void vlog(string_view format_str, format_args args); // OK
  1551. format_args args = make_format_args(42); // Error: dangling reference
  1552. \endrst
  1553. */
  1554. template <typename Context> class basic_format_args {
  1555. public:
  1556. using size_type = int;
  1557. using format_arg = basic_format_arg<Context>;
  1558. private:
  1559. // A descriptor that contains information about formatting arguments.
  1560. // If the number of arguments is less or equal to max_packed_args then
  1561. // argument types are passed in the descriptor. This reduces binary code size
  1562. // per formatting function call.
  1563. unsigned long long desc_;
  1564. union {
  1565. // If is_packed() returns true then argument values are stored in values_;
  1566. // otherwise they are stored in args_. This is done to improve cache
  1567. // locality and reduce compiled code size since storing larger objects
  1568. // may require more code (at least on x86-64) even if the same amount of
  1569. // data is actually copied to stack. It saves ~10% on the bloat test.
  1570. const detail::value<Context>* values_;
  1571. const format_arg* args_;
  1572. };
  1573. bool is_packed() const { return (desc_ & detail::is_unpacked_bit) == 0; }
  1574. bool has_named_args() const {
  1575. return (desc_ & detail::has_named_args_bit) != 0;
  1576. }
  1577. detail::type type(int index) const {
  1578. int shift = index * detail::packed_arg_bits;
  1579. unsigned int mask = (1 << detail::packed_arg_bits) - 1;
  1580. return static_cast<detail::type>((desc_ >> shift) & mask);
  1581. }
  1582. basic_format_args(unsigned long long desc,
  1583. const detail::value<Context>* values)
  1584. : desc_(desc), values_(values) {}
  1585. basic_format_args(unsigned long long desc, const format_arg* args)
  1586. : desc_(desc), args_(args) {}
  1587. public:
  1588. basic_format_args() : desc_(0) {}
  1589. /**
  1590. \rst
  1591. Constructs a `basic_format_args` object from `~fmt::format_arg_store`.
  1592. \endrst
  1593. */
  1594. template <typename... Args>
  1595. FMT_INLINE basic_format_args(const format_arg_store<Context, Args...>& store)
  1596. : basic_format_args(store.desc, store.data_.args()) {}
  1597. /**
  1598. \rst
  1599. Constructs a `basic_format_args` object from
  1600. `~fmt::dynamic_format_arg_store`.
  1601. \endrst
  1602. */
  1603. FMT_INLINE basic_format_args(const dynamic_format_arg_store<Context>& store)
  1604. : basic_format_args(store.get_types(), store.data()) {}
  1605. /**
  1606. \rst
  1607. Constructs a `basic_format_args` object from a dynamic set of arguments.
  1608. \endrst
  1609. */
  1610. basic_format_args(const format_arg* args, int count)
  1611. : basic_format_args(detail::is_unpacked_bit | detail::to_unsigned(count),
  1612. args) {}
  1613. /** Returns the argument with the specified id. */
  1614. format_arg get(int id) const {
  1615. format_arg arg;
  1616. if (!is_packed()) {
  1617. if (id < max_size()) arg = args_[id];
  1618. return arg;
  1619. }
  1620. if (id >= detail::max_packed_args) return arg;
  1621. arg.type_ = type(id);
  1622. if (arg.type_ == detail::type::none_type) return arg;
  1623. arg.value_ = values_[id];
  1624. return arg;
  1625. }
  1626. template <typename Char> format_arg get(basic_string_view<Char> name) const {
  1627. int id = get_id(name);
  1628. return id >= 0 ? get(id) : format_arg();
  1629. }
  1630. template <typename Char> int get_id(basic_string_view<Char> name) const {
  1631. if (!has_named_args()) return -1;
  1632. const auto& named_args =
  1633. (is_packed() ? values_[-1] : args_[-1].value_).named_args;
  1634. for (size_t i = 0; i < named_args.size; ++i) {
  1635. if (named_args.data[i].name == name) return named_args.data[i].id;
  1636. }
  1637. return -1;
  1638. }
  1639. int max_size() const {
  1640. unsigned long long max_packed = detail::max_packed_args;
  1641. return static_cast<int>(is_packed() ? max_packed
  1642. : desc_ & ~detail::is_unpacked_bit);
  1643. }
  1644. };
  1645. #ifdef FMT_ARM_ABI_COMPATIBILITY
  1646. /** An alias to ``basic_format_args<format_context>``. */
  1647. // Separate types would result in shorter symbols but break ABI compatibility
  1648. // between clang and gcc on ARM (#1919).
  1649. using format_args = basic_format_args<format_context>;
  1650. using wformat_args = basic_format_args<wformat_context>;
  1651. #else
  1652. // DEPRECATED! These are kept for ABI compatibility.
  1653. // It is a separate type rather than an alias to make symbols readable.
  1654. struct format_args : basic_format_args<format_context> {
  1655. template <typename... Args>
  1656. FMT_INLINE format_args(const Args&... args) : basic_format_args(args...) {}
  1657. };
  1658. struct wformat_args : basic_format_args<wformat_context> {
  1659. using basic_format_args::basic_format_args;
  1660. };
  1661. #endif
  1662. namespace detail {
  1663. template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
  1664. std::basic_string<Char> vformat(
  1665. basic_string_view<Char> format_str,
  1666. basic_format_args<buffer_context<type_identity_t<Char>>> args);
  1667. FMT_API std::string vformat(string_view format_str, format_args args);
  1668. template <typename Char>
  1669. void vformat_to(
  1670. buffer<Char>& buf, basic_string_view<Char> format_str,
  1671. basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args,
  1672. detail::locale_ref loc = {});
  1673. template <typename Char, typename Args,
  1674. FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
  1675. inline void vprint_mojibake(std::FILE*, basic_string_view<Char>, const Args&) {}
  1676. FMT_API void vprint_mojibake(std::FILE*, string_view, format_args);
  1677. #ifndef _WIN32
  1678. inline void vprint_mojibake(std::FILE*, string_view, format_args) {}
  1679. #endif
  1680. } // namespace detail
  1681. /** Formats a string and writes the output to ``out``. */
  1682. // GCC 8 and earlier cannot handle std::back_insert_iterator<Container> with
  1683. // vformat_to<ArgFormatter>(...) overload, so SFINAE on iterator type instead.
  1684. template <typename OutputIt, typename S, typename Char = char_t<S>,
  1685. bool enable = detail::is_output_iterator<OutputIt, Char>::value>
  1686. auto vformat_to(OutputIt out, const S& format_str,
  1687. basic_format_args<buffer_context<type_identity_t<Char>>> args)
  1688. -> typename std::enable_if<enable, OutputIt>::type {
  1689. decltype(detail::get_buffer<Char>(out)) buf(detail::get_buffer_init(out));
  1690. detail::vformat_to(buf, to_string_view(format_str), args);
  1691. return detail::get_iterator(buf);
  1692. }
  1693. /**
  1694. \rst
  1695. Formats arguments, writes the result to the output iterator ``out`` and returns
  1696. the iterator past the end of the output range.
  1697. **Example**::
  1698. std::vector<char> out;
  1699. fmt::format_to(std::back_inserter(out), "{}", 42);
  1700. \endrst
  1701. */
  1702. // We cannot use FMT_ENABLE_IF because of a bug in gcc 8.3.
  1703. template <typename OutputIt, typename S, typename... Args,
  1704. bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value>
  1705. inline auto format_to(OutputIt out, const S& format_str, Args&&... args) ->
  1706. typename std::enable_if<enable, OutputIt>::type {
  1707. const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
  1708. return vformat_to(out, to_string_view(format_str), vargs);
  1709. }
  1710. template <typename OutputIt> struct format_to_n_result {
  1711. /** Iterator past the end of the output range. */
  1712. OutputIt out;
  1713. /** Total (not truncated) output size. */
  1714. size_t size;
  1715. };
  1716. template <typename OutputIt, typename Char, typename... Args,
  1717. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value)>
  1718. inline format_to_n_result<OutputIt> vformat_to_n(
  1719. OutputIt out, size_t n, basic_string_view<Char> format_str,
  1720. basic_format_args<buffer_context<type_identity_t<Char>>> args) {
  1721. detail::iterator_buffer<OutputIt, Char, detail::fixed_buffer_traits> buf(out,
  1722. n);
  1723. detail::vformat_to(buf, format_str, args);
  1724. return {buf.out(), buf.count()};
  1725. }
  1726. /**
  1727. \rst
  1728. Formats arguments, writes up to ``n`` characters of the result to the output
  1729. iterator ``out`` and returns the total output size and the iterator past the
  1730. end of the output range.
  1731. \endrst
  1732. */
  1733. template <typename OutputIt, typename S, typename... Args,
  1734. bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value>
  1735. inline auto format_to_n(OutputIt out, size_t n, const S& format_str,
  1736. const Args&... args) ->
  1737. typename std::enable_if<enable, format_to_n_result<OutputIt>>::type {
  1738. const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
  1739. return vformat_to_n(out, n, to_string_view(format_str), vargs);
  1740. }
  1741. /**
  1742. Returns the number of characters in the output of
  1743. ``format(format_str, args...)``.
  1744. */
  1745. template <typename... Args>
  1746. inline size_t formatted_size(string_view format_str, Args&&... args) {
  1747. const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
  1748. detail::counting_buffer<> buf;
  1749. detail::vformat_to(buf, format_str, vargs);
  1750. return buf.count();
  1751. }
  1752. template <typename S, typename Char = char_t<S>>
  1753. FMT_INLINE std::basic_string<Char> vformat(
  1754. const S& format_str,
  1755. basic_format_args<buffer_context<type_identity_t<Char>>> args) {
  1756. return detail::vformat(to_string_view(format_str), args);
  1757. }
  1758. /**
  1759. \rst
  1760. Formats arguments and returns the result as a string.
  1761. **Example**::
  1762. #include <fmt/core.h>
  1763. std::string message = fmt::format("The answer is {}", 42);
  1764. \endrst
  1765. */
  1766. // Pass char_t as a default template parameter instead of using
  1767. // std::basic_string<char_t<S>> to reduce the symbol size.
  1768. template <typename S, typename... Args, typename Char = char_t<S>>
  1769. FMT_INLINE std::basic_string<Char> format(const S& format_str, Args&&... args) {
  1770. const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
  1771. return detail::vformat(to_string_view(format_str), vargs);
  1772. }
  1773. FMT_API void vprint(string_view, format_args);
  1774. FMT_API void vprint(std::FILE*, string_view, format_args);
  1775. /**
  1776. \rst
  1777. Formats ``args`` according to specifications in ``format_str`` and writes the
  1778. output to the file ``f``. Strings are assumed to be Unicode-encoded unless the
  1779. ``FMT_UNICODE`` macro is set to 0.
  1780. **Example**::
  1781. fmt::print(stderr, "Don't {}!", "panic");
  1782. \endrst
  1783. */
  1784. template <typename S, typename... Args, typename Char = char_t<S>>
  1785. inline void print(std::FILE* f, const S& format_str, Args&&... args) {
  1786. const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
  1787. return detail::is_unicode<Char>()
  1788. ? vprint(f, to_string_view(format_str), vargs)
  1789. : detail::vprint_mojibake(f, to_string_view(format_str), vargs);
  1790. }
  1791. /**
  1792. \rst
  1793. Formats ``args`` according to specifications in ``format_str`` and writes
  1794. the output to ``stdout``. Strings are assumed to be Unicode-encoded unless
  1795. the ``FMT_UNICODE`` macro is set to 0.
  1796. **Example**::
  1797. fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
  1798. \endrst
  1799. */
  1800. template <typename S, typename... Args, typename Char = char_t<S>>
  1801. inline void print(const S& format_str, Args&&... args) {
  1802. const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
  1803. return detail::is_unicode<Char>()
  1804. ? vprint(to_string_view(format_str), vargs)
  1805. : detail::vprint_mojibake(stdout, to_string_view(format_str),
  1806. vargs);
  1807. }
  1808. FMT_END_NAMESPACE
  1809. #endif // FMT_CORE_H_