Coverage Report

Created: 2025-12-14 06:06

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