Coverage Report

Created: 2025-10-27 06:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/abseil-cpp/absl/strings/string_view.h
Line
Count
Source
1
//
2
// Copyright 2017 The Abseil Authors.
3
//
4
// Licensed under the Apache License, Version 2.0 (the "License");
5
// you may not use this file except in compliance with the License.
6
// You may obtain a copy of the License at
7
//
8
//      https://www.apache.org/licenses/LICENSE-2.0
9
//
10
// Unless required by applicable law or agreed to in writing, software
11
// distributed under the License is distributed on an "AS IS" BASIS,
12
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
// See the License for the specific language governing permissions and
14
// limitations under the License.
15
//
16
// -----------------------------------------------------------------------------
17
// File: string_view.h
18
// -----------------------------------------------------------------------------
19
//
20
// This file contains the definition of the `absl::string_view` class. A
21
// `string_view` points to a contiguous span of characters, often part or all of
22
// another `std::string`, double-quoted string literal, character array, or even
23
// another `string_view`.
24
//
25
// This `absl::string_view` abstraction is designed to be a drop-in
26
// replacement for the C++17 `std::string_view` abstraction.
27
#ifndef ABSL_STRINGS_STRING_VIEW_H_
28
#define ABSL_STRINGS_STRING_VIEW_H_
29
30
#include <algorithm>
31
#include <cassert>
32
#include <cstddef>
33
#include <cstring>
34
#include <iosfwd>
35
#include <iterator>
36
#include <limits>
37
#include <memory>
38
#include <string>
39
#include <type_traits>
40
41
#include "absl/base/attributes.h"
42
#include "absl/base/config.h"
43
#include "absl/base/internal/throw_delegate.h"
44
#include "absl/base/macros.h"
45
#include "absl/base/nullability.h"
46
#include "absl/base/optimization.h"
47
#include "absl/base/port.h"
48
49
#ifdef ABSL_USES_STD_STRING_VIEW
50
51
#include <string_view>  // IWYU pragma: export
52
53
namespace absl {
54
ABSL_NAMESPACE_BEGIN
55
using string_view = std::string_view;
56
ABSL_NAMESPACE_END
57
}  // namespace absl
58
59
#else  // ABSL_USES_STD_STRING_VIEW
60
61
#if ABSL_HAVE_BUILTIN(__builtin_memcmp) ||        \
62
    (defined(__GNUC__) && !defined(__clang__)) || \
63
    (defined(_MSC_VER) && _MSC_VER >= 1928)
64
#define ABSL_INTERNAL_STRING_VIEW_MEMCMP __builtin_memcmp
65
#else  // ABSL_HAVE_BUILTIN(__builtin_memcmp)
66
#define ABSL_INTERNAL_STRING_VIEW_MEMCMP memcmp
67
#endif  // ABSL_HAVE_BUILTIN(__builtin_memcmp)
68
69
// If `std::ranges` is available, mark `string_view` as satisfying the
70
// `view` and `borrowed_range` concepts, just like `std::string_view`.
71
#ifdef __has_include
72
#if __has_include(<version>)
73
#include <version>
74
#endif
75
#endif
76
77
#if defined(__cpp_lib_ranges) && __cpp_lib_ranges >= 201911L
78
#include <ranges>  // NOLINT(build/c++20)
79
80
namespace absl {
81
ABSL_NAMESPACE_BEGIN
82
class string_view;
83
ABSL_NAMESPACE_END
84
}  // namespace absl
85
86
template <>
87
// NOLINTNEXTLINE(build/c++20)
88
inline constexpr bool std::ranges::enable_view<absl::string_view> = true;
89
template <>
90
// NOLINTNEXTLINE(build/c++20)
91
inline constexpr bool std::ranges::enable_borrowed_range<absl::string_view> =
92
    true;
93
#endif
94
95
namespace absl {
96
ABSL_NAMESPACE_BEGIN
97
98
// absl::string_view
99
//
100
// A `string_view` provides a lightweight view into the string data provided by
101
// a `std::string`, double-quoted string literal, character array, or even
102
// another `string_view`. A `string_view` does *not* own the string to which it
103
// points, and that data cannot be modified through the view.
104
//
105
// You can use `string_view` as a function or method parameter anywhere a
106
// parameter can receive a double-quoted string literal, `const char*`,
107
// `std::string`, or another `absl::string_view` argument with no need to copy
108
// the string data. Systematic use of `string_view` within function arguments
109
// reduces data copies and `strlen()` calls.
110
//
111
// Because of its small size, prefer passing `string_view` by value:
112
//
113
//   void MyFunction(absl::string_view arg);
114
//
115
// If circumstances require, you may also pass one by const reference:
116
//
117
//   void MyFunction(const absl::string_view& arg);  // not preferred
118
//
119
// Passing by value generates slightly smaller code for many architectures.
120
//
121
// In either case, the source data of the `string_view` must outlive the
122
// `string_view` itself.
123
//
124
// A `string_view` is also suitable for local variables if you know that the
125
// lifetime of the underlying object is longer than the lifetime of your
126
// `string_view` variable. However, beware of binding a `string_view` to a
127
// temporary value:
128
//
129
//   // BAD use of string_view: lifetime problem
130
//   absl::string_view sv = obj.ReturnAString();
131
//
132
//   // GOOD use of string_view: str outlives sv
133
//   std::string str = obj.ReturnAString();
134
//   absl::string_view sv = str;
135
//
136
// Due to lifetime issues, a `string_view` is sometimes a poor choice for a
137
// return value and usually a poor choice for a data member. If you do use a
138
// `string_view` this way, it is your responsibility to ensure that the object
139
// pointed to by the `string_view` outlives the `string_view`.
140
//
141
// A `string_view` may represent a whole string or just part of a string. For
142
// example, when splitting a string, `std::vector<absl::string_view>` is a
143
// natural data type for the output.
144
//
145
// For another example, a Cord is a non-contiguous, potentially very
146
// long string-like object.  The Cord class has an interface that iteratively
147
// provides string_view objects that point to the successive pieces of a Cord
148
// object.
149
//
150
// When constructed from a source which is NUL-terminated, the `string_view`
151
// itself will not include the NUL-terminator unless a specific size (including
152
// the NUL) is passed to the constructor. As a result, common idioms that work
153
// on NUL-terminated strings do not work on `string_view` objects. If you write
154
// code that scans a `string_view`, you must check its length rather than test
155
// for nul, for example. Note, however, that nuls may still be embedded within
156
// a `string_view` explicitly.
157
//
158
// You may create a null `string_view` in two ways:
159
//
160
//   absl::string_view sv;
161
//   absl::string_view sv(nullptr, 0);
162
//
163
// For the above, `sv.data() == nullptr`, `sv.length() == 0`, and
164
// `sv.empty() == true`. Also, if you create a `string_view` with a non-null
165
// pointer then `sv.data() != nullptr`. Thus, you can use `string_view()` to
166
// signal an undefined value that is different from other `string_view` values
167
// in a similar fashion to how `const char* p1 = nullptr;` is different from
168
// `const char* p2 = "";`. However, in practice, it is not recommended to rely
169
// on this behavior.
170
//
171
// Be careful not to confuse a null `string_view` with an empty one. A null
172
// `string_view` is an empty `string_view`, but some empty `string_view`s are
173
// not null. Prefer checking for emptiness over checking for null.
174
//
175
// There are many ways to create an empty string_view:
176
//
177
//   const char* nullcp = nullptr;
178
//   // string_view.size() will return 0 in all cases.
179
//   absl::string_view();
180
//   absl::string_view(nullcp, 0);
181
//   absl::string_view("");
182
//   absl::string_view("", 0);
183
//   absl::string_view("abcdef", 0);
184
//   absl::string_view("abcdef" + 6, 0);
185
//
186
// All empty `string_view` objects whether null or not, are equal:
187
//
188
//   absl::string_view() == absl::string_view("", 0)
189
//   absl::string_view(nullptr, 0) == absl::string_view("abcdef"+6, 0)
190
class ABSL_ATTRIBUTE_VIEW string_view {
191
 public:
192
  using traits_type = std::char_traits<char>;
193
  using value_type = char;
194
  using pointer = char* absl_nullable;
195
  using const_pointer = const char* absl_nullable;
196
  using reference = char&;
197
  using const_reference = const char&;
198
  using const_iterator = const char* absl_nullable;
199
  using iterator = const_iterator;
200
  using const_reverse_iterator = std::reverse_iterator<const_iterator>;
201
  using reverse_iterator = const_reverse_iterator;
202
  using size_type = size_t;
203
  using difference_type = std::ptrdiff_t;
204
  using absl_internal_is_view = std::true_type;
205
206
  static constexpr size_type npos = static_cast<size_type>(-1);
207
208
  // Null `string_view` constructor
209
  constexpr string_view() noexcept : ptr_(nullptr), length_(0) {}
210
211
  // Implicit constructors
212
213
  template <typename Allocator>
214
  string_view(  // NOLINT(runtime/explicit)
215
      const std::basic_string<char, std::char_traits<char>, Allocator>& str
216
          ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept
217
      // This is implemented in terms of `string_view(p, n)` so `str.size()`
218
      // doesn't need to be reevaluated after `ptr_` is set.
219
      // The length check is also skipped since it is unnecessary and causes
220
      // code bloat.
221
      : string_view(str.data(), str.size(), SkipCheckLengthTag{}) {}
222
223
  // Implicit constructor of a `string_view` from NUL-terminated `str`. When
224
  // accepting possibly null strings, use `absl::NullSafeStringView(str)`
225
  // instead (see below).
226
  // The length check is skipped since it is unnecessary and causes code bloat.
227
  constexpr string_view(  // NOLINT(runtime/explicit)
228
      const char* absl_nonnull str)
229
      : ptr_(str), length_(str ? StrlenInternal(str) : 0) {
230
    assert(str != nullptr);
231
  }
232
233
  // Constructor of a `string_view` from a `const char*` and length.
234
  constexpr string_view(const char* absl_nullable data, size_type len)
235
      : ptr_(data), length_(CheckLengthInternal(len)) {
236
    ABSL_ASSERT(data != nullptr || len == 0);
237
  }
238
239
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
240
  template <std::contiguous_iterator It, std::sized_sentinel_for<It> End>
241
    requires(std::is_same_v<std::iter_value_t<It>, value_type> &&
242
             !std::is_convertible_v<End, size_type>)
243
  constexpr string_view(It begin, End end)
244
      : ptr_(std::to_address(begin)), length_(end - begin) {
245
    ABSL_HARDENING_ASSERT(end >= begin);
246
  }
247
#endif  // ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
248
249
  constexpr string_view(const string_view&) noexcept = default;
250
  string_view& operator=(const string_view&) noexcept = default;
251
252
  // Iterators
253
254
  // string_view::begin()
255
  //
256
  // Returns an iterator pointing to the first character at the beginning of the
257
  // `string_view`, or `end()` if the `string_view` is empty.
258
  constexpr const_iterator begin() const noexcept { return ptr_; }
259
260
  // string_view::end()
261
  //
262
  // Returns an iterator pointing just beyond the last character at the end of
263
  // the `string_view`. This iterator acts as a placeholder; attempting to
264
  // access it results in undefined behavior.
265
  constexpr const_iterator end() const noexcept { return ptr_ + length_; }
266
267
  // string_view::cbegin()
268
  //
269
  // Returns a const iterator pointing to the first character at the beginning
270
  // of the `string_view`, or `end()` if the `string_view` is empty.
271
  constexpr const_iterator cbegin() const noexcept { return begin(); }
272
273
  // string_view::cend()
274
  //
275
  // Returns a const iterator pointing just beyond the last character at the end
276
  // of the `string_view`. This pointer acts as a placeholder; attempting to
277
  // access its element results in undefined behavior.
278
  constexpr const_iterator cend() const noexcept { return end(); }
279
280
  // string_view::rbegin()
281
  //
282
  // Returns a reverse iterator pointing to the last character at the end of the
283
  // `string_view`, or `rend()` if the `string_view` is empty.
284
  const_reverse_iterator rbegin() const noexcept {
285
    return const_reverse_iterator(end());
286
  }
287
288
  // string_view::rend()
289
  //
290
  // Returns a reverse iterator pointing just before the first character at the
291
  // beginning of the `string_view`. This pointer acts as a placeholder;
292
  // attempting to access its element results in undefined behavior.
293
  const_reverse_iterator rend() const noexcept {
294
    return const_reverse_iterator(begin());
295
  }
296
297
  // string_view::crbegin()
298
  //
299
  // Returns a const reverse iterator pointing to the last character at the end
300
  // of the `string_view`, or `crend()` if the `string_view` is empty.
301
  const_reverse_iterator crbegin() const noexcept { return rbegin(); }
302
303
  // string_view::crend()
304
  //
305
  // Returns a const reverse iterator pointing just before the first character
306
  // at the beginning of the `string_view`. This pointer acts as a placeholder;
307
  // attempting to access its element results in undefined behavior.
308
  const_reverse_iterator crend() const noexcept { return rend(); }
309
310
  // Capacity Utilities
311
312
  // string_view::size()
313
  //
314
  // Returns the number of characters in the `string_view`.
315
  constexpr size_type size() const noexcept { return length_; }
316
317
  // string_view::length()
318
  //
319
  // Returns the number of characters in the `string_view`. Alias for `size()`.
320
  constexpr size_type length() const noexcept { return size(); }
321
322
  // string_view::max_size()
323
  //
324
  // Returns the maximum number of characters the `string_view` can hold.
325
  constexpr size_type max_size() const noexcept { return kMaxSize; }
326
327
  // string_view::empty()
328
  //
329
  // Checks if the `string_view` is empty (refers to no characters).
330
  constexpr bool empty() const noexcept { return length_ == 0; }
331
332
  // string_view::operator[]
333
  //
334
  // Returns the ith element of the `string_view` using the array operator.
335
  // Note that this operator does not perform any bounds checking.
336
  constexpr const_reference operator[](size_type i) const {
337
    ABSL_HARDENING_ASSERT(i < size());
338
    return ptr_[i];
339
  }
340
341
  // string_view::at()
342
  //
343
  // Returns the ith element of the `string_view`. Bounds checking is performed,
344
  // and an exception of type `std::out_of_range` will be thrown on invalid
345
  // access.
346
  constexpr const_reference at(size_type i) const {
347
    if (ABSL_PREDICT_FALSE(i >= size())) {
348
      base_internal::ThrowStdOutOfRange("absl::string_view::at");
349
    }
350
    return ptr_[i];
351
  }
352
353
  // string_view::front()
354
  //
355
  // Returns the first element of a `string_view`.
356
  constexpr const_reference front() const {
357
    ABSL_HARDENING_ASSERT(!empty());
358
    return ptr_[0];
359
  }
360
361
  // string_view::back()
362
  //
363
  // Returns the last element of a `string_view`.
364
  constexpr const_reference back() const {
365
    ABSL_HARDENING_ASSERT(!empty());
366
    return ptr_[size() - 1];
367
  }
368
369
  // string_view::data()
370
  //
371
  // Returns a pointer to the underlying character array (which is of course
372
  // stored elsewhere). Note that `string_view::data()` may contain embedded nul
373
  // characters, but the returned buffer may or may not be NUL-terminated;
374
  // therefore, do not pass `data()` to a routine that expects a NUL-terminated
375
  // string.
376
  constexpr const_pointer data() const noexcept { return ptr_; }
377
378
  // Modifiers
379
380
  // string_view::remove_prefix()
381
  //
382
  // Removes the first `n` characters from the `string_view`. Note that the
383
  // underlying string is not changed, only the view.
384
  constexpr void remove_prefix(size_type n) {
385
    ABSL_HARDENING_ASSERT(n <= length_);
386
    ptr_ += n;
387
    length_ -= n;
388
  }
389
390
  // string_view::remove_suffix()
391
  //
392
  // Removes the last `n` characters from the `string_view`. Note that the
393
  // underlying string is not changed, only the view.
394
  constexpr void remove_suffix(size_type n) {
395
    ABSL_HARDENING_ASSERT(n <= length_);
396
    length_ -= n;
397
  }
398
399
  // string_view::swap()
400
  //
401
  // Swaps this `string_view` with another `string_view`.
402
  constexpr void swap(string_view& s) noexcept {
403
    auto t = *this;
404
    *this = s;
405
    s = t;
406
  }
407
408
  // Explicit conversion operators
409
410
  // Converts to `std::basic_string`.
411
  template <typename A>
412
  explicit operator std::basic_string<char, traits_type, A>() const {
413
    if (!data()) return {};
414
    return std::basic_string<char, traits_type, A>(data(), size());
415
  }
416
417
  // string_view::copy()
418
  //
419
  // Copies the contents of the `string_view` at offset `pos` and length `n`
420
  // into `buf`.
421
  size_type copy(char* absl_nonnull buf, size_type n, size_type pos = 0) const {
422
    if (ABSL_PREDICT_FALSE(pos > length_)) {
423
      base_internal::ThrowStdOutOfRange("absl::string_view::copy");
424
    }
425
    size_type rlen = (std::min)(length_ - pos, n);
426
    if (rlen > 0) {
427
      const char* start = ptr_ + pos;
428
      traits_type::copy(buf, start, rlen);
429
    }
430
    return rlen;
431
  }
432
433
  // string_view::substr()
434
  //
435
  // Returns a "substring" of the `string_view` (at offset `pos` and length
436
  // `n`) as another string_view. This function throws `std::out_of_bounds` if
437
  // `pos > size`.
438
  // Use absl::ClippedSubstr if you need a truncating substr operation.
439
  constexpr string_view substr(size_type pos = 0, size_type n = npos) const {
440
    if (ABSL_PREDICT_FALSE(pos > length_)) {
441
      base_internal::ThrowStdOutOfRange("absl::string_view::substr");
442
    }
443
    return string_view(ptr_ + pos, (std::min)(n, length_ - pos));
444
  }
445
446
  // string_view::compare()
447
  //
448
  // Performs a lexicographical comparison between this `string_view` and
449
  // another `string_view` `x`, returning a negative value if `*this` is less
450
  // than `x`, 0 if `*this` is equal to `x`, and a positive value if `*this`
451
  // is greater than `x`.
452
  constexpr int compare(string_view x) const noexcept {
453
    return CompareImpl(length_, x.length_,
454
                       (std::min)(length_, x.length_) == 0
455
                           ? 0
456
                           : ABSL_INTERNAL_STRING_VIEW_MEMCMP(
457
                                 ptr_, x.ptr_, (std::min)(length_, x.length_)));
458
  }
459
460
  // Overload of `string_view::compare()` for comparing a substring of the
461
  // 'string_view` and another `absl::string_view`.
462
  constexpr int compare(size_type pos1, size_type count1, string_view v) const {
463
    return substr(pos1, count1).compare(v);
464
  }
465
466
  // Overload of `string_view::compare()` for comparing a substring of the
467
  // `string_view` and a substring of another `absl::string_view`.
468
  constexpr int compare(size_type pos1, size_type count1, string_view v,
469
                        size_type pos2, size_type count2) const {
470
    return substr(pos1, count1).compare(v.substr(pos2, count2));
471
  }
472
473
  // Overload of `string_view::compare()` for comparing a `string_view` and a
474
  // a different C-style string `s`.
475
  constexpr int compare(const char* absl_nonnull s) const {
476
    return compare(string_view(s));
477
  }
478
479
  // Overload of `string_view::compare()` for comparing a substring of the
480
  // `string_view` and a different string C-style string `s`.
481
  constexpr int compare(size_type pos1, size_type count1,
482
                        const char* absl_nonnull s) const {
483
    return substr(pos1, count1).compare(string_view(s));
484
  }
485
486
  // Overload of `string_view::compare()` for comparing a substring of the
487
  // `string_view` and a substring of a different C-style string `s`.
488
  constexpr int compare(size_type pos1, size_type count1,
489
                        const char* absl_nonnull s, size_type count2) const {
490
    return substr(pos1, count1).compare(string_view(s, count2));
491
  }
492
493
  // Find Utilities
494
495
  // string_view::find()
496
  //
497
  // Finds the first occurrence of the substring `s` within the `string_view`,
498
  // returning the position of the first character's match, or `npos` if no
499
  // match was found.
500
  size_type find(string_view s, size_type pos = 0) const noexcept;
501
502
  // Overload of `string_view::find()` for finding the given character `c`
503
  // within the `string_view`.
504
  size_type find(char c, size_type pos = 0) const noexcept;
505
506
  // Overload of `string_view::find()` for finding a substring of a different
507
  // C-style string `s` within the `string_view`.
508
  size_type find(const char* absl_nonnull s, size_type pos,
509
                 size_type count) const {
510
    return find(string_view(s, count), pos);
511
  }
512
513
  // Overload of `string_view::find()` for finding a different C-style string
514
  // `s` within the `string_view`.
515
  size_type find(const char* absl_nonnull s, size_type pos = 0) const {
516
    return find(string_view(s), pos);
517
  }
518
519
  // string_view::rfind()
520
  //
521
  // Finds the last occurrence of a substring `s` within the `string_view`,
522
  // returning the position of the first character's match, or `npos` if no
523
  // match was found.
524
  size_type rfind(string_view s, size_type pos = npos) const noexcept;
525
526
  // Overload of `string_view::rfind()` for finding the last given character `c`
527
  // within the `string_view`.
528
  size_type rfind(char c, size_type pos = npos) const noexcept;
529
530
  // Overload of `string_view::rfind()` for finding a substring of a different
531
  // C-style string `s` within the `string_view`.
532
  size_type rfind(const char* absl_nonnull s, size_type pos,
533
                  size_type count) const {
534
    return rfind(string_view(s, count), pos);
535
  }
536
537
  // Overload of `string_view::rfind()` for finding a different C-style string
538
  // `s` within the `string_view`.
539
  size_type rfind(const char* absl_nonnull s, size_type pos = npos) const {
540
    return rfind(string_view(s), pos);
541
  }
542
543
  // string_view::find_first_of()
544
  //
545
  // Finds the first occurrence of any of the characters in `s` within the
546
  // `string_view`, returning the start position of the match, or `npos` if no
547
  // match was found.
548
  size_type find_first_of(string_view s, size_type pos = 0) const noexcept;
549
550
  // Overload of `string_view::find_first_of()` for finding a character `c`
551
  // within the `string_view`.
552
  size_type find_first_of(char c, size_type pos = 0) const noexcept {
553
    return find(c, pos);
554
  }
555
556
  // Overload of `string_view::find_first_of()` for finding a substring of a
557
  // different C-style string `s` within the `string_view`.
558
  size_type find_first_of(const char* absl_nonnull s, size_type pos,
559
                          size_type count) const {
560
    return find_first_of(string_view(s, count), pos);
561
  }
562
563
  // Overload of `string_view::find_first_of()` for finding a different C-style
564
  // string `s` within the `string_view`.
565
  size_type find_first_of(const char* absl_nonnull s, size_type pos = 0) const {
566
    return find_first_of(string_view(s), pos);
567
  }
568
569
  // string_view::find_last_of()
570
  //
571
  // Finds the last occurrence of any of the characters in `s` within the
572
  // `string_view`, returning the start position of the match, or `npos` if no
573
  // match was found.
574
  size_type find_last_of(string_view s, size_type pos = npos) const noexcept;
575
576
  // Overload of `string_view::find_last_of()` for finding a character `c`
577
  // within the `string_view`.
578
  size_type find_last_of(char c, size_type pos = npos) const noexcept {
579
    return rfind(c, pos);
580
  }
581
582
  // Overload of `string_view::find_last_of()` for finding a substring of a
583
  // different C-style string `s` within the `string_view`.
584
  size_type find_last_of(const char* absl_nonnull s, size_type pos,
585
                         size_type count) const {
586
    return find_last_of(string_view(s, count), pos);
587
  }
588
589
  // Overload of `string_view::find_last_of()` for finding a different C-style
590
  // string `s` within the `string_view`.
591
  size_type find_last_of(const char* absl_nonnull s,
592
                         size_type pos = npos) const {
593
    return find_last_of(string_view(s), pos);
594
  }
595
596
  // string_view::find_first_not_of()
597
  //
598
  // Finds the first occurrence of any of the characters not in `s` within the
599
  // `string_view`, returning the start position of the first non-match, or
600
  // `npos` if no non-match was found.
601
  size_type find_first_not_of(string_view s, size_type pos = 0) const noexcept;
602
603
  // Overload of `string_view::find_first_not_of()` for finding a character
604
  // that is not `c` within the `string_view`.
605
  size_type find_first_not_of(char c, size_type pos = 0) const noexcept;
606
607
  // Overload of `string_view::find_first_not_of()` for finding a substring of a
608
  // different C-style string `s` within the `string_view`.
609
  size_type find_first_not_of(const char* absl_nonnull s, size_type pos,
610
                              size_type count) const {
611
    return find_first_not_of(string_view(s, count), pos);
612
  }
613
614
  // Overload of `string_view::find_first_not_of()` for finding a different
615
  // C-style string `s` within the `string_view`.
616
  size_type find_first_not_of(const char* absl_nonnull s,
617
                              size_type pos = 0) const {
618
    return find_first_not_of(string_view(s), pos);
619
  }
620
621
  // string_view::find_last_not_of()
622
  //
623
  // Finds the last occurrence of any of the characters not in `s` within the
624
  // `string_view`, returning the start position of the last non-match, or
625
  // `npos` if no non-match was found.
626
  size_type find_last_not_of(string_view s,
627
                             size_type pos = npos) const noexcept;
628
629
  // Overload of `string_view::find_last_not_of()` for finding a character
630
  // that is not `c` within the `string_view`.
631
  size_type find_last_not_of(char c, size_type pos = npos) const noexcept;
632
633
  // Overload of `string_view::find_last_not_of()` for finding a substring of a
634
  // different C-style string `s` within the `string_view`.
635
  size_type find_last_not_of(const char* absl_nonnull s, size_type pos,
636
                             size_type count) const {
637
    return find_last_not_of(string_view(s, count), pos);
638
  }
639
640
  // Overload of `string_view::find_last_not_of()` for finding a different
641
  // C-style string `s` within the `string_view`.
642
  size_type find_last_not_of(const char* absl_nonnull s,
643
                             size_type pos = npos) const {
644
    return find_last_not_of(string_view(s), pos);
645
  }
646
647
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
648
  // string_view::starts_with()
649
  //
650
  // Returns true if the `string_view` starts with the prefix `s`.
651
  //
652
  // This method only exists when targeting at least C++20.
653
  // If support for C++ prior to C++20 is required, use `absl::StartsWith()`
654
  // from `//absl/strings/match.h` for compatibility.
655
  constexpr bool starts_with(string_view s) const noexcept {
656
    return s.empty() ||
657
           (size() >= s.size() &&
658
            ABSL_INTERNAL_STRING_VIEW_MEMCMP(data(), s.data(), s.size()) == 0);
659
  }
660
661
  // Overload of `string_view::starts_with()` that returns true if `c` is the
662
  // first character of the `string_view`.
663
  constexpr bool starts_with(char c) const noexcept {
664
    return !empty() && front() == c;
665
  }
666
667
  // Overload of `string_view::starts_with()` that returns true if the
668
  // `string_view` starts with the C-style prefix `s`.
669
  constexpr bool starts_with(const char* absl_nonnull s) const {
670
    return starts_with(string_view(s));
671
  }
672
673
  // string_view::ends_with()
674
  //
675
  // Returns true if the `string_view` ends with the suffix `s`.
676
  //
677
  // This method only exists when targeting at least C++20.
678
  // If support for C++ prior to C++20 is required, use `absl::EndsWith()`
679
  // from `//absl/strings/match.h` for compatibility.
680
  constexpr bool ends_with(string_view s) const noexcept {
681
    return s.empty() || (size() >= s.size() && ABSL_INTERNAL_STRING_VIEW_MEMCMP(
682
                                                   data() + (size() - s.size()),
683
                                                   s.data(), s.size()) == 0);
684
  }
685
686
  // Overload of `string_view::ends_with()` that returns true if `c` is the
687
  // last character of the `string_view`.
688
  constexpr bool ends_with(char c) const noexcept {
689
    return !empty() && back() == c;
690
  }
691
692
  // Overload of `string_view::ends_with()` that returns true if the
693
  // `string_view` ends with the C-style suffix `s`.
694
  constexpr bool ends_with(const char* absl_nonnull s) const {
695
    return ends_with(string_view(s));
696
  }
697
#endif  // ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
698
699
 private:
700
  // The constructor from std::string delegates to this constructor.
701
  // See the comment on that constructor for the rationale.
702
  struct SkipCheckLengthTag {};
703
  string_view(const char* absl_nullable data, size_type len,
704
              SkipCheckLengthTag) noexcept
705
      : ptr_(data), length_(len) {}
706
707
  static constexpr size_type kMaxSize =
708
      (std::numeric_limits<difference_type>::max)();
709
710
  static constexpr size_type CheckLengthInternal(size_type len) {
711
    ABSL_HARDENING_ASSERT(len <= kMaxSize);
712
    return len;
713
  }
714
715
  static constexpr size_type StrlenInternal(const char* absl_nonnull str) {
716
#if defined(_MSC_VER) && !defined(__clang__)
717
    // MSVC 2017+ can evaluate this at compile-time.
718
    const char* begin = str;
719
    while (*str != '\0') ++str;
720
    return str - begin;
721
#elif ABSL_HAVE_BUILTIN(__builtin_strlen) || \
722
    (defined(__GNUC__) && !defined(__clang__))
723
    // GCC has __builtin_strlen according to
724
    // https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Other-Builtins.html, but
725
    // ABSL_HAVE_BUILTIN doesn't detect that, so we use the extra checks above.
726
    // __builtin_strlen is constexpr.
727
    return __builtin_strlen(str);
728
#else
729
    return str ? strlen(str) : 0;
730
#endif
731
  }
732
733
  static constexpr int CompareImpl(size_type length_a, size_type length_b,
734
                                   int compare_result) {
735
    return compare_result == 0 ? static_cast<int>(length_a > length_b) -
736
                                     static_cast<int>(length_a < length_b)
737
                               : (compare_result < 0 ? -1 : 1);
738
  }
739
740
  const char* absl_nullable ptr_;
741
  size_type length_;
742
};
743
744
// This large function is defined inline so that in a fairly common case where
745
// one of the arguments is a literal, the compiler can elide a lot of the
746
// following comparisons.
747
constexpr bool operator==(string_view x, string_view y) noexcept {
748
  return x.size() == y.size() &&
749
         (x.empty() ||
750
          ABSL_INTERNAL_STRING_VIEW_MEMCMP(x.data(), y.data(), x.size()) == 0);
751
}
752
753
constexpr bool operator!=(string_view x, string_view y) noexcept {
754
  return !(x == y);
755
}
756
757
constexpr bool operator<(string_view x, string_view y) noexcept {
758
  return x.compare(y) < 0;
759
}
760
761
constexpr bool operator>(string_view x, string_view y) noexcept {
762
  return y < x;
763
}
764
765
constexpr bool operator<=(string_view x, string_view y) noexcept {
766
  return !(y < x);
767
}
768
769
constexpr bool operator>=(string_view x, string_view y) noexcept {
770
  return !(x < y);
771
}
772
773
// IO Insertion Operator
774
std::ostream& operator<<(std::ostream& o, string_view piece);
775
776
ABSL_NAMESPACE_END
777
}  // namespace absl
778
779
#undef ABSL_INTERNAL_STRING_VIEW_MEMCMP
780
781
#endif  // ABSL_USES_STD_STRING_VIEW
782
783
namespace absl {
784
ABSL_NAMESPACE_BEGIN
785
786
// ClippedSubstr()
787
//
788
// Like `s.substr(pos, n)`, but clips `pos` to an upper bound of `s.size()`.
789
// Provided because std::string_view::substr throws if `pos > size()`
790
inline string_view ClippedSubstr(string_view s ABSL_ATTRIBUTE_LIFETIME_BOUND,
791
0
                                 size_t pos, size_t n = string_view::npos) {
792
0
  pos = (std::min)(pos, static_cast<size_t>(s.size()));
793
0
  return s.substr(pos, n);
794
0
}
795
796
// NullSafeStringView()
797
//
798
// Creates an `absl::string_view` from a pointer `p` even if it's null-valued.
799
// This function should be used where an `absl::string_view` can be created from
800
// a possibly-null pointer.
801
0
constexpr string_view NullSafeStringView(const char* absl_nullable p) {
802
0
  return p ? string_view(p) : string_view();
803
0
}
804
805
ABSL_NAMESPACE_END
806
}  // namespace absl
807
808
#endif  // ABSL_STRINGS_STRING_VIEW_H_