Coverage Report

Created: 2025-08-28 06:48

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