args.h 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // Formatting library for C++ - dynamic argument lists
  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_ARGS_H_
  8. #define FMT_ARGS_H_
  9. #ifndef FMT_MODULE
  10. # include <functional> // std::reference_wrapper
  11. # include <memory> // std::unique_ptr
  12. # include <vector>
  13. #endif
  14. #include "format.h" // std_string_view
  15. FMT_BEGIN_NAMESPACE
  16. namespace detail {
  17. template <typename T> struct is_reference_wrapper : std::false_type {};
  18. template <typename T>
  19. struct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type {};
  20. template <typename T> auto unwrap(const T& v) -> const T& { return v; }
  21. template <typename T>
  22. auto unwrap(const std::reference_wrapper<T>& v) -> const T& {
  23. return static_cast<const T&>(v);
  24. }
  25. // node is defined outside dynamic_arg_list to workaround a C2504 bug in MSVC
  26. // 2022 (v17.10.0).
  27. //
  28. // Workaround for clang's -Wweak-vtables. Unlike for regular classes, for
  29. // templates it doesn't complain about inability to deduce single translation
  30. // unit for placing vtable. So node is made a fake template.
  31. template <typename = void> struct node {
  32. virtual ~node() = default;
  33. std::unique_ptr<node<>> next;
  34. };
  35. class dynamic_arg_list {
  36. template <typename T> struct typed_node : node<> {
  37. T value;
  38. template <typename Arg>
  39. FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {}
  40. template <typename Char>
  41. FMT_CONSTEXPR typed_node(const basic_string_view<Char>& arg)
  42. : value(arg.data(), arg.size()) {}
  43. };
  44. std::unique_ptr<node<>> head_;
  45. public:
  46. template <typename T, typename Arg> auto push(const Arg& arg) -> const T& {
  47. auto new_node = std::unique_ptr<typed_node<T>>(new typed_node<T>(arg));
  48. auto& value = new_node->value;
  49. new_node->next = std::move(head_);
  50. head_ = std::move(new_node);
  51. return value;
  52. }
  53. };
  54. } // namespace detail
  55. /**
  56. * A dynamic list of formatting arguments with storage.
  57. *
  58. * It can be implicitly converted into `fmt::basic_format_args` for passing
  59. * into type-erased formatting functions such as `fmt::vformat`.
  60. */
  61. template <typename Context> class dynamic_format_arg_store {
  62. private:
  63. using char_type = typename Context::char_type;
  64. template <typename T> struct need_copy {
  65. static constexpr detail::type mapped_type =
  66. detail::mapped_type_constant<T, char_type>::value;
  67. enum {
  68. value = !(detail::is_reference_wrapper<T>::value ||
  69. std::is_same<T, basic_string_view<char_type>>::value ||
  70. std::is_same<T, detail::std_string_view<char_type>>::value ||
  71. (mapped_type != detail::type::cstring_type &&
  72. mapped_type != detail::type::string_type &&
  73. mapped_type != detail::type::custom_type))
  74. };
  75. };
  76. template <typename T>
  77. using stored_t = conditional_t<
  78. std::is_convertible<T, std::basic_string<char_type>>::value &&
  79. !detail::is_reference_wrapper<T>::value,
  80. std::basic_string<char_type>, T>;
  81. // Storage of basic_format_arg must be contiguous.
  82. std::vector<basic_format_arg<Context>> data_;
  83. std::vector<detail::named_arg_info<char_type>> named_info_;
  84. // Storage of arguments not fitting into basic_format_arg must grow
  85. // without relocation because items in data_ refer to it.
  86. detail::dynamic_arg_list dynamic_args_;
  87. friend class basic_format_args<Context>;
  88. auto data() const -> const basic_format_arg<Context>* {
  89. return named_info_.empty() ? data_.data() : data_.data() + 1;
  90. }
  91. template <typename T> void emplace_arg(const T& arg) {
  92. data_.emplace_back(arg);
  93. }
  94. template <typename T>
  95. void emplace_arg(const detail::named_arg<char_type, T>& arg) {
  96. if (named_info_.empty())
  97. data_.insert(data_.begin(), basic_format_arg<Context>(nullptr, 0));
  98. data_.emplace_back(detail::unwrap(arg.value));
  99. auto pop_one = [](std::vector<basic_format_arg<Context>>* data) {
  100. data->pop_back();
  101. };
  102. std::unique_ptr<std::vector<basic_format_arg<Context>>, decltype(pop_one)>
  103. guard{&data_, pop_one};
  104. named_info_.push_back({arg.name, static_cast<int>(data_.size() - 2u)});
  105. data_[0] = {named_info_.data(), named_info_.size()};
  106. guard.release();
  107. }
  108. public:
  109. constexpr dynamic_format_arg_store() = default;
  110. operator basic_format_args<Context>() const {
  111. return basic_format_args<Context>(data(), static_cast<int>(data_.size()),
  112. !named_info_.empty());
  113. }
  114. /**
  115. * Adds an argument into the dynamic store for later passing to a formatting
  116. * function.
  117. *
  118. * Note that custom types and string types (but not string views) are copied
  119. * into the store dynamically allocating memory if necessary.
  120. *
  121. * **Example**:
  122. *
  123. * fmt::dynamic_format_arg_store<fmt::format_context> store;
  124. * store.push_back(42);
  125. * store.push_back("abc");
  126. * store.push_back(1.5f);
  127. * std::string result = fmt::vformat("{} and {} and {}", store);
  128. */
  129. template <typename T> void push_back(const T& arg) {
  130. if (detail::const_check(need_copy<T>::value))
  131. emplace_arg(dynamic_args_.push<stored_t<T>>(arg));
  132. else
  133. emplace_arg(detail::unwrap(arg));
  134. }
  135. /**
  136. * Adds a reference to the argument into the dynamic store for later passing
  137. * to a formatting function.
  138. *
  139. * **Example**:
  140. *
  141. * fmt::dynamic_format_arg_store<fmt::format_context> store;
  142. * char band[] = "Rolling Stones";
  143. * store.push_back(std::cref(band));
  144. * band[9] = 'c'; // Changing str affects the output.
  145. * std::string result = fmt::vformat("{}", store);
  146. * // result == "Rolling Scones"
  147. */
  148. template <typename T> void push_back(std::reference_wrapper<T> arg) {
  149. static_assert(
  150. need_copy<T>::value,
  151. "objects of built-in types and string views are always copied");
  152. emplace_arg(arg.get());
  153. }
  154. /**
  155. * Adds named argument into the dynamic store for later passing to a
  156. * formatting function. `std::reference_wrapper` is supported to avoid
  157. * copying of the argument. The name is always copied into the store.
  158. */
  159. template <typename T>
  160. void push_back(const detail::named_arg<char_type, T>& arg) {
  161. const char_type* arg_name =
  162. dynamic_args_.push<std::basic_string<char_type>>(arg.name).c_str();
  163. if (detail::const_check(need_copy<T>::value)) {
  164. emplace_arg(
  165. fmt::arg(arg_name, dynamic_args_.push<stored_t<T>>(arg.value)));
  166. } else {
  167. emplace_arg(fmt::arg(arg_name, arg.value));
  168. }
  169. }
  170. /// Erase all elements from the store.
  171. void clear() {
  172. data_.clear();
  173. named_info_.clear();
  174. dynamic_args_ = {};
  175. }
  176. /// Reserves space to store at least `new_cap` arguments including
  177. /// `new_cap_named` named arguments.
  178. void reserve(size_t new_cap, size_t new_cap_named) {
  179. FMT_ASSERT(new_cap >= new_cap_named,
  180. "set of arguments includes set of named arguments");
  181. data_.reserve(new_cap);
  182. named_info_.reserve(new_cap_named);
  183. }
  184. /// Returns the number of elements in the store.
  185. size_t size() const noexcept { return data_.size(); }
  186. };
  187. FMT_END_NAMESPACE
  188. #endif // FMT_ARGS_H_