• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "absl/strings/string_view.h"
16 
17 #include <stdlib.h>
18 #include <iomanip>
19 #include <iterator>
20 #include <limits>
21 #include <map>
22 #include <sstream>
23 #include <stdexcept>
24 #include <string>
25 #include <type_traits>
26 #include <utility>
27 
28 #include "gtest/gtest.h"
29 #include "absl/base/config.h"
30 #include "absl/base/dynamic_annotations.h"
31 
32 #if defined(ABSL_HAVE_STD_STRING_VIEW) || defined(__ANDROID__)
33 // We don't control the death messaging when using std::string_view.
34 // Android assert messages only go to system log, so death tests cannot inspect
35 // the message for matching.
36 #define ABSL_EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
37   EXPECT_DEATH_IF_SUPPORTED(statement, ".*")
38 #else
39 #define ABSL_EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
40   EXPECT_DEATH_IF_SUPPORTED(statement, regex)
41 #endif
42 
43 namespace {
44 
45 // A minimal allocator that uses malloc().
46 template <typename T>
47 struct Mallocator {
48   typedef T value_type;
49   typedef size_t size_type;
50   typedef ptrdiff_t difference_type;
51   typedef T* pointer;
52   typedef const T* const_pointer;
53   typedef T& reference;
54   typedef const T& const_reference;
55 
max_size__anon571393f50111::Mallocator56   size_type max_size() const {
57     return size_t(std::numeric_limits<size_type>::max()) / sizeof(value_type);
58   }
59   template <typename U>
60   struct rebind {
61     typedef Mallocator<U> other;
62   };
63   Mallocator() = default;
64   template <class U>
Mallocator__anon571393f50111::Mallocator65   Mallocator(const Mallocator<U>&) {}  // NOLINT(runtime/explicit)
66 
allocate__anon571393f50111::Mallocator67   T* allocate(size_t n) { return static_cast<T*>(std::malloc(n * sizeof(T))); }
deallocate__anon571393f50111::Mallocator68   void deallocate(T* p, size_t) { std::free(p); }
69 };
70 template <typename T, typename U>
operator ==(const Mallocator<T> &,const Mallocator<U> &)71 bool operator==(const Mallocator<T>&, const Mallocator<U>&) {
72   return true;
73 }
74 template <typename T, typename U>
operator !=(const Mallocator<T> &,const Mallocator<U> &)75 bool operator!=(const Mallocator<T>&, const Mallocator<U>&) {
76   return false;
77 }
78 
TEST(StringViewTest,Ctor)79 TEST(StringViewTest, Ctor) {
80   {
81     // Null.
82     absl::string_view s10;
83     EXPECT_TRUE(s10.data() == nullptr);
84     EXPECT_EQ(0, s10.length());
85   }
86 
87   {
88     // const char* without length.
89     const char* hello = "hello";
90     absl::string_view s20(hello);
91     EXPECT_TRUE(s20.data() == hello);
92     EXPECT_EQ(5, s20.length());
93 
94     // const char* with length.
95     absl::string_view s21(hello, 4);
96     EXPECT_TRUE(s21.data() == hello);
97     EXPECT_EQ(4, s21.length());
98 
99     // Not recommended, but valid C++
100     absl::string_view s22(hello, 6);
101     EXPECT_TRUE(s22.data() == hello);
102     EXPECT_EQ(6, s22.length());
103   }
104 
105   {
106     // std::string.
107     std::string hola = "hola";
108     absl::string_view s30(hola);
109     EXPECT_TRUE(s30.data() == hola.data());
110     EXPECT_EQ(4, s30.length());
111 
112     // std::string with embedded '\0'.
113     hola.push_back('\0');
114     hola.append("h2");
115     hola.push_back('\0');
116     absl::string_view s31(hola);
117     EXPECT_TRUE(s31.data() == hola.data());
118     EXPECT_EQ(8, s31.length());
119   }
120 
121   {
122     using mstring =
123         std::basic_string<char, std::char_traits<char>, Mallocator<char>>;
124     mstring str1("BUNGIE-JUMPING!");
125     const mstring str2("SLEEPING!");
126 
127     absl::string_view s1(str1);
128     s1.remove_prefix(strlen("BUNGIE-JUM"));
129 
130     absl::string_view s2(str2);
131     s2.remove_prefix(strlen("SLEE"));
132 
133     EXPECT_EQ(s1, s2);
134     EXPECT_EQ(s1, "PING!");
135   }
136 
137   // TODO(mec): absl::string_view(const absl::string_view&);
138 }
139 
TEST(StringViewTest,Swap)140 TEST(StringViewTest, Swap) {
141   absl::string_view a("a");
142   absl::string_view b("bbb");
143   EXPECT_TRUE(noexcept(a.swap(b)));
144   a.swap(b);
145   EXPECT_EQ(a, "bbb");
146   EXPECT_EQ(b, "a");
147   a.swap(b);
148   EXPECT_EQ(a, "a");
149   EXPECT_EQ(b, "bbb");
150 }
151 
TEST(StringViewTest,STLComparator)152 TEST(StringViewTest, STLComparator) {
153   std::string s1("foo");
154   std::string s2("bar");
155   std::string s3("baz");
156 
157   absl::string_view p1(s1);
158   absl::string_view p2(s2);
159   absl::string_view p3(s3);
160 
161   typedef std::map<absl::string_view, int> TestMap;
162   TestMap map;
163 
164   map.insert(std::make_pair(p1, 0));
165   map.insert(std::make_pair(p2, 1));
166   map.insert(std::make_pair(p3, 2));
167   EXPECT_EQ(map.size(), 3);
168 
169   TestMap::const_iterator iter = map.begin();
170   EXPECT_EQ(iter->second, 1);
171   ++iter;
172   EXPECT_EQ(iter->second, 2);
173   ++iter;
174   EXPECT_EQ(iter->second, 0);
175   ++iter;
176   EXPECT_TRUE(iter == map.end());
177 
178   TestMap::iterator new_iter = map.find("zot");
179   EXPECT_TRUE(new_iter == map.end());
180 
181   new_iter = map.find("bar");
182   EXPECT_TRUE(new_iter != map.end());
183 
184   map.erase(new_iter);
185   EXPECT_EQ(map.size(), 2);
186 
187   iter = map.begin();
188   EXPECT_EQ(iter->second, 2);
189   ++iter;
190   EXPECT_EQ(iter->second, 0);
191   ++iter;
192   EXPECT_TRUE(iter == map.end());
193 }
194 
195 #define COMPARE(result, op, x, y)                                      \
196   EXPECT_EQ(result, absl::string_view((x)) op absl::string_view((y))); \
197   EXPECT_EQ(result, absl::string_view((x)).compare(absl::string_view((y))) op 0)
198 
TEST(StringViewTest,ComparisonOperators)199 TEST(StringViewTest, ComparisonOperators) {
200   COMPARE(true, ==, "",   "");
201   COMPARE(true, ==, "", absl::string_view());
202   COMPARE(true, ==, absl::string_view(), "");
203   COMPARE(true, ==, "a",  "a");
204   COMPARE(true, ==, "aa", "aa");
205   COMPARE(false, ==, "a",  "");
206   COMPARE(false, ==, "",   "a");
207   COMPARE(false, ==, "a",  "b");
208   COMPARE(false, ==, "a",  "aa");
209   COMPARE(false, ==, "aa", "a");
210 
211   COMPARE(false, !=, "",   "");
212   COMPARE(false, !=, "a",  "a");
213   COMPARE(false, !=, "aa", "aa");
214   COMPARE(true, !=, "a",  "");
215   COMPARE(true, !=, "",   "a");
216   COMPARE(true, !=, "a",  "b");
217   COMPARE(true, !=, "a",  "aa");
218   COMPARE(true, !=, "aa", "a");
219 
220   COMPARE(true, <, "a",  "b");
221   COMPARE(true, <, "a",  "aa");
222   COMPARE(true, <, "aa", "b");
223   COMPARE(true, <, "aa", "bb");
224   COMPARE(false, <, "a",  "a");
225   COMPARE(false, <, "b",  "a");
226   COMPARE(false, <, "aa", "a");
227   COMPARE(false, <, "b",  "aa");
228   COMPARE(false, <, "bb", "aa");
229 
230   COMPARE(true, <=, "a",  "a");
231   COMPARE(true, <=, "a",  "b");
232   COMPARE(true, <=, "a",  "aa");
233   COMPARE(true, <=, "aa", "b");
234   COMPARE(true, <=, "aa", "bb");
235   COMPARE(false, <=, "b",  "a");
236   COMPARE(false, <=, "aa", "a");
237   COMPARE(false, <=, "b",  "aa");
238   COMPARE(false, <=, "bb", "aa");
239 
240   COMPARE(false, >=, "a",  "b");
241   COMPARE(false, >=, "a",  "aa");
242   COMPARE(false, >=, "aa", "b");
243   COMPARE(false, >=, "aa", "bb");
244   COMPARE(true, >=, "a",  "a");
245   COMPARE(true, >=, "b",  "a");
246   COMPARE(true, >=, "aa", "a");
247   COMPARE(true, >=, "b",  "aa");
248   COMPARE(true, >=, "bb", "aa");
249 
250   COMPARE(false, >, "a",  "a");
251   COMPARE(false, >, "a",  "b");
252   COMPARE(false, >, "a",  "aa");
253   COMPARE(false, >, "aa", "b");
254   COMPARE(false, >, "aa", "bb");
255   COMPARE(true, >, "b",  "a");
256   COMPARE(true, >, "aa", "a");
257   COMPARE(true, >, "b",  "aa");
258   COMPARE(true, >, "bb", "aa");
259 }
260 
TEST(StringViewTest,ComparisonOperatorsByCharacterPosition)261 TEST(StringViewTest, ComparisonOperatorsByCharacterPosition) {
262   std::string x;
263   for (int i = 0; i < 256; i++) {
264     x += 'a';
265     std::string y = x;
266     COMPARE(true, ==, x, y);
267     for (int j = 0; j < i; j++) {
268       std::string z = x;
269       z[j] = 'b';       // Differs in position 'j'
270       COMPARE(false, ==, x, z);
271       COMPARE(true, <, x, z);
272       COMPARE(true, >, z, x);
273       if (j + 1 < i) {
274         z[j + 1] = 'A';  // Differs in position 'j+1' as well
275         COMPARE(false, ==, x, z);
276         COMPARE(true, <, x, z);
277         COMPARE(true, >, z, x);
278         z[j + 1] = 'z';  // Differs in position 'j+1' as well
279         COMPARE(false, ==, x, z);
280         COMPARE(true, <, x, z);
281         COMPARE(true, >, z, x);
282       }
283     }
284   }
285 }
286 #undef COMPARE
287 
288 // Sadly, our users often confuse std::string::npos with
289 // absl::string_view::npos; So much so that we test here that they are the same.
290 // They need to both be unsigned, and both be the maximum-valued integer of
291 // their type.
292 
293 template <typename T>
294 struct is_type {
295   template <typename U>
same__anon571393f50111::is_type296   static bool same(U) {
297     return false;
298   }
same__anon571393f50111::is_type299   static bool same(T) { return true; }
300 };
301 
TEST(StringViewTest,NposMatchesStdStringView)302 TEST(StringViewTest, NposMatchesStdStringView) {
303   EXPECT_EQ(absl::string_view::npos, std::string::npos);
304 
305   EXPECT_TRUE(is_type<size_t>::same(absl::string_view::npos));
306   EXPECT_FALSE(is_type<size_t>::same(""));
307 
308   // Make sure absl::string_view::npos continues to be a header constant.
309   char test[absl::string_view::npos & 1] = {0};
310   EXPECT_EQ(0, test[0]);
311 }
312 
TEST(StringViewTest,STL1)313 TEST(StringViewTest, STL1) {
314   const absl::string_view a("abcdefghijklmnopqrstuvwxyz");
315   const absl::string_view b("abc");
316   const absl::string_view c("xyz");
317   const absl::string_view d("foobar");
318   const absl::string_view e;
319   std::string temp("123");
320   temp += '\0';
321   temp += "456";
322   const absl::string_view f(temp);
323 
324   EXPECT_EQ(a[6], 'g');
325   EXPECT_EQ(b[0], 'a');
326   EXPECT_EQ(c[2], 'z');
327   EXPECT_EQ(f[3], '\0');
328   EXPECT_EQ(f[5], '5');
329 
330   EXPECT_EQ(*d.data(), 'f');
331   EXPECT_EQ(d.data()[5], 'r');
332   EXPECT_TRUE(e.data() == nullptr);
333 
334   EXPECT_EQ(*a.begin(), 'a');
335   EXPECT_EQ(*(b.begin() + 2), 'c');
336   EXPECT_EQ(*(c.end() - 1), 'z');
337 
338   EXPECT_EQ(*a.rbegin(), 'z');
339   EXPECT_EQ(*(b.rbegin() + 2), 'a');
340   EXPECT_EQ(*(c.rend() - 1), 'x');
341   EXPECT_TRUE(a.rbegin() + 26 == a.rend());
342 
343   EXPECT_EQ(a.size(), 26);
344   EXPECT_EQ(b.size(), 3);
345   EXPECT_EQ(c.size(), 3);
346   EXPECT_EQ(d.size(), 6);
347   EXPECT_EQ(e.size(), 0);
348   EXPECT_EQ(f.size(), 7);
349 
350   EXPECT_TRUE(!d.empty());
351   EXPECT_TRUE(d.begin() != d.end());
352   EXPECT_TRUE(d.begin() + 6 == d.end());
353 
354   EXPECT_TRUE(e.empty());
355   EXPECT_TRUE(e.begin() == e.end());
356 
357   char buf[4] = { '%', '%', '%', '%' };
358   EXPECT_EQ(a.copy(buf, 4), 4);
359   EXPECT_EQ(buf[0], a[0]);
360   EXPECT_EQ(buf[1], a[1]);
361   EXPECT_EQ(buf[2], a[2]);
362   EXPECT_EQ(buf[3], a[3]);
363   EXPECT_EQ(a.copy(buf, 3, 7), 3);
364   EXPECT_EQ(buf[0], a[7]);
365   EXPECT_EQ(buf[1], a[8]);
366   EXPECT_EQ(buf[2], a[9]);
367   EXPECT_EQ(buf[3], a[3]);
368   EXPECT_EQ(c.copy(buf, 99), 3);
369   EXPECT_EQ(buf[0], c[0]);
370   EXPECT_EQ(buf[1], c[1]);
371   EXPECT_EQ(buf[2], c[2]);
372   EXPECT_EQ(buf[3], a[3]);
373 #ifdef ABSL_HAVE_EXCEPTIONS
374   EXPECT_THROW(a.copy(buf, 1, 27), std::out_of_range);
375 #else
376   ABSL_EXPECT_DEATH_IF_SUPPORTED(a.copy(buf, 1, 27), "absl::string_view::copy");
377 #endif
378 }
379 
380 // Separated from STL1() because some compilers produce an overly
381 // large stack frame for the combined function.
TEST(StringViewTest,STL2)382 TEST(StringViewTest, STL2) {
383   const absl::string_view a("abcdefghijklmnopqrstuvwxyz");
384   const absl::string_view b("abc");
385   const absl::string_view c("xyz");
386   absl::string_view d("foobar");
387   const absl::string_view e;
388   const absl::string_view f(
389       "123"
390       "\0"
391       "456",
392       7);
393 
394   d = absl::string_view();
395   EXPECT_EQ(d.size(), 0);
396   EXPECT_TRUE(d.empty());
397   EXPECT_TRUE(d.data() == nullptr);
398   EXPECT_TRUE(d.begin() == d.end());
399 
400   EXPECT_EQ(a.find(b), 0);
401   EXPECT_EQ(a.find(b, 1), absl::string_view::npos);
402   EXPECT_EQ(a.find(c), 23);
403   EXPECT_EQ(a.find(c, 9), 23);
404   EXPECT_EQ(a.find(c, absl::string_view::npos), absl::string_view::npos);
405   EXPECT_EQ(b.find(c), absl::string_view::npos);
406   EXPECT_EQ(b.find(c, absl::string_view::npos), absl::string_view::npos);
407   EXPECT_EQ(a.find(d), 0);
408   EXPECT_EQ(a.find(e), 0);
409   EXPECT_EQ(a.find(d, 12), 12);
410   EXPECT_EQ(a.find(e, 17), 17);
411   absl::string_view g("xx not found bb");
412   EXPECT_EQ(a.find(g), absl::string_view::npos);
413   // empty std::string nonsense
414   EXPECT_EQ(d.find(b), absl::string_view::npos);
415   EXPECT_EQ(e.find(b), absl::string_view::npos);
416   EXPECT_EQ(d.find(b, 4), absl::string_view::npos);
417   EXPECT_EQ(e.find(b, 7), absl::string_view::npos);
418 
419   size_t empty_search_pos = std::string().find(std::string());
420   EXPECT_EQ(d.find(d), empty_search_pos);
421   EXPECT_EQ(d.find(e), empty_search_pos);
422   EXPECT_EQ(e.find(d), empty_search_pos);
423   EXPECT_EQ(e.find(e), empty_search_pos);
424   EXPECT_EQ(d.find(d, 4), std::string().find(std::string(), 4));
425   EXPECT_EQ(d.find(e, 4), std::string().find(std::string(), 4));
426   EXPECT_EQ(e.find(d, 4), std::string().find(std::string(), 4));
427   EXPECT_EQ(e.find(e, 4), std::string().find(std::string(), 4));
428 
429   EXPECT_EQ(a.find('a'), 0);
430   EXPECT_EQ(a.find('c'), 2);
431   EXPECT_EQ(a.find('z'), 25);
432   EXPECT_EQ(a.find('$'), absl::string_view::npos);
433   EXPECT_EQ(a.find('\0'), absl::string_view::npos);
434   EXPECT_EQ(f.find('\0'), 3);
435   EXPECT_EQ(f.find('3'), 2);
436   EXPECT_EQ(f.find('5'), 5);
437   EXPECT_EQ(g.find('o'), 4);
438   EXPECT_EQ(g.find('o', 4), 4);
439   EXPECT_EQ(g.find('o', 5), 8);
440   EXPECT_EQ(a.find('b', 5), absl::string_view::npos);
441   // empty std::string nonsense
442   EXPECT_EQ(d.find('\0'), absl::string_view::npos);
443   EXPECT_EQ(e.find('\0'), absl::string_view::npos);
444   EXPECT_EQ(d.find('\0', 4), absl::string_view::npos);
445   EXPECT_EQ(e.find('\0', 7), absl::string_view::npos);
446   EXPECT_EQ(d.find('x'), absl::string_view::npos);
447   EXPECT_EQ(e.find('x'), absl::string_view::npos);
448   EXPECT_EQ(d.find('x', 4), absl::string_view::npos);
449   EXPECT_EQ(e.find('x', 7), absl::string_view::npos);
450 
451   EXPECT_EQ(a.rfind(b), 0);
452   EXPECT_EQ(a.rfind(b, 1), 0);
453   EXPECT_EQ(a.rfind(c), 23);
454   EXPECT_EQ(a.rfind(c, 22), absl::string_view::npos);
455   EXPECT_EQ(a.rfind(c, 1), absl::string_view::npos);
456   EXPECT_EQ(a.rfind(c, 0), absl::string_view::npos);
457   EXPECT_EQ(b.rfind(c), absl::string_view::npos);
458   EXPECT_EQ(b.rfind(c, 0), absl::string_view::npos);
459   EXPECT_EQ(a.rfind(d), std::string(a).rfind(std::string()));
460   EXPECT_EQ(a.rfind(e), std::string(a).rfind(std::string()));
461   EXPECT_EQ(a.rfind(d, 12), 12);
462   EXPECT_EQ(a.rfind(e, 17), 17);
463   EXPECT_EQ(a.rfind(g), absl::string_view::npos);
464   EXPECT_EQ(d.rfind(b), absl::string_view::npos);
465   EXPECT_EQ(e.rfind(b), absl::string_view::npos);
466   EXPECT_EQ(d.rfind(b, 4), absl::string_view::npos);
467   EXPECT_EQ(e.rfind(b, 7), absl::string_view::npos);
468   // empty std::string nonsense
469   EXPECT_EQ(d.rfind(d, 4), std::string().rfind(std::string()));
470   EXPECT_EQ(e.rfind(d, 7), std::string().rfind(std::string()));
471   EXPECT_EQ(d.rfind(e, 4), std::string().rfind(std::string()));
472   EXPECT_EQ(e.rfind(e, 7), std::string().rfind(std::string()));
473   EXPECT_EQ(d.rfind(d), std::string().rfind(std::string()));
474   EXPECT_EQ(e.rfind(d), std::string().rfind(std::string()));
475   EXPECT_EQ(d.rfind(e), std::string().rfind(std::string()));
476   EXPECT_EQ(e.rfind(e), std::string().rfind(std::string()));
477 
478   EXPECT_EQ(g.rfind('o'), 8);
479   EXPECT_EQ(g.rfind('q'), absl::string_view::npos);
480   EXPECT_EQ(g.rfind('o', 8), 8);
481   EXPECT_EQ(g.rfind('o', 7), 4);
482   EXPECT_EQ(g.rfind('o', 3), absl::string_view::npos);
483   EXPECT_EQ(f.rfind('\0'), 3);
484   EXPECT_EQ(f.rfind('\0', 12), 3);
485   EXPECT_EQ(f.rfind('3'), 2);
486   EXPECT_EQ(f.rfind('5'), 5);
487   // empty std::string nonsense
488   EXPECT_EQ(d.rfind('o'), absl::string_view::npos);
489   EXPECT_EQ(e.rfind('o'), absl::string_view::npos);
490   EXPECT_EQ(d.rfind('o', 4), absl::string_view::npos);
491   EXPECT_EQ(e.rfind('o', 7), absl::string_view::npos);
492 }
493 
494 // Continued from STL2
TEST(StringViewTest,STL2FindFirst)495 TEST(StringViewTest, STL2FindFirst) {
496   const absl::string_view a("abcdefghijklmnopqrstuvwxyz");
497   const absl::string_view b("abc");
498   const absl::string_view c("xyz");
499   absl::string_view d("foobar");
500   const absl::string_view e;
501   const absl::string_view f(
502       "123"
503       "\0"
504       "456",
505       7);
506   absl::string_view g("xx not found bb");
507 
508   d = absl::string_view();
509   EXPECT_EQ(a.find_first_of(b), 0);
510   EXPECT_EQ(a.find_first_of(b, 0), 0);
511   EXPECT_EQ(a.find_first_of(b, 1), 1);
512   EXPECT_EQ(a.find_first_of(b, 2), 2);
513   EXPECT_EQ(a.find_first_of(b, 3), absl::string_view::npos);
514   EXPECT_EQ(a.find_first_of(c), 23);
515   EXPECT_EQ(a.find_first_of(c, 23), 23);
516   EXPECT_EQ(a.find_first_of(c, 24), 24);
517   EXPECT_EQ(a.find_first_of(c, 25), 25);
518   EXPECT_EQ(a.find_first_of(c, 26), absl::string_view::npos);
519   EXPECT_EQ(g.find_first_of(b), 13);
520   EXPECT_EQ(g.find_first_of(c), 0);
521   EXPECT_EQ(a.find_first_of(f), absl::string_view::npos);
522   EXPECT_EQ(f.find_first_of(a), absl::string_view::npos);
523   // empty std::string nonsense
524   EXPECT_EQ(a.find_first_of(d), absl::string_view::npos);
525   EXPECT_EQ(a.find_first_of(e), absl::string_view::npos);
526   EXPECT_EQ(d.find_first_of(b), absl::string_view::npos);
527   EXPECT_EQ(e.find_first_of(b), absl::string_view::npos);
528   EXPECT_EQ(d.find_first_of(d), absl::string_view::npos);
529   EXPECT_EQ(e.find_first_of(d), absl::string_view::npos);
530   EXPECT_EQ(d.find_first_of(e), absl::string_view::npos);
531   EXPECT_EQ(e.find_first_of(e), absl::string_view::npos);
532 
533   EXPECT_EQ(a.find_first_not_of(b), 3);
534   EXPECT_EQ(a.find_first_not_of(c), 0);
535   EXPECT_EQ(b.find_first_not_of(a), absl::string_view::npos);
536   EXPECT_EQ(c.find_first_not_of(a), absl::string_view::npos);
537   EXPECT_EQ(f.find_first_not_of(a), 0);
538   EXPECT_EQ(a.find_first_not_of(f), 0);
539   EXPECT_EQ(a.find_first_not_of(d), 0);
540   EXPECT_EQ(a.find_first_not_of(e), 0);
541   // empty std::string nonsense
542   EXPECT_EQ(a.find_first_not_of(d), 0);
543   EXPECT_EQ(a.find_first_not_of(e), 0);
544   EXPECT_EQ(a.find_first_not_of(d, 1), 1);
545   EXPECT_EQ(a.find_first_not_of(e, 1), 1);
546   EXPECT_EQ(a.find_first_not_of(d, a.size() - 1), a.size() - 1);
547   EXPECT_EQ(a.find_first_not_of(e, a.size() - 1), a.size() - 1);
548   EXPECT_EQ(a.find_first_not_of(d, a.size()), absl::string_view::npos);
549   EXPECT_EQ(a.find_first_not_of(e, a.size()), absl::string_view::npos);
550   EXPECT_EQ(a.find_first_not_of(d, absl::string_view::npos),
551             absl::string_view::npos);
552   EXPECT_EQ(a.find_first_not_of(e, absl::string_view::npos),
553             absl::string_view::npos);
554   EXPECT_EQ(d.find_first_not_of(a), absl::string_view::npos);
555   EXPECT_EQ(e.find_first_not_of(a), absl::string_view::npos);
556   EXPECT_EQ(d.find_first_not_of(d), absl::string_view::npos);
557   EXPECT_EQ(e.find_first_not_of(d), absl::string_view::npos);
558   EXPECT_EQ(d.find_first_not_of(e), absl::string_view::npos);
559   EXPECT_EQ(e.find_first_not_of(e), absl::string_view::npos);
560 
561   absl::string_view h("====");
562   EXPECT_EQ(h.find_first_not_of('='), absl::string_view::npos);
563   EXPECT_EQ(h.find_first_not_of('=', 3), absl::string_view::npos);
564   EXPECT_EQ(h.find_first_not_of('\0'), 0);
565   EXPECT_EQ(g.find_first_not_of('x'), 2);
566   EXPECT_EQ(f.find_first_not_of('\0'), 0);
567   EXPECT_EQ(f.find_first_not_of('\0', 3), 4);
568   EXPECT_EQ(f.find_first_not_of('\0', 2), 2);
569   // empty std::string nonsense
570   EXPECT_EQ(d.find_first_not_of('x'), absl::string_view::npos);
571   EXPECT_EQ(e.find_first_not_of('x'), absl::string_view::npos);
572   EXPECT_EQ(d.find_first_not_of('\0'), absl::string_view::npos);
573   EXPECT_EQ(e.find_first_not_of('\0'), absl::string_view::npos);
574 }
575 
576 // Continued from STL2
TEST(StringViewTest,STL2FindLast)577 TEST(StringViewTest, STL2FindLast) {
578   const absl::string_view a("abcdefghijklmnopqrstuvwxyz");
579   const absl::string_view b("abc");
580   const absl::string_view c("xyz");
581   absl::string_view d("foobar");
582   const absl::string_view e;
583   const absl::string_view f(
584       "123"
585       "\0"
586       "456",
587       7);
588   absl::string_view g("xx not found bb");
589   absl::string_view h("====");
590   absl::string_view i("56");
591 
592   d = absl::string_view();
593   EXPECT_EQ(h.find_last_of(a), absl::string_view::npos);
594   EXPECT_EQ(g.find_last_of(a), g.size()-1);
595   EXPECT_EQ(a.find_last_of(b), 2);
596   EXPECT_EQ(a.find_last_of(c), a.size()-1);
597   EXPECT_EQ(f.find_last_of(i), 6);
598   EXPECT_EQ(a.find_last_of('a'), 0);
599   EXPECT_EQ(a.find_last_of('b'), 1);
600   EXPECT_EQ(a.find_last_of('z'), 25);
601   EXPECT_EQ(a.find_last_of('a', 5), 0);
602   EXPECT_EQ(a.find_last_of('b', 5), 1);
603   EXPECT_EQ(a.find_last_of('b', 0), absl::string_view::npos);
604   EXPECT_EQ(a.find_last_of('z', 25), 25);
605   EXPECT_EQ(a.find_last_of('z', 24), absl::string_view::npos);
606   EXPECT_EQ(f.find_last_of(i, 5), 5);
607   EXPECT_EQ(f.find_last_of(i, 6), 6);
608   EXPECT_EQ(f.find_last_of(a, 4), absl::string_view::npos);
609   // empty std::string nonsense
610   EXPECT_EQ(f.find_last_of(d), absl::string_view::npos);
611   EXPECT_EQ(f.find_last_of(e), absl::string_view::npos);
612   EXPECT_EQ(f.find_last_of(d, 4), absl::string_view::npos);
613   EXPECT_EQ(f.find_last_of(e, 4), absl::string_view::npos);
614   EXPECT_EQ(d.find_last_of(d), absl::string_view::npos);
615   EXPECT_EQ(d.find_last_of(e), absl::string_view::npos);
616   EXPECT_EQ(e.find_last_of(d), absl::string_view::npos);
617   EXPECT_EQ(e.find_last_of(e), absl::string_view::npos);
618   EXPECT_EQ(d.find_last_of(f), absl::string_view::npos);
619   EXPECT_EQ(e.find_last_of(f), absl::string_view::npos);
620   EXPECT_EQ(d.find_last_of(d, 4), absl::string_view::npos);
621   EXPECT_EQ(d.find_last_of(e, 4), absl::string_view::npos);
622   EXPECT_EQ(e.find_last_of(d, 4), absl::string_view::npos);
623   EXPECT_EQ(e.find_last_of(e, 4), absl::string_view::npos);
624   EXPECT_EQ(d.find_last_of(f, 4), absl::string_view::npos);
625   EXPECT_EQ(e.find_last_of(f, 4), absl::string_view::npos);
626 
627   EXPECT_EQ(a.find_last_not_of(b), a.size()-1);
628   EXPECT_EQ(a.find_last_not_of(c), 22);
629   EXPECT_EQ(b.find_last_not_of(a), absl::string_view::npos);
630   EXPECT_EQ(b.find_last_not_of(b), absl::string_view::npos);
631   EXPECT_EQ(f.find_last_not_of(i), 4);
632   EXPECT_EQ(a.find_last_not_of(c, 24), 22);
633   EXPECT_EQ(a.find_last_not_of(b, 3), 3);
634   EXPECT_EQ(a.find_last_not_of(b, 2), absl::string_view::npos);
635   // empty std::string nonsense
636   EXPECT_EQ(f.find_last_not_of(d), f.size()-1);
637   EXPECT_EQ(f.find_last_not_of(e), f.size()-1);
638   EXPECT_EQ(f.find_last_not_of(d, 4), 4);
639   EXPECT_EQ(f.find_last_not_of(e, 4), 4);
640   EXPECT_EQ(d.find_last_not_of(d), absl::string_view::npos);
641   EXPECT_EQ(d.find_last_not_of(e), absl::string_view::npos);
642   EXPECT_EQ(e.find_last_not_of(d), absl::string_view::npos);
643   EXPECT_EQ(e.find_last_not_of(e), absl::string_view::npos);
644   EXPECT_EQ(d.find_last_not_of(f), absl::string_view::npos);
645   EXPECT_EQ(e.find_last_not_of(f), absl::string_view::npos);
646   EXPECT_EQ(d.find_last_not_of(d, 4), absl::string_view::npos);
647   EXPECT_EQ(d.find_last_not_of(e, 4), absl::string_view::npos);
648   EXPECT_EQ(e.find_last_not_of(d, 4), absl::string_view::npos);
649   EXPECT_EQ(e.find_last_not_of(e, 4), absl::string_view::npos);
650   EXPECT_EQ(d.find_last_not_of(f, 4), absl::string_view::npos);
651   EXPECT_EQ(e.find_last_not_of(f, 4), absl::string_view::npos);
652 
653   EXPECT_EQ(h.find_last_not_of('x'), h.size() - 1);
654   EXPECT_EQ(h.find_last_not_of('='), absl::string_view::npos);
655   EXPECT_EQ(b.find_last_not_of('c'), 1);
656   EXPECT_EQ(h.find_last_not_of('x', 2), 2);
657   EXPECT_EQ(h.find_last_not_of('=', 2), absl::string_view::npos);
658   EXPECT_EQ(b.find_last_not_of('b', 1), 0);
659   // empty std::string nonsense
660   EXPECT_EQ(d.find_last_not_of('x'), absl::string_view::npos);
661   EXPECT_EQ(e.find_last_not_of('x'), absl::string_view::npos);
662   EXPECT_EQ(d.find_last_not_of('\0'), absl::string_view::npos);
663   EXPECT_EQ(e.find_last_not_of('\0'), absl::string_view::npos);
664 }
665 
666 // Continued from STL2
TEST(StringViewTest,STL2Substr)667 TEST(StringViewTest, STL2Substr) {
668   const absl::string_view a("abcdefghijklmnopqrstuvwxyz");
669   const absl::string_view b("abc");
670   const absl::string_view c("xyz");
671   absl::string_view d("foobar");
672   const absl::string_view e;
673 
674   d = absl::string_view();
675   EXPECT_EQ(a.substr(0, 3), b);
676   EXPECT_EQ(a.substr(23), c);
677   EXPECT_EQ(a.substr(23, 3), c);
678   EXPECT_EQ(a.substr(23, 99), c);
679   EXPECT_EQ(a.substr(0), a);
680   EXPECT_EQ(a.substr(3, 2), "de");
681   // empty std::string nonsense
682   EXPECT_EQ(d.substr(0, 99), e);
683   // use of npos
684   EXPECT_EQ(a.substr(0, absl::string_view::npos), a);
685   EXPECT_EQ(a.substr(23, absl::string_view::npos), c);
686   // throw exception
687 #ifdef ABSL_HAVE_EXCEPTIONS
688   EXPECT_THROW((void)a.substr(99, 2), std::out_of_range);
689 #else
690   ABSL_EXPECT_DEATH_IF_SUPPORTED((void)a.substr(99, 2),
691                                  "absl::string_view::substr");
692 #endif
693 }
694 
TEST(StringViewTest,TruncSubstr)695 TEST(StringViewTest, TruncSubstr) {
696   const absl::string_view hi("hi");
697   EXPECT_EQ("", absl::ClippedSubstr(hi, 0, 0));
698   EXPECT_EQ("h", absl::ClippedSubstr(hi, 0, 1));
699   EXPECT_EQ("hi", absl::ClippedSubstr(hi, 0));
700   EXPECT_EQ("i", absl::ClippedSubstr(hi, 1));
701   EXPECT_EQ("", absl::ClippedSubstr(hi, 2));
702   EXPECT_EQ("", absl::ClippedSubstr(hi, 3));  // truncation
703   EXPECT_EQ("", absl::ClippedSubstr(hi, 3, 2));  // truncation
704 }
705 
TEST(StringViewTest,UTF8)706 TEST(StringViewTest, UTF8) {
707   std::string utf8 = "\u00E1";
708   std::string utf8_twice = utf8 + " " + utf8;
709   int utf8_len = strlen(utf8.data());
710   EXPECT_EQ(utf8_len, absl::string_view(utf8_twice).find_first_of(" "));
711   EXPECT_EQ(utf8_len, absl::string_view(utf8_twice).find_first_of(" \t"));
712 }
713 
TEST(StringViewTest,FindConformance)714 TEST(StringViewTest, FindConformance) {
715   struct {
716     std::string haystack;
717     std::string needle;
718   } specs[] = {
719     {"", ""},
720     {"", "a"},
721     {"a", ""},
722     {"a", "a"},
723     {"a", "b"},
724     {"aa", ""},
725     {"aa", "a"},
726     {"aa", "b"},
727     {"ab", "a"},
728     {"ab", "b"},
729     {"abcd", ""},
730     {"abcd", "a"},
731     {"abcd", "d"},
732     {"abcd", "ab"},
733     {"abcd", "bc"},
734     {"abcd", "cd"},
735     {"abcd", "abcd"},
736   };
737   for (const auto& s : specs) {
738     SCOPED_TRACE(s.haystack);
739     SCOPED_TRACE(s.needle);
740     std::string st = s.haystack;
741     absl::string_view sp = s.haystack;
742     for (size_t i = 0; i <= sp.size(); ++i) {
743       size_t pos = (i == sp.size()) ? absl::string_view::npos : i;
744       SCOPED_TRACE(pos);
745       EXPECT_EQ(sp.find(s.needle, pos),
746                 st.find(s.needle, pos));
747       EXPECT_EQ(sp.rfind(s.needle, pos),
748                 st.rfind(s.needle, pos));
749       EXPECT_EQ(sp.find_first_of(s.needle, pos),
750                 st.find_first_of(s.needle, pos));
751       EXPECT_EQ(sp.find_first_not_of(s.needle, pos),
752                 st.find_first_not_of(s.needle, pos));
753       EXPECT_EQ(sp.find_last_of(s.needle, pos),
754                 st.find_last_of(s.needle, pos));
755       EXPECT_EQ(sp.find_last_not_of(s.needle, pos),
756                 st.find_last_not_of(s.needle, pos));
757     }
758   }
759 }
760 
TEST(StringViewTest,Remove)761 TEST(StringViewTest, Remove) {
762   absl::string_view a("foobar");
763   std::string s1("123");
764   s1 += '\0';
765   s1 += "456";
766   absl::string_view e;
767   std::string s2;
768 
769   // remove_prefix
770   absl::string_view c(a);
771   c.remove_prefix(3);
772   EXPECT_EQ(c, "bar");
773   c = a;
774   c.remove_prefix(0);
775   EXPECT_EQ(c, a);
776   c.remove_prefix(c.size());
777   EXPECT_EQ(c, e);
778 
779   // remove_suffix
780   c = a;
781   c.remove_suffix(3);
782   EXPECT_EQ(c, "foo");
783   c = a;
784   c.remove_suffix(0);
785   EXPECT_EQ(c, a);
786   c.remove_suffix(c.size());
787   EXPECT_EQ(c, e);
788 }
789 
TEST(StringViewTest,Set)790 TEST(StringViewTest, Set) {
791   absl::string_view a("foobar");
792   absl::string_view empty;
793   absl::string_view b;
794 
795   // set
796   b = absl::string_view("foobar", 6);
797   EXPECT_EQ(b, a);
798   b = absl::string_view("foobar", 0);
799   EXPECT_EQ(b, empty);
800   b = absl::string_view("foobar", 7);
801   EXPECT_NE(b, a);
802 
803   b = absl::string_view("foobar");
804   EXPECT_EQ(b, a);
805 }
806 
TEST(StringViewTest,FrontBack)807 TEST(StringViewTest, FrontBack) {
808   static const char arr[] = "abcd";
809   const absl::string_view csp(arr, 4);
810   EXPECT_EQ(&arr[0], &csp.front());
811   EXPECT_EQ(&arr[3], &csp.back());
812 }
813 
TEST(StringViewTest,FrontBackSingleChar)814 TEST(StringViewTest, FrontBackSingleChar) {
815   static const char c = 'a';
816   const absl::string_view csp(&c, 1);
817   EXPECT_EQ(&c, &csp.front());
818   EXPECT_EQ(&c, &csp.back());
819 }
820 
TEST(StringViewTest,FrontBackEmpty)821 TEST(StringViewTest, FrontBackEmpty) {
822 #ifndef ABSL_USES_STD_STRING_VIEW
823 #ifndef NDEBUG
824   // Abseil's string_view implementation has debug assertions that check that
825   // front() and back() are not called on an empty string_view.
826   absl::string_view sv;
827   ABSL_EXPECT_DEATH_IF_SUPPORTED(sv.front(), "");
828   ABSL_EXPECT_DEATH_IF_SUPPORTED(sv.back(), "");
829 #endif
830 #endif
831 }
832 
833 // `std::string_view::string_view(const char*)` calls
834 // `std::char_traits<char>::length(const char*)` to get the string length. In
835 // libc++, it doesn't allow `nullptr` in the constexpr context, with the error
836 // "read of dereferenced null pointer is not allowed in a constant expression".
837 // At run time, the behavior of `std::char_traits::length()` on `nullptr` is
838 // undefined by the standard and usually results in crash with libc++.
839 // GCC also started rejected this in libstdc++ starting in GCC9.
840 // In MSVC, creating a constexpr string_view from nullptr also triggers an
841 // "unevaluable pointer value" error. This compiler implementation conforms
842 // to the standard, but `absl::string_view` implements a different
843 // behavior for historical reasons. We work around tests that construct
844 // `string_view` from `nullptr` when using libc++.
845 #if !defined(ABSL_USES_STD_STRING_VIEW) ||                    \
846     (!(defined(_GLIBCXX_RELEASE) && _GLIBCXX_RELEASE >= 9) && \
847      !defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
848 #define ABSL_HAVE_STRING_VIEW_FROM_NULLPTR 1
849 #endif
850 
TEST(StringViewTest,NULLInput)851 TEST(StringViewTest, NULLInput) {
852   absl::string_view s;
853   EXPECT_EQ(s.data(), nullptr);
854   EXPECT_EQ(s.size(), 0);
855 
856 #ifdef ABSL_HAVE_STRING_VIEW_FROM_NULLPTR
857   s = absl::string_view(nullptr);
858   EXPECT_EQ(s.data(), nullptr);
859   EXPECT_EQ(s.size(), 0);
860 
861   // .ToString() on a absl::string_view with nullptr should produce the empty
862   // std::string.
863   EXPECT_EQ("", std::string(s));
864 #endif  // ABSL_HAVE_STRING_VIEW_FROM_NULLPTR
865 }
866 
TEST(StringViewTest,Comparisons2)867 TEST(StringViewTest, Comparisons2) {
868   // The `compare` member has 6 overloads (v: string_view, s: const char*):
869   //  (1) compare(v)
870   //  (2) compare(pos1, count1, v)
871   //  (3) compare(pos1, count1, v, pos2, count2)
872   //  (4) compare(s)
873   //  (5) compare(pos1, count1, s)
874   //  (6) compare(pos1, count1, s, count2)
875 
876   absl::string_view abc("abcdefghijklmnopqrstuvwxyz");
877 
878   // check comparison operations on strings longer than 4 bytes.
879   EXPECT_EQ(abc, absl::string_view("abcdefghijklmnopqrstuvwxyz"));
880   EXPECT_EQ(abc.compare(absl::string_view("abcdefghijklmnopqrstuvwxyz")), 0);
881 
882   EXPECT_LT(abc, absl::string_view("abcdefghijklmnopqrstuvwxzz"));
883   EXPECT_LT(abc.compare(absl::string_view("abcdefghijklmnopqrstuvwxzz")), 0);
884 
885   EXPECT_GT(abc, absl::string_view("abcdefghijklmnopqrstuvwxyy"));
886   EXPECT_GT(abc.compare(absl::string_view("abcdefghijklmnopqrstuvwxyy")), 0);
887 
888   // The "substr" variants of `compare`.
889   absl::string_view digits("0123456789");
890   auto npos = absl::string_view::npos;
891 
892   // Taking string_view
893   EXPECT_EQ(digits.compare(3, npos, absl::string_view("3456789")), 0);  // 2
894   EXPECT_EQ(digits.compare(3, 4, absl::string_view("3456")), 0);        // 2
895   EXPECT_EQ(digits.compare(10, 0, absl::string_view()), 0);             // 2
896   EXPECT_EQ(digits.compare(3, 4, absl::string_view("0123456789"), 3, 4),
897             0);  // 3
898   EXPECT_LT(digits.compare(3, 4, absl::string_view("0123456789"), 3, 5),
899             0);  // 3
900   EXPECT_LT(digits.compare(0, npos, absl::string_view("0123456789"), 3, 5),
901             0);  // 3
902   // Taking const char*
903   EXPECT_EQ(digits.compare(3, 4, "3456"), 0);                 // 5
904   EXPECT_EQ(digits.compare(3, npos, "3456789"), 0);           // 5
905   EXPECT_EQ(digits.compare(10, 0, ""), 0);                    // 5
906   EXPECT_EQ(digits.compare(3, 4, "0123456789", 3, 4), 0);     // 6
907   EXPECT_LT(digits.compare(3, 4, "0123456789", 3, 5), 0);     // 6
908   EXPECT_LT(digits.compare(0, npos, "0123456789", 3, 5), 0);  // 6
909 }
910 
TEST(StringViewTest,At)911 TEST(StringViewTest, At) {
912   absl::string_view abc = "abc";
913   EXPECT_EQ(abc.at(0), 'a');
914   EXPECT_EQ(abc.at(1), 'b');
915   EXPECT_EQ(abc.at(2), 'c');
916 #ifdef ABSL_HAVE_EXCEPTIONS
917   EXPECT_THROW(abc.at(3), std::out_of_range);
918 #else
919   ABSL_EXPECT_DEATH_IF_SUPPORTED(abc.at(3), "absl::string_view::at");
920 #endif
921 }
922 
923 struct MyCharAlloc : std::allocator<char> {};
924 
TEST(StringViewTest,ExplicitConversionOperator)925 TEST(StringViewTest, ExplicitConversionOperator) {
926   absl::string_view sp = "hi";
927   EXPECT_EQ(sp, std::string(sp));
928 }
929 
TEST(StringViewTest,NullSafeStringView)930 TEST(StringViewTest, NullSafeStringView) {
931   {
932     absl::string_view s = absl::NullSafeStringView(nullptr);
933     EXPECT_EQ(nullptr, s.data());
934     EXPECT_EQ(0, s.size());
935     EXPECT_EQ(absl::string_view(), s);
936   }
937   {
938     static const char kHi[] = "hi";
939     absl::string_view s = absl::NullSafeStringView(kHi);
940     EXPECT_EQ(kHi, s.data());
941     EXPECT_EQ(strlen(kHi), s.size());
942     EXPECT_EQ(absl::string_view("hi"), s);
943   }
944 }
945 
TEST(StringViewTest,ConstexprNullSafeStringView)946 TEST(StringViewTest, ConstexprNullSafeStringView) {
947   {
948     constexpr absl::string_view s = absl::NullSafeStringView(nullptr);
949     EXPECT_EQ(nullptr, s.data());
950     EXPECT_EQ(0, s.size());
951     EXPECT_EQ(absl::string_view(), s);
952   }
953 #if !defined(_MSC_VER) || _MSC_VER >= 1910
954   // MSVC 2017+ is required for good constexpr string_view support.
955   // See the implementation of `absl::string_view::StrlenInternal()`.
956   {
957     static constexpr char kHi[] = "hi";
958     absl::string_view s = absl::NullSafeStringView(kHi);
959     EXPECT_EQ(kHi, s.data());
960     EXPECT_EQ(strlen(kHi), s.size());
961     EXPECT_EQ(absl::string_view("hi"), s);
962   }
963   {
964     constexpr absl::string_view s = absl::NullSafeStringView("hello");
965     EXPECT_EQ(s.size(), 5);
966     EXPECT_EQ("hello", s);
967   }
968 #endif
969 }
970 
TEST(StringViewTest,ConstexprCompiles)971 TEST(StringViewTest, ConstexprCompiles) {
972   constexpr absl::string_view sp;
973 #ifdef ABSL_HAVE_STRING_VIEW_FROM_NULLPTR
974   constexpr absl::string_view cstr(nullptr);
975 #endif
976   constexpr absl::string_view cstr_len("cstr", 4);
977 
978 #if defined(ABSL_USES_STD_STRING_VIEW)
979   // In libstdc++ (as of 7.2), `std::string_view::string_view(const char*)`
980   // calls `std::char_traits<char>::length(const char*)` to get the std::string
981   // length, but it is not marked constexpr yet. See GCC bug:
982   // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78156
983   // Also, there is a LWG issue that adds constexpr to length() which was just
984   // resolved 2017-06-02. See
985   // http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#2232
986   // TODO(zhangxy): Update the condition when libstdc++ adopts the constexpr
987   // length().
988 #if !defined(__GLIBCXX__)
989 #define ABSL_HAVE_CONSTEXPR_STRING_VIEW_FROM_CSTR 1
990 #endif  // !__GLIBCXX__
991 
992 #else  // ABSL_USES_STD_STRING_VIEW
993 
994 // This duplicates the check for __builtin_strlen in the header.
995 #if ABSL_HAVE_BUILTIN(__builtin_strlen) || \
996     (defined(__GNUC__) && !defined(__clang__))
997 #define ABSL_HAVE_CONSTEXPR_STRING_VIEW_FROM_CSTR 1
998 #elif defined(__GNUC__)  // GCC or clang
999 #error GCC/clang should have constexpr string_view.
1000 #endif
1001 
1002 // MSVC 2017+ should be able to construct a constexpr string_view from a cstr.
1003 #if defined(_MSC_VER) && _MSC_VER >= 1910
1004 #define ABSL_HAVE_CONSTEXPR_STRING_VIEW_FROM_CSTR 1
1005 #endif
1006 
1007 #endif  // ABSL_USES_STD_STRING_VIEW
1008 
1009 #ifdef ABSL_HAVE_CONSTEXPR_STRING_VIEW_FROM_CSTR
1010   constexpr absl::string_view cstr_strlen("foo");
1011   EXPECT_EQ(cstr_strlen.length(), 3);
1012   constexpr absl::string_view cstr_strlen2 = "bar";
1013   EXPECT_EQ(cstr_strlen2, "bar");
1014 
1015 #if ABSL_HAVE_BUILTIN(__builtin_memcmp) || \
1016     (defined(__GNUC__) && !defined(__clang__))
1017 #define ABSL_HAVE_CONSTEXPR_STRING_VIEW_COMPARISON 1
1018 #endif
1019 #ifdef ABSL_HAVE_CONSTEXPR_STRING_VIEW_COMPARISON
1020   constexpr absl::string_view foo = "foo";
1021   constexpr absl::string_view bar = "bar";
1022   constexpr bool foo_eq_bar = foo == bar;
1023   constexpr bool foo_ne_bar = foo != bar;
1024   constexpr bool foo_lt_bar = foo < bar;
1025   constexpr bool foo_le_bar = foo <= bar;
1026   constexpr bool foo_gt_bar = foo > bar;
1027   constexpr bool foo_ge_bar = foo >= bar;
1028   constexpr int foo_compare_bar = foo.compare(bar);
1029   EXPECT_FALSE(foo_eq_bar);
1030   EXPECT_TRUE(foo_ne_bar);
1031   EXPECT_FALSE(foo_lt_bar);
1032   EXPECT_FALSE(foo_le_bar);
1033   EXPECT_TRUE(foo_gt_bar);
1034   EXPECT_TRUE(foo_ge_bar);
1035   EXPECT_GT(foo_compare_bar, 0);
1036 #endif
1037 #endif
1038 
1039 #if !defined(__clang__) || 3 < __clang_major__ || \
1040   (3 == __clang_major__ && 4 < __clang_minor__)
1041   // older clang versions (< 3.5) complain that:
1042   //   "cannot perform pointer arithmetic on null pointer"
1043   constexpr absl::string_view::iterator const_begin_empty = sp.begin();
1044   constexpr absl::string_view::iterator const_end_empty = sp.end();
1045   EXPECT_EQ(const_begin_empty, const_end_empty);
1046 
1047 #ifdef ABSL_HAVE_STRING_VIEW_FROM_NULLPTR
1048   constexpr absl::string_view::iterator const_begin_nullptr = cstr.begin();
1049   constexpr absl::string_view::iterator const_end_nullptr = cstr.end();
1050   EXPECT_EQ(const_begin_nullptr, const_end_nullptr);
1051 #endif  // ABSL_HAVE_STRING_VIEW_FROM_NULLPTR
1052 #endif  // !defined(__clang__) || ...
1053 
1054   constexpr absl::string_view::iterator const_begin = cstr_len.begin();
1055   constexpr absl::string_view::iterator const_end = cstr_len.end();
1056   constexpr absl::string_view::size_type const_size = cstr_len.size();
1057   constexpr absl::string_view::size_type const_length = cstr_len.length();
1058   static_assert(const_begin + const_size == const_end,
1059                 "pointer arithmetic check");
1060   static_assert(const_begin + const_length == const_end,
1061                 "pointer arithmetic check");
1062 #ifndef _MSC_VER
1063   // MSVC has bugs doing constexpr pointer arithmetic.
1064   // https://developercommunity.visualstudio.com/content/problem/482192/bad-pointer-arithmetic-in-constepxr-2019-rc1-svc1.html
1065   EXPECT_EQ(const_begin + const_size, const_end);
1066   EXPECT_EQ(const_begin + const_length, const_end);
1067 #endif
1068 
1069   constexpr bool isempty = sp.empty();
1070   EXPECT_TRUE(isempty);
1071 
1072   constexpr const char c = cstr_len[2];
1073   EXPECT_EQ(c, 't');
1074 
1075   constexpr const char cfront = cstr_len.front();
1076   constexpr const char cback = cstr_len.back();
1077   EXPECT_EQ(cfront, 'c');
1078   EXPECT_EQ(cback, 'r');
1079 
1080   constexpr const char* np = sp.data();
1081   constexpr const char* cstr_ptr = cstr_len.data();
1082   EXPECT_EQ(np, nullptr);
1083   EXPECT_NE(cstr_ptr, nullptr);
1084 
1085   constexpr size_t sp_npos = sp.npos;
1086   EXPECT_EQ(sp_npos, -1);
1087 }
1088 
TEST(StringViewTest,Noexcept)1089 TEST(StringViewTest, Noexcept) {
1090   EXPECT_TRUE((std::is_nothrow_constructible<absl::string_view,
1091                                              const std::string&>::value));
1092   EXPECT_TRUE((std::is_nothrow_constructible<absl::string_view,
1093                                              const std::string&>::value));
1094   EXPECT_TRUE(std::is_nothrow_constructible<absl::string_view>::value);
1095   constexpr absl::string_view sp;
1096   EXPECT_TRUE(noexcept(sp.begin()));
1097   EXPECT_TRUE(noexcept(sp.end()));
1098   EXPECT_TRUE(noexcept(sp.cbegin()));
1099   EXPECT_TRUE(noexcept(sp.cend()));
1100   EXPECT_TRUE(noexcept(sp.rbegin()));
1101   EXPECT_TRUE(noexcept(sp.rend()));
1102   EXPECT_TRUE(noexcept(sp.crbegin()));
1103   EXPECT_TRUE(noexcept(sp.crend()));
1104   EXPECT_TRUE(noexcept(sp.size()));
1105   EXPECT_TRUE(noexcept(sp.length()));
1106   EXPECT_TRUE(noexcept(sp.empty()));
1107   EXPECT_TRUE(noexcept(sp.data()));
1108   EXPECT_TRUE(noexcept(sp.compare(sp)));
1109   EXPECT_TRUE(noexcept(sp.find(sp)));
1110   EXPECT_TRUE(noexcept(sp.find('f')));
1111   EXPECT_TRUE(noexcept(sp.rfind(sp)));
1112   EXPECT_TRUE(noexcept(sp.rfind('f')));
1113   EXPECT_TRUE(noexcept(sp.find_first_of(sp)));
1114   EXPECT_TRUE(noexcept(sp.find_first_of('f')));
1115   EXPECT_TRUE(noexcept(sp.find_last_of(sp)));
1116   EXPECT_TRUE(noexcept(sp.find_last_of('f')));
1117   EXPECT_TRUE(noexcept(sp.find_first_not_of(sp)));
1118   EXPECT_TRUE(noexcept(sp.find_first_not_of('f')));
1119   EXPECT_TRUE(noexcept(sp.find_last_not_of(sp)));
1120   EXPECT_TRUE(noexcept(sp.find_last_not_of('f')));
1121 }
1122 
TEST(StringViewTest,BoundsCheck)1123 TEST(StringViewTest, BoundsCheck) {
1124 #ifndef ABSL_USES_STD_STRING_VIEW
1125 #ifndef NDEBUG
1126   // Abseil's string_view implementation has bounds-checking in debug mode.
1127   absl::string_view h = "hello";
1128   ABSL_EXPECT_DEATH_IF_SUPPORTED(h[5], "");
1129   ABSL_EXPECT_DEATH_IF_SUPPORTED(h[-1], "");
1130 #endif
1131 #endif
1132 }
1133 
TEST(ComparisonOpsTest,StringCompareNotAmbiguous)1134 TEST(ComparisonOpsTest, StringCompareNotAmbiguous) {
1135   EXPECT_EQ("hello", std::string("hello"));
1136   EXPECT_LT("hello", std::string("world"));
1137 }
1138 
TEST(ComparisonOpsTest,HeterogenousStringViewEquals)1139 TEST(ComparisonOpsTest, HeterogenousStringViewEquals) {
1140   EXPECT_EQ(absl::string_view("hello"), std::string("hello"));
1141   EXPECT_EQ("hello", absl::string_view("hello"));
1142 }
1143 
TEST(FindOneCharTest,EdgeCases)1144 TEST(FindOneCharTest, EdgeCases) {
1145   absl::string_view a("xxyyyxx");
1146 
1147   // Set a = "xyyyx".
1148   a.remove_prefix(1);
1149   a.remove_suffix(1);
1150 
1151   EXPECT_EQ(0, a.find('x'));
1152   EXPECT_EQ(0, a.find('x', 0));
1153   EXPECT_EQ(4, a.find('x', 1));
1154   EXPECT_EQ(4, a.find('x', 4));
1155   EXPECT_EQ(absl::string_view::npos, a.find('x', 5));
1156 
1157   EXPECT_EQ(4, a.rfind('x'));
1158   EXPECT_EQ(4, a.rfind('x', 5));
1159   EXPECT_EQ(4, a.rfind('x', 4));
1160   EXPECT_EQ(0, a.rfind('x', 3));
1161   EXPECT_EQ(0, a.rfind('x', 0));
1162 
1163   // Set a = "yyy".
1164   a.remove_prefix(1);
1165   a.remove_suffix(1);
1166 
1167   EXPECT_EQ(absl::string_view::npos, a.find('x'));
1168   EXPECT_EQ(absl::string_view::npos, a.rfind('x'));
1169 }
1170 
1171 #ifndef THREAD_SANITIZER  // Allocates too much memory for tsan.
TEST(HugeStringView,TwoPointTwoGB)1172 TEST(HugeStringView, TwoPointTwoGB) {
1173   if (sizeof(size_t) <= 4 || RunningOnValgrind())
1174     return;
1175   // Try a huge std::string piece.
1176   const size_t size = size_t{2200} * 1000 * 1000;
1177   std::string s(size, 'a');
1178   absl::string_view sp(s);
1179   EXPECT_EQ(size, sp.length());
1180   sp.remove_prefix(1);
1181   EXPECT_EQ(size - 1, sp.length());
1182   sp.remove_suffix(2);
1183   EXPECT_EQ(size - 1 - 2, sp.length());
1184 }
1185 #endif  // THREAD_SANITIZER
1186 
1187 #if !defined(NDEBUG) && !defined(ABSL_USES_STD_STRING_VIEW)
TEST(NonNegativeLenTest,NonNegativeLen)1188 TEST(NonNegativeLenTest, NonNegativeLen) {
1189   ABSL_EXPECT_DEATH_IF_SUPPORTED(absl::string_view("xyz", -1),
1190                                  "len <= kMaxSize");
1191 }
1192 
TEST(LenExceedsMaxSizeTest,LenExceedsMaxSize)1193 TEST(LenExceedsMaxSizeTest, LenExceedsMaxSize) {
1194   auto max_size = absl::string_view().max_size();
1195 
1196   // This should construct ok (although the view itself is obviously invalid).
1197   absl::string_view ok_view("", max_size);
1198 
1199   // Adding one to the max should trigger an assertion.
1200   ABSL_EXPECT_DEATH_IF_SUPPORTED(absl::string_view("", max_size + 1),
1201                                  "len <= kMaxSize");
1202 }
1203 #endif  // !defined(NDEBUG) && !defined(ABSL_USES_STD_STRING_VIEW)
1204 
1205 class StringViewStreamTest : public ::testing::Test {
1206  public:
1207   // Set negative 'width' for right justification.
1208   template <typename T>
Pad(const T & s,int width,char fill=0)1209   std::string Pad(const T& s, int width, char fill = 0) {
1210     std::ostringstream oss;
1211     if (fill != 0) {
1212       oss << std::setfill(fill);
1213     }
1214     if (width < 0) {
1215       width = -width;
1216       oss << std::right;
1217     }
1218     oss << std::setw(width) << s;
1219     return oss.str();
1220   }
1221 };
1222 
TEST_F(StringViewStreamTest,Padding)1223 TEST_F(StringViewStreamTest, Padding) {
1224   std::string s("hello");
1225   absl::string_view sp(s);
1226   for (int w = -64; w < 64; ++w) {
1227     SCOPED_TRACE(w);
1228     EXPECT_EQ(Pad(s, w), Pad(sp, w));
1229   }
1230   for (int w = -64; w < 64; ++w) {
1231     SCOPED_TRACE(w);
1232     EXPECT_EQ(Pad(s, w, '#'), Pad(sp, w, '#'));
1233   }
1234 }
1235 
TEST_F(StringViewStreamTest,ResetsWidth)1236 TEST_F(StringViewStreamTest, ResetsWidth) {
1237   // Width should reset after one formatted write.
1238   // If we weren't resetting width after formatting the string_view,
1239   // we'd have width=5 carrying over to the printing of the "]",
1240   // creating "[###hi####]".
1241   std::string s = "hi";
1242   absl::string_view sp = s;
1243   {
1244     std::ostringstream oss;
1245     oss << "[" << std::setfill('#') << std::setw(5) << s << "]";
1246     ASSERT_EQ("[###hi]", oss.str());
1247   }
1248   {
1249     std::ostringstream oss;
1250     oss << "[" << std::setfill('#') << std::setw(5) << sp << "]";
1251     EXPECT_EQ("[###hi]", oss.str());
1252   }
1253 }
1254 
1255 }  // namespace
1256