str_split_internal.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // This file declares INTERNAL parts of the Split API that are inline/templated
  16. // or otherwise need to be available at compile time. The main abstractions
  17. // defined in here are
  18. //
  19. // - ConvertibleToStringView
  20. // - SplitIterator<>
  21. // - Splitter<>
  22. //
  23. // DO NOT INCLUDE THIS FILE DIRECTLY. Use this file by including
  24. // absl/strings/str_split.h.
  25. //
  26. // IWYU pragma: private, include "absl/strings/str_split.h"
  27. #ifndef ABSL_STRINGS_INTERNAL_STR_SPLIT_INTERNAL_H_
  28. #define ABSL_STRINGS_INTERNAL_STR_SPLIT_INTERNAL_H_
  29. #include <array>
  30. #include <initializer_list>
  31. #include <iterator>
  32. #include <tuple>
  33. #include <type_traits>
  34. #include <utility>
  35. #include <vector>
  36. #include "absl/base/macros.h"
  37. #include "absl/base/port.h"
  38. #include "absl/meta/type_traits.h"
  39. #include "absl/strings/string_view.h"
  40. #ifdef _GLIBCXX_DEBUG
  41. #include "absl/strings/internal/stl_type_traits.h"
  42. #endif // _GLIBCXX_DEBUG
  43. namespace absl {
  44. ABSL_NAMESPACE_BEGIN
  45. namespace strings_internal {
  46. // This class is implicitly constructible from everything that absl::string_view
  47. // is implicitly constructible from, except for rvalue strings. This means it
  48. // can be used as a function parameter in places where passing a temporary
  49. // string might cause memory lifetime issues.
  50. class ConvertibleToStringView {
  51. public:
  52. ConvertibleToStringView(const char* s) // NOLINT(runtime/explicit)
  53. : value_(s) {}
  54. ConvertibleToStringView(char* s) : value_(s) {} // NOLINT(runtime/explicit)
  55. ConvertibleToStringView(absl::string_view s) // NOLINT(runtime/explicit)
  56. : value_(s) {}
  57. ConvertibleToStringView(const std::string& s) // NOLINT(runtime/explicit)
  58. : value_(s) {}
  59. // Disable conversion from rvalue strings.
  60. ConvertibleToStringView(std::string&& s) = delete;
  61. ConvertibleToStringView(const std::string&& s) = delete;
  62. absl::string_view value() const { return value_; }
  63. private:
  64. absl::string_view value_;
  65. };
  66. // An iterator that enumerates the parts of a string from a Splitter. The text
  67. // to be split, the Delimiter, and the Predicate are all taken from the given
  68. // Splitter object. Iterators may only be compared if they refer to the same
  69. // Splitter instance.
  70. //
  71. // This class is NOT part of the public splitting API.
  72. template <typename Splitter>
  73. class SplitIterator {
  74. public:
  75. using iterator_category = std::input_iterator_tag;
  76. using value_type = absl::string_view;
  77. using difference_type = ptrdiff_t;
  78. using pointer = const value_type*;
  79. using reference = const value_type&;
  80. enum State { kInitState, kLastState, kEndState };
  81. SplitIterator(State state, const Splitter* splitter)
  82. : pos_(0),
  83. state_(state),
  84. splitter_(splitter),
  85. delimiter_(splitter->delimiter()),
  86. predicate_(splitter->predicate()) {
  87. // Hack to maintain backward compatibility. This one block makes it so an
  88. // empty absl::string_view whose .data() happens to be nullptr behaves
  89. // *differently* from an otherwise empty absl::string_view whose .data() is
  90. // not nullptr. This is an undesirable difference in general, but this
  91. // behavior is maintained to avoid breaking existing code that happens to
  92. // depend on this old behavior/bug. Perhaps it will be fixed one day. The
  93. // difference in behavior is as follows:
  94. // Split(absl::string_view(""), '-'); // {""}
  95. // Split(absl::string_view(), '-'); // {}
  96. if (splitter_->text().data() == nullptr) {
  97. state_ = kEndState;
  98. pos_ = splitter_->text().size();
  99. return;
  100. }
  101. if (state_ == kEndState) {
  102. pos_ = splitter_->text().size();
  103. } else {
  104. ++(*this);
  105. }
  106. }
  107. bool at_end() const { return state_ == kEndState; }
  108. reference operator*() const { return curr_; }
  109. pointer operator->() const { return &curr_; }
  110. SplitIterator& operator++() {
  111. do {
  112. if (state_ == kLastState) {
  113. state_ = kEndState;
  114. return *this;
  115. }
  116. const absl::string_view text = splitter_->text();
  117. const absl::string_view d = delimiter_.Find(text, pos_);
  118. if (d.data() == text.data() + text.size()) state_ = kLastState;
  119. curr_ = text.substr(pos_, d.data() - (text.data() + pos_));
  120. pos_ += curr_.size() + d.size();
  121. } while (!predicate_(curr_));
  122. return *this;
  123. }
  124. SplitIterator operator++(int) {
  125. SplitIterator old(*this);
  126. ++(*this);
  127. return old;
  128. }
  129. friend bool operator==(const SplitIterator& a, const SplitIterator& b) {
  130. return a.state_ == b.state_ && a.pos_ == b.pos_;
  131. }
  132. friend bool operator!=(const SplitIterator& a, const SplitIterator& b) {
  133. return !(a == b);
  134. }
  135. private:
  136. size_t pos_;
  137. State state_;
  138. absl::string_view curr_;
  139. const Splitter* splitter_;
  140. typename Splitter::DelimiterType delimiter_;
  141. typename Splitter::PredicateType predicate_;
  142. };
  143. // HasMappedType<T>::value is true iff there exists a type T::mapped_type.
  144. template <typename T, typename = void>
  145. struct HasMappedType : std::false_type {};
  146. template <typename T>
  147. struct HasMappedType<T, absl::void_t<typename T::mapped_type>>
  148. : std::true_type {};
  149. // HasValueType<T>::value is true iff there exists a type T::value_type.
  150. template <typename T, typename = void>
  151. struct HasValueType : std::false_type {};
  152. template <typename T>
  153. struct HasValueType<T, absl::void_t<typename T::value_type>> : std::true_type {
  154. };
  155. // HasConstIterator<T>::value is true iff there exists a type T::const_iterator.
  156. template <typename T, typename = void>
  157. struct HasConstIterator : std::false_type {};
  158. template <typename T>
  159. struct HasConstIterator<T, absl::void_t<typename T::const_iterator>>
  160. : std::true_type {};
  161. // HasEmplace<T>::value is true iff there exists a method T::emplace().
  162. template <typename T, typename = void>
  163. struct HasEmplace : std::false_type {};
  164. template <typename T>
  165. struct HasEmplace<T, absl::void_t<decltype(std::declval<T>().emplace())>>
  166. : std::true_type {};
  167. // IsInitializerList<T>::value is true iff T is an std::initializer_list. More
  168. // details below in Splitter<> where this is used.
  169. std::false_type IsInitializerListDispatch(...); // default: No
  170. template <typename T>
  171. std::true_type IsInitializerListDispatch(std::initializer_list<T>*);
  172. template <typename T>
  173. struct IsInitializerList
  174. : decltype(IsInitializerListDispatch(static_cast<T*>(nullptr))) {};
  175. // A SplitterIsConvertibleTo<C>::type alias exists iff the specified condition
  176. // is true for type 'C'.
  177. //
  178. // Restricts conversion to container-like types (by testing for the presence of
  179. // a const_iterator member type) and also to disable conversion to an
  180. // std::initializer_list (which also has a const_iterator). Otherwise, code
  181. // compiled in C++11 will get an error due to ambiguous conversion paths (in
  182. // C++11 std::vector<T>::operator= is overloaded to take either a std::vector<T>
  183. // or an std::initializer_list<T>).
  184. template <typename C, bool has_value_type, bool has_mapped_type>
  185. struct SplitterIsConvertibleToImpl : std::false_type {};
  186. template <typename C>
  187. struct SplitterIsConvertibleToImpl<C, true, false>
  188. : std::is_constructible<typename C::value_type, absl::string_view> {};
  189. template <typename C>
  190. struct SplitterIsConvertibleToImpl<C, true, true>
  191. : absl::conjunction<
  192. std::is_constructible<typename C::key_type, absl::string_view>,
  193. std::is_constructible<typename C::mapped_type, absl::string_view>> {};
  194. template <typename C>
  195. struct SplitterIsConvertibleTo
  196. : SplitterIsConvertibleToImpl<
  197. C,
  198. #ifdef _GLIBCXX_DEBUG
  199. !IsStrictlyBaseOfAndConvertibleToSTLContainer<C>::value &&
  200. #endif // _GLIBCXX_DEBUG
  201. !IsInitializerList<
  202. typename std::remove_reference<C>::type>::value &&
  203. HasValueType<C>::value && HasConstIterator<C>::value,
  204. HasMappedType<C>::value> {
  205. };
  206. // This class implements the range that is returned by absl::StrSplit(). This
  207. // class has templated conversion operators that allow it to be implicitly
  208. // converted to a variety of types that the caller may have specified on the
  209. // left-hand side of an assignment.
  210. //
  211. // The main interface for interacting with this class is through its implicit
  212. // conversion operators. However, this class may also be used like a container
  213. // in that it has .begin() and .end() member functions. It may also be used
  214. // within a range-for loop.
  215. //
  216. // Output containers can be collections of any type that is constructible from
  217. // an absl::string_view.
  218. //
  219. // An Predicate functor may be supplied. This predicate will be used to filter
  220. // the split strings: only strings for which the predicate returns true will be
  221. // kept. A Predicate object is any unary functor that takes an absl::string_view
  222. // and returns bool.
  223. //
  224. // The StringType parameter can be either string_view or string, depending on
  225. // whether the Splitter refers to a string stored elsewhere, or if the string
  226. // resides inside the Splitter itself.
  227. template <typename Delimiter, typename Predicate, typename StringType>
  228. class Splitter {
  229. public:
  230. using DelimiterType = Delimiter;
  231. using PredicateType = Predicate;
  232. using const_iterator = strings_internal::SplitIterator<Splitter>;
  233. using value_type = typename std::iterator_traits<const_iterator>::value_type;
  234. Splitter(StringType input_text, Delimiter d, Predicate p)
  235. : text_(std::move(input_text)),
  236. delimiter_(std::move(d)),
  237. predicate_(std::move(p)) {}
  238. absl::string_view text() const { return text_; }
  239. const Delimiter& delimiter() const { return delimiter_; }
  240. const Predicate& predicate() const { return predicate_; }
  241. // Range functions that iterate the split substrings as absl::string_view
  242. // objects. These methods enable a Splitter to be used in a range-based for
  243. // loop.
  244. const_iterator begin() const { return {const_iterator::kInitState, this}; }
  245. const_iterator end() const { return {const_iterator::kEndState, this}; }
  246. // An implicit conversion operator that is restricted to only those containers
  247. // that the splitter is convertible to.
  248. template <typename Container,
  249. typename = typename std::enable_if<
  250. SplitterIsConvertibleTo<Container>::value>::type>
  251. operator Container() const { // NOLINT(runtime/explicit)
  252. return ConvertToContainer<Container, typename Container::value_type,
  253. HasMappedType<Container>::value>()(*this);
  254. }
  255. // Returns a pair with its .first and .second members set to the first two
  256. // strings returned by the begin() iterator. Either/both of .first and .second
  257. // will be constructed with empty strings if the iterator doesn't have a
  258. // corresponding value.
  259. template <typename First, typename Second>
  260. operator std::pair<First, Second>() const { // NOLINT(runtime/explicit)
  261. absl::string_view first, second;
  262. auto it = begin();
  263. if (it != end()) {
  264. first = *it;
  265. if (++it != end()) {
  266. second = *it;
  267. }
  268. }
  269. return {First(first), Second(second)};
  270. }
  271. private:
  272. // ConvertToContainer is a functor converting a Splitter to the requested
  273. // Container of ValueType. It is specialized below to optimize splitting to
  274. // certain combinations of Container and ValueType.
  275. //
  276. // This base template handles the generic case of storing the split results in
  277. // the requested non-map-like container and converting the split substrings to
  278. // the requested type.
  279. template <typename Container, typename ValueType, bool is_map = false>
  280. struct ConvertToContainer {
  281. Container operator()(const Splitter& splitter) const {
  282. Container c;
  283. auto it = std::inserter(c, c.end());
  284. for (const auto& sp : splitter) {
  285. *it++ = ValueType(sp);
  286. }
  287. return c;
  288. }
  289. };
  290. // Partial specialization for a std::vector<absl::string_view>.
  291. //
  292. // Optimized for the common case of splitting to a
  293. // std::vector<absl::string_view>. In this case we first split the results to
  294. // a small array of absl::string_view on the stack, to reduce reallocations.
  295. template <typename A>
  296. struct ConvertToContainer<std::vector<absl::string_view, A>,
  297. absl::string_view, false> {
  298. std::vector<absl::string_view, A> operator()(
  299. const Splitter& splitter) const {
  300. struct raw_view {
  301. const char* data;
  302. size_t size;
  303. operator absl::string_view() const { // NOLINT(runtime/explicit)
  304. return {data, size};
  305. }
  306. };
  307. std::vector<absl::string_view, A> v;
  308. std::array<raw_view, 16> ar;
  309. for (auto it = splitter.begin(); !it.at_end();) {
  310. size_t index = 0;
  311. do {
  312. ar[index].data = it->data();
  313. ar[index].size = it->size();
  314. ++it;
  315. } while (++index != ar.size() && !it.at_end());
  316. v.insert(v.end(), ar.begin(), ar.begin() + index);
  317. }
  318. return v;
  319. }
  320. };
  321. // Partial specialization for a std::vector<std::string>.
  322. //
  323. // Optimized for the common case of splitting to a std::vector<std::string>.
  324. // In this case we first split the results to a std::vector<absl::string_view>
  325. // so the returned std::vector<std::string> can have space reserved to avoid
  326. // std::string moves.
  327. template <typename A>
  328. struct ConvertToContainer<std::vector<std::string, A>, std::string, false> {
  329. std::vector<std::string, A> operator()(const Splitter& splitter) const {
  330. const std::vector<absl::string_view> v = splitter;
  331. return std::vector<std::string, A>(v.begin(), v.end());
  332. }
  333. };
  334. // Partial specialization for containers of pairs (e.g., maps).
  335. //
  336. // The algorithm is to insert a new pair into the map for each even-numbered
  337. // item, with the even-numbered item as the key with a default-constructed
  338. // value. Each odd-numbered item will then be assigned to the last pair's
  339. // value.
  340. template <typename Container, typename First, typename Second>
  341. struct ConvertToContainer<Container, std::pair<const First, Second>, true> {
  342. using iterator = typename Container::iterator;
  343. Container operator()(const Splitter& splitter) const {
  344. Container m;
  345. iterator it;
  346. bool insert = true;
  347. for (const absl::string_view sv : splitter) {
  348. if (insert) {
  349. it = InsertOrEmplace(&m, sv);
  350. } else {
  351. it->second = Second(sv);
  352. }
  353. insert = !insert;
  354. }
  355. return m;
  356. }
  357. // Inserts the key and an empty value into the map, returning an iterator to
  358. // the inserted item. We use emplace() if available, otherwise insert().
  359. template <typename M>
  360. static absl::enable_if_t<HasEmplace<M>::value, iterator> InsertOrEmplace(
  361. M* m, absl::string_view key) {
  362. // Use piecewise_construct to support old versions of gcc in which pair
  363. // constructor can't otherwise construct string from string_view.
  364. return ToIter(m->emplace(std::piecewise_construct, std::make_tuple(key),
  365. std::tuple<>()));
  366. }
  367. template <typename M>
  368. static absl::enable_if_t<!HasEmplace<M>::value, iterator> InsertOrEmplace(
  369. M* m, absl::string_view key) {
  370. return ToIter(m->insert(std::make_pair(First(key), Second(""))));
  371. }
  372. static iterator ToIter(std::pair<iterator, bool> pair) {
  373. return pair.first;
  374. }
  375. static iterator ToIter(iterator iter) { return iter; }
  376. };
  377. StringType text_;
  378. Delimiter delimiter_;
  379. Predicate predicate_;
  380. };
  381. } // namespace strings_internal
  382. ABSL_NAMESPACE_END
  383. } // namespace absl
  384. #endif // ABSL_STRINGS_INTERNAL_STR_SPLIT_INTERNAL_H_