Coverage Report

Created: 2026-08-14 07:20

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