string_view.h 29 KB

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