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