str_split_internal.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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_,
  120. static_cast<size_t>(d.data() - (text.data() + pos_)));
  121. pos_ += curr_.size() + d.size();
  122. } while (!predicate_(curr_));
  123. return *this;
  124. }
  125. SplitIterator operator++(int) {
  126. SplitIterator old(*this);
  127. ++(*this);
  128. return old;
  129. }
  130. friend bool operator==(const SplitIterator& a, const SplitIterator& b) {
  131. return a.state_ == b.state_ && a.pos_ == b.pos_;
  132. }
  133. friend bool operator!=(const SplitIterator& a, const SplitIterator& b) {
  134. return !(a == b);
  135. }
  136. private:
  137. size_t pos_;
  138. State state_;
  139. absl::string_view curr_;
  140. const Splitter* splitter_;
  141. typename Splitter::DelimiterType delimiter_;
  142. typename Splitter::PredicateType predicate_;
  143. };
  144. // HasMappedType<T>::value is true iff there exists a type T::mapped_type.
  145. template <typename T, typename = void>
  146. struct HasMappedType : std::false_type {};
  147. template <typename T>
  148. struct HasMappedType<T, absl::void_t<typename T::mapped_type>>
  149. : std::true_type {};
  150. // HasValueType<T>::value is true iff there exists a type T::value_type.
  151. template <typename T, typename = void>
  152. struct HasValueType : std::false_type {};
  153. template <typename T>
  154. struct HasValueType<T, absl::void_t<typename T::value_type>> : std::true_type {
  155. };
  156. // HasConstIterator<T>::value is true iff there exists a type T::const_iterator.
  157. template <typename T, typename = void>
  158. struct HasConstIterator : std::false_type {};
  159. template <typename T>
  160. struct HasConstIterator<T, absl::void_t<typename T::const_iterator>>
  161. : std::true_type {};
  162. // HasEmplace<T>::value is true iff there exists a method T::emplace().
  163. template <typename T, typename = void>
  164. struct HasEmplace : std::false_type {};
  165. template <typename T>
  166. struct HasEmplace<T, absl::void_t<decltype(std::declval<T>().emplace())>>
  167. : std::true_type {};
  168. // IsInitializerList<T>::value is true iff T is an std::initializer_list. More
  169. // details below in Splitter<> where this is used.
  170. std::false_type IsInitializerListDispatch(...); // default: No
  171. template <typename T>
  172. std::true_type IsInitializerListDispatch(std::initializer_list<T>*);
  173. template <typename T>
  174. struct IsInitializerList
  175. : decltype(IsInitializerListDispatch(static_cast<T*>(nullptr))) {};
  176. // A SplitterIsConvertibleTo<C>::type alias exists iff the specified condition
  177. // is true for type 'C'.
  178. //
  179. // Restricts conversion to container-like types (by testing for the presence of
  180. // a const_iterator member type) and also to disable conversion to an
  181. // std::initializer_list (which also has a const_iterator). Otherwise, code
  182. // compiled in C++11 will get an error due to ambiguous conversion paths (in
  183. // C++11 std::vector<T>::operator= is overloaded to take either a std::vector<T>
  184. // or an std::initializer_list<T>).
  185. template <typename C, bool has_value_type, bool has_mapped_type>
  186. struct SplitterIsConvertibleToImpl : std::false_type {};
  187. template <typename C>
  188. struct SplitterIsConvertibleToImpl<C, true, false>
  189. : std::is_constructible<typename C::value_type, absl::string_view> {};
  190. template <typename C>
  191. struct SplitterIsConvertibleToImpl<C, true, true>
  192. : absl::conjunction<
  193. std::is_constructible<typename C::key_type, absl::string_view>,
  194. std::is_constructible<typename C::mapped_type, absl::string_view>> {};
  195. template <typename C>
  196. struct SplitterIsConvertibleTo
  197. : SplitterIsConvertibleToImpl<
  198. C,
  199. #ifdef _GLIBCXX_DEBUG
  200. !IsStrictlyBaseOfAndConvertibleToSTLContainer<C>::value &&
  201. #endif // _GLIBCXX_DEBUG
  202. !IsInitializerList<
  203. typename std::remove_reference<C>::type>::value &&
  204. HasValueType<C>::value && HasConstIterator<C>::value,
  205. HasMappedType<C>::value> {
  206. };
  207. template <typename StringType, typename Container, typename = void>
  208. struct ShouldUseLifetimeBound : std::false_type {};
  209. template <typename StringType, typename Container>
  210. struct ShouldUseLifetimeBound<
  211. StringType, Container,
  212. std::enable_if_t<
  213. std::is_same<StringType, std::string>::value &&
  214. std::is_same<typename Container::value_type, absl::string_view>::value>>
  215. : std::true_type {};
  216. template <typename StringType, typename First, typename Second>
  217. using ShouldUseLifetimeBoundForPair = std::integral_constant<
  218. bool, std::is_same<StringType, std::string>::value &&
  219. (std::is_same<First, absl::string_view>::value ||
  220. std::is_same<Second, absl::string_view>::value)>;
  221. // This class implements the range that is returned by absl::StrSplit(). This
  222. // class has templated conversion operators that allow it to be implicitly
  223. // converted to a variety of types that the caller may have specified on the
  224. // left-hand side of an assignment.
  225. //
  226. // The main interface for interacting with this class is through its implicit
  227. // conversion operators. However, this class may also be used like a container
  228. // in that it has .begin() and .end() member functions. It may also be used
  229. // within a range-for loop.
  230. //
  231. // Output containers can be collections of any type that is constructible from
  232. // an absl::string_view.
  233. //
  234. // An Predicate functor may be supplied. This predicate will be used to filter
  235. // the split strings: only strings for which the predicate returns true will be
  236. // kept. A Predicate object is any unary functor that takes an absl::string_view
  237. // and returns bool.
  238. //
  239. // The StringType parameter can be either string_view or string, depending on
  240. // whether the Splitter refers to a string stored elsewhere, or if the string
  241. // resides inside the Splitter itself.
  242. template <typename Delimiter, typename Predicate, typename StringType>
  243. class Splitter {
  244. public:
  245. using DelimiterType = Delimiter;
  246. using PredicateType = Predicate;
  247. using const_iterator = strings_internal::SplitIterator<Splitter>;
  248. using value_type = typename std::iterator_traits<const_iterator>::value_type;
  249. Splitter(StringType input_text, Delimiter d, Predicate p)
  250. : text_(std::move(input_text)),
  251. delimiter_(std::move(d)),
  252. predicate_(std::move(p)) {}
  253. absl::string_view text() const { return text_; }
  254. const Delimiter& delimiter() const { return delimiter_; }
  255. const Predicate& predicate() const { return predicate_; }
  256. // Range functions that iterate the split substrings as absl::string_view
  257. // objects. These methods enable a Splitter to be used in a range-based for
  258. // loop.
  259. const_iterator begin() const { return {const_iterator::kInitState, this}; }
  260. const_iterator end() const { return {const_iterator::kEndState, this}; }
  261. // An implicit conversion operator that is restricted to only those containers
  262. // that the splitter is convertible to.
  263. template <
  264. typename Container,
  265. std::enable_if_t<ShouldUseLifetimeBound<StringType, Container>::value &&
  266. SplitterIsConvertibleTo<Container>::value,
  267. std::nullptr_t> = nullptr>
  268. // NOLINTNEXTLINE(google-explicit-constructor)
  269. operator Container() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
  270. return ConvertToContainer<Container, typename Container::value_type,
  271. HasMappedType<Container>::value>()(*this);
  272. }
  273. template <
  274. typename Container,
  275. std::enable_if_t<!ShouldUseLifetimeBound<StringType, Container>::value &&
  276. SplitterIsConvertibleTo<Container>::value,
  277. std::nullptr_t> = nullptr>
  278. // NOLINTNEXTLINE(google-explicit-constructor)
  279. operator Container() const {
  280. return ConvertToContainer<Container, typename Container::value_type,
  281. HasMappedType<Container>::value>()(*this);
  282. }
  283. // Returns a pair with its .first and .second members set to the first two
  284. // strings returned by the begin() iterator. Either/both of .first and .second
  285. // will be constructed with empty strings if the iterator doesn't have a
  286. // corresponding value.
  287. template <typename First, typename Second,
  288. std::enable_if_t<
  289. ShouldUseLifetimeBoundForPair<StringType, First, Second>::value,
  290. std::nullptr_t> = nullptr>
  291. // NOLINTNEXTLINE(google-explicit-constructor)
  292. operator std::pair<First, Second>() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
  293. return ConvertToPair<First, Second>();
  294. }
  295. template <typename First, typename Second,
  296. std::enable_if_t<!ShouldUseLifetimeBoundForPair<StringType, First,
  297. Second>::value,
  298. std::nullptr_t> = nullptr>
  299. // NOLINTNEXTLINE(google-explicit-constructor)
  300. operator std::pair<First, Second>() const {
  301. return ConvertToPair<First, Second>();
  302. }
  303. private:
  304. template <typename First, typename Second>
  305. std::pair<First, Second> ConvertToPair() const {
  306. absl::string_view first, second;
  307. auto it = begin();
  308. if (it != end()) {
  309. first = *it;
  310. if (++it != end()) {
  311. second = *it;
  312. }
  313. }
  314. return {First(first), Second(second)};
  315. }
  316. // ConvertToContainer is a functor converting a Splitter to the requested
  317. // Container of ValueType. It is specialized below to optimize splitting to
  318. // certain combinations of Container and ValueType.
  319. //
  320. // This base template handles the generic case of storing the split results in
  321. // the requested non-map-like container and converting the split substrings to
  322. // the requested type.
  323. template <typename Container, typename ValueType, bool is_map = false>
  324. struct ConvertToContainer {
  325. Container operator()(const Splitter& splitter) const {
  326. Container c;
  327. auto it = std::inserter(c, c.end());
  328. for (const auto& sp : splitter) {
  329. *it++ = ValueType(sp);
  330. }
  331. return c;
  332. }
  333. };
  334. // Partial specialization for a std::vector<absl::string_view>.
  335. //
  336. // Optimized for the common case of splitting to a
  337. // std::vector<absl::string_view>. In this case we first split the results to
  338. // a small array of absl::string_view on the stack, to reduce reallocations.
  339. template <typename A>
  340. struct ConvertToContainer<std::vector<absl::string_view, A>,
  341. absl::string_view, false> {
  342. std::vector<absl::string_view, A> operator()(
  343. const Splitter& splitter) const {
  344. struct raw_view {
  345. const char* data;
  346. size_t size;
  347. operator absl::string_view() const { // NOLINT(runtime/explicit)
  348. return {data, size};
  349. }
  350. };
  351. std::vector<absl::string_view, A> v;
  352. std::array<raw_view, 16> ar;
  353. for (auto it = splitter.begin(); !it.at_end();) {
  354. size_t index = 0;
  355. do {
  356. ar[index].data = it->data();
  357. ar[index].size = it->size();
  358. ++it;
  359. } while (++index != ar.size() && !it.at_end());
  360. v.insert(v.end(), ar.begin(), ar.begin() + index);
  361. }
  362. return v;
  363. }
  364. };
  365. // Partial specialization for a std::vector<std::string>.
  366. //
  367. // Optimized for the common case of splitting to a std::vector<std::string>.
  368. // In this case we first split the results to a std::vector<absl::string_view>
  369. // so the returned std::vector<std::string> can have space reserved to avoid
  370. // std::string moves.
  371. template <typename A>
  372. struct ConvertToContainer<std::vector<std::string, A>, std::string, false> {
  373. std::vector<std::string, A> operator()(const Splitter& splitter) const {
  374. const std::vector<absl::string_view> v = splitter;
  375. return std::vector<std::string, A>(v.begin(), v.end());
  376. }
  377. };
  378. // Partial specialization for containers of pairs (e.g., maps).
  379. //
  380. // The algorithm is to insert a new pair into the map for each even-numbered
  381. // item, with the even-numbered item as the key with a default-constructed
  382. // value. Each odd-numbered item will then be assigned to the last pair's
  383. // value.
  384. template <typename Container, typename First, typename Second>
  385. struct ConvertToContainer<Container, std::pair<const First, Second>, true> {
  386. using iterator = typename Container::iterator;
  387. Container operator()(const Splitter& splitter) const {
  388. Container m;
  389. iterator it;
  390. bool insert = true;
  391. for (const absl::string_view sv : splitter) {
  392. if (insert) {
  393. it = InsertOrEmplace(&m, sv);
  394. } else {
  395. it->second = Second(sv);
  396. }
  397. insert = !insert;
  398. }
  399. return m;
  400. }
  401. // Inserts the key and an empty value into the map, returning an iterator to
  402. // the inserted item. We use emplace() if available, otherwise insert().
  403. template <typename M>
  404. static absl::enable_if_t<HasEmplace<M>::value, iterator> InsertOrEmplace(
  405. M* m, absl::string_view key) {
  406. // Use piecewise_construct to support old versions of gcc in which pair
  407. // constructor can't otherwise construct string from string_view.
  408. return ToIter(m->emplace(std::piecewise_construct, std::make_tuple(key),
  409. std::tuple<>()));
  410. }
  411. template <typename M>
  412. static absl::enable_if_t<!HasEmplace<M>::value, iterator> InsertOrEmplace(
  413. M* m, absl::string_view key) {
  414. return ToIter(m->insert(std::make_pair(First(key), Second(""))));
  415. }
  416. static iterator ToIter(std::pair<iterator, bool> pair) {
  417. return pair.first;
  418. }
  419. static iterator ToIter(iterator iter) { return iter; }
  420. };
  421. StringType text_;
  422. Delimiter delimiter_;
  423. Predicate predicate_;
  424. };
  425. } // namespace strings_internal
  426. ABSL_NAMESPACE_END
  427. } // namespace absl
  428. #endif // ABSL_STRINGS_INTERNAL_STR_SPLIT_INTERNAL_H_