Debian Codegraph @

Xpjproject/third_party/webrtc_aec3/src/absl/strings/string_view.h

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