args.h 7.3 KB

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