Apply clang-format to folly/**/*Range*.*
[folly.git] / folly / test / RangeTest.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
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  *   http://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 // @author Kristina Holst (kholst@fb.com)
18 // @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
19
20 #include <folly/Range.h>
21
22 #include <array>
23 #include <iterator>
24 #include <limits>
25 #include <random>
26 #include <string>
27 #include <type_traits>
28 #include <vector>
29
30 #include <boost/algorithm/string/trim.hpp>
31 #include <boost/range/concepts.hpp>
32
33 #include <folly/portability/GTest.h>
34 #include <folly/portability/Memory.h>
35 #include <folly/portability/SysMman.h>
36
37 using namespace folly;
38 using namespace folly::detail;
39 using namespace std;
40
41 static_assert(std::is_literal_type<StringPiece>::value, "");
42
43 BOOST_CONCEPT_ASSERT((boost::RandomAccessRangeConcept<StringPiece>));
44
45 TEST(StringPiece, All) {
46   const char* foo = "foo";
47   const char* foo2 = "foo";
48   string fooStr(foo);
49   string foo2Str(foo2);
50
51   // we expect the compiler to optimize things so that there's only one copy
52   // of the string literal "foo", even though we've got it in multiple places
53   EXPECT_EQ(foo, foo2); // remember, this uses ==, not strcmp, so it's a ptr
54                         // comparison rather than lexical
55
56   // the string object creates copies though, so the c_str of these should be
57   // distinct
58   EXPECT_NE(fooStr.c_str(), foo2Str.c_str());
59
60   // test the basic StringPiece functionality
61   StringPiece s(foo);
62   EXPECT_EQ(s.size(), 3);
63
64   EXPECT_EQ(s.start(), foo); // ptr comparison
65   EXPECT_NE(s.start(), fooStr.c_str()); // ptr comparison
66   EXPECT_NE(s.start(), foo2Str.c_str()); // ptr comparison
67
68   EXPECT_EQ(s.toString(), foo); // lexical comparison
69   EXPECT_EQ(s.toString(), fooStr.c_str()); // lexical comparison
70   EXPECT_EQ(s.toString(), foo2Str.c_str()); // lexical comparison
71
72   EXPECT_EQ(s, foo); // lexical comparison
73   EXPECT_EQ(s, fooStr); // lexical comparison
74   EXPECT_EQ(s, foo2Str); // lexical comparison
75   EXPECT_EQ(foo, s);
76
77   // check using StringPiece to reference substrings
78   const char* foobarbaz = "foobarbaz";
79
80   // the full "foobarbaz"
81   s.reset(foobarbaz, strlen(foobarbaz));
82   EXPECT_EQ(s.size(), 9);
83   EXPECT_EQ(s.start(), foobarbaz);
84   EXPECT_EQ(s, "foobarbaz");
85
86   // only the 'foo'
87   s.assign(foobarbaz, foobarbaz + 3);
88   EXPECT_EQ(s.size(), 3);
89   EXPECT_EQ(s.start(), foobarbaz);
90   EXPECT_EQ(s, "foo");
91
92   // find
93   s.reset(foobarbaz, strlen(foobarbaz));
94   EXPECT_EQ(s.find("bar"), 3);
95   EXPECT_EQ(s.find("ba", 3), 3);
96   EXPECT_EQ(s.find("ba", 4), 6);
97   EXPECT_EQ(s.find("notfound"), StringPiece::npos);
98   EXPECT_EQ(s.find("notfound", 1), StringPiece::npos);
99   EXPECT_EQ(s.find("bar", 4), StringPiece::npos); // starting position too far
100   // starting pos that is obviously past the end -- This works for std::string
101   EXPECT_EQ(s.toString().find("notfound", 55), StringPiece::npos);
102   EXPECT_EQ(s.find("z", s.size()), StringPiece::npos);
103   EXPECT_EQ(s.find("z", 55), StringPiece::npos);
104   // empty needle
105   EXPECT_EQ(s.find(""), std::string().find(""));
106   EXPECT_EQ(s.find(""), 0);
107
108   // single char finds
109   EXPECT_EQ(s.find('b'), 3);
110   EXPECT_EQ(s.find('b', 3), 3);
111   EXPECT_EQ(s.find('b', 4), 6);
112   EXPECT_EQ(s.find('o', 2), 2);
113   EXPECT_EQ(s.find('y'), StringPiece::npos);
114   EXPECT_EQ(s.find('y', 1), StringPiece::npos);
115   EXPECT_EQ(s.find('o', 4), StringPiece::npos); // starting position too far
116   EXPECT_TRUE(s.contains('z'));
117   // starting pos that is obviously past the end -- This works for std::string
118   EXPECT_EQ(s.toString().find('y', 55), StringPiece::npos);
119   EXPECT_EQ(s.find('z', s.size()), StringPiece::npos);
120   EXPECT_EQ(s.find('z', 55), StringPiece::npos);
121   // null char
122   EXPECT_EQ(s.find('\0'), std::string().find('\0'));
123   EXPECT_EQ(s.find('\0'), StringPiece::npos);
124   EXPECT_FALSE(s.contains('\0'));
125
126   // single char rfinds
127   EXPECT_EQ(s.rfind('b'), 6);
128   EXPECT_EQ(s.rfind('y'), StringPiece::npos);
129   EXPECT_EQ(s.str().rfind('y'), StringPiece::npos);
130   EXPECT_EQ(ByteRange(s).rfind('b'), 6);
131   EXPECT_EQ(ByteRange(s).rfind('y'), StringPiece::npos);
132   // null char
133   EXPECT_EQ(s.rfind('\0'), s.str().rfind('\0'));
134   EXPECT_EQ(s.rfind('\0'), StringPiece::npos);
135
136   // find_first_of
137   s.reset(foobarbaz, strlen(foobarbaz));
138   EXPECT_EQ(s.find_first_of("bar"), 3);
139   EXPECT_EQ(s.find_first_of("ba", 3), 3);
140   EXPECT_EQ(s.find_first_of("ba", 4), 4);
141   EXPECT_TRUE(s.contains("bar"));
142   EXPECT_EQ(s.find_first_of("xyxy"), StringPiece::npos);
143   EXPECT_EQ(s.find_first_of("xyxy", 1), StringPiece::npos);
144   EXPECT_FALSE(s.contains("xyxy"));
145   // starting position too far
146   EXPECT_EQ(s.find_first_of("foo", 4), StringPiece::npos);
147   // starting pos that is obviously past the end -- This works for std::string
148   EXPECT_EQ(s.toString().find_first_of("xyxy", 55), StringPiece::npos);
149   EXPECT_EQ(s.find_first_of("z", s.size()), StringPiece::npos);
150   EXPECT_EQ(s.find_first_of("z", 55), StringPiece::npos);
151   // empty needle. Note that this returns npos, while find() returns 0!
152   EXPECT_EQ(s.find_first_of(""), std::string().find_first_of(""));
153   EXPECT_EQ(s.find_first_of(""), StringPiece::npos);
154
155   // single char find_first_ofs
156   EXPECT_EQ(s.find_first_of('b'), 3);
157   EXPECT_EQ(s.find_first_of('b', 3), 3);
158   EXPECT_EQ(s.find_first_of('b', 4), 6);
159   EXPECT_EQ(s.find_first_of('o', 2), 2);
160   EXPECT_EQ(s.find_first_of('y'), StringPiece::npos);
161   EXPECT_EQ(s.find_first_of('y', 1), StringPiece::npos);
162   // starting position too far
163   EXPECT_EQ(s.find_first_of('o', 4), StringPiece::npos);
164   // starting pos that is obviously past the end -- This works for std::string
165   EXPECT_EQ(s.toString().find_first_of('y', 55), StringPiece::npos);
166   EXPECT_EQ(s.find_first_of('z', s.size()), StringPiece::npos);
167   EXPECT_EQ(s.find_first_of('z', 55), StringPiece::npos);
168   // null char
169   EXPECT_EQ(s.find_first_of('\0'), std::string().find_first_of('\0'));
170   EXPECT_EQ(s.find_first_of('\0'), StringPiece::npos);
171
172   // just "barbaz"
173   s.reset(foobarbaz + 3, strlen(foobarbaz + 3));
174   EXPECT_EQ(s.size(), 6);
175   EXPECT_EQ(s.start(), foobarbaz + 3);
176   EXPECT_EQ(s, "barbaz");
177
178   // just "bar"
179   s.reset(foobarbaz + 3, 3);
180   EXPECT_EQ(s.size(), 3);
181   EXPECT_EQ(s, "bar");
182
183   // clear
184   s.clear();
185   EXPECT_EQ(s.toString(), "");
186
187   // test an empty StringPiece
188   StringPiece s2;
189   EXPECT_EQ(s2.size(), 0);
190
191   // Test comparison operators
192   foo = "";
193   EXPECT_LE(s, foo);
194   EXPECT_LE(foo, s);
195   EXPECT_GE(s, foo);
196   EXPECT_GE(foo, s);
197   EXPECT_EQ(s, foo);
198   EXPECT_EQ(foo, s);
199
200   foo = "abc";
201   EXPECT_LE(s, foo);
202   EXPECT_LT(s, foo);
203   EXPECT_GE(foo, s);
204   EXPECT_GT(foo, s);
205   EXPECT_NE(s, foo);
206
207   EXPECT_LE(s, s);
208   EXPECT_LE(s, s);
209   EXPECT_GE(s, s);
210   EXPECT_GE(s, s);
211   EXPECT_EQ(s, s);
212   EXPECT_EQ(s, s);
213
214   s = "abc";
215   s2 = "abc";
216   EXPECT_LE(s, s2);
217   EXPECT_LE(s2, s);
218   EXPECT_GE(s, s2);
219   EXPECT_GE(s2, s);
220   EXPECT_EQ(s, s2);
221   EXPECT_EQ(s2, s);
222 }
223
224 template <class T>
225 void expectLT(const T& a, const T& b) {
226   EXPECT_TRUE(a < b);
227   EXPECT_TRUE(a <= b);
228   EXPECT_FALSE(a == b);
229   EXPECT_FALSE(a >= b);
230   EXPECT_FALSE(a > b);
231
232   EXPECT_FALSE(b < a);
233   EXPECT_FALSE(b <= a);
234   EXPECT_TRUE(b >= a);
235   EXPECT_TRUE(b > a);
236 }
237
238 template <class T>
239 void expectEQ(const T& a, const T& b) {
240   EXPECT_FALSE(a < b);
241   EXPECT_TRUE(a <= b);
242   EXPECT_TRUE(a == b);
243   EXPECT_TRUE(a >= b);
244   EXPECT_FALSE(a > b);
245 }
246
247 TEST(StringPiece, EightBitComparisons) {
248   char values[] = {'\x00', '\x20', '\x40', '\x7f', '\x80', '\xc0', '\xff'};
249   constexpr size_t count = sizeof(values) / sizeof(values[0]);
250   for (size_t i = 0; i < count; ++i) {
251     std::string a(1, values[i]);
252     // Defeat copy-on-write
253     std::string aCopy(a.data(), a.size());
254     expectEQ(a, aCopy);
255     expectEQ(StringPiece(a), StringPiece(aCopy));
256
257     for (size_t j = i + 1; j < count; ++j) {
258       std::string b(1, values[j]);
259       expectLT(a, b);
260       expectLT(StringPiece(a), StringPiece(b));
261     }
262   }
263 }
264
265 TEST(StringPiece, ToByteRange) {
266   StringPiece a("hello");
267   ByteRange b(a);
268   EXPECT_EQ(
269       static_cast<const void*>(a.begin()), static_cast<const void*>(b.begin()));
270   EXPECT_EQ(
271       static_cast<const void*>(a.end()), static_cast<const void*>(b.end()));
272
273   // and convert back again
274   StringPiece c(b);
275   EXPECT_EQ(a.begin(), c.begin());
276   EXPECT_EQ(a.end(), c.end());
277 }
278
279 TEST(StringPiece, InvalidRange) {
280   StringPiece a("hello");
281   EXPECT_EQ(a, a.subpiece(0, 10));
282   EXPECT_EQ(StringPiece("ello"), a.subpiece(1));
283   EXPECT_EQ(StringPiece("ello"), a.subpiece(1, std::string::npos));
284   EXPECT_EQ(StringPiece("ell"), a.subpiece(1, 3));
285   EXPECT_THROW(a.subpiece(6, 7), std::out_of_range);
286   EXPECT_THROW(a.subpiece(6), std::out_of_range);
287
288   std::string b("hello");
289   EXPECT_EQ(a, StringPiece(b, 0, 10));
290   EXPECT_EQ("ello", a.subpiece(1));
291   EXPECT_EQ("ello", a.subpiece(1, std::string::npos));
292   EXPECT_EQ("ell", a.subpiece(1, 3));
293   EXPECT_THROW(a.subpiece(6, 7), std::out_of_range);
294   EXPECT_THROW(a.subpiece(6), std::out_of_range);
295 }
296
297 TEST(StringPiece, Constexpr) {
298   constexpr const char* helloArray = "hello";
299
300   constexpr StringPiece hello1("hello");
301   EXPECT_EQ("hello", hello1);
302   static_assert(hello1.size() == 5, "hello size should be 5 at compile time");
303
304   constexpr StringPiece hello2(helloArray);
305   EXPECT_EQ("hello", hello2);
306   static_assert(hello2.size() == 5, "hello size should be 5 at compile time");
307 }
308
309 TEST(StringPiece, Prefix) {
310   StringPiece a("hello");
311   EXPECT_TRUE(a.startsWith(""));
312   EXPECT_TRUE(a.startsWith("h"));
313   EXPECT_TRUE(a.startsWith('h'));
314   EXPECT_TRUE(a.startsWith("hello"));
315   EXPECT_FALSE(a.startsWith("hellox"));
316   EXPECT_FALSE(a.startsWith('x'));
317   EXPECT_FALSE(a.startsWith("x"));
318
319   EXPECT_TRUE(a.startsWith("", folly::AsciiCaseInsensitive()));
320   EXPECT_TRUE(a.startsWith("hello", folly::AsciiCaseInsensitive()));
321   EXPECT_TRUE(a.startsWith("hellO", folly::AsciiCaseInsensitive()));
322   EXPECT_TRUE(a.startsWith("HELL", folly::AsciiCaseInsensitive()));
323   EXPECT_TRUE(a.startsWith("H", folly::AsciiCaseInsensitive()));
324   EXPECT_FALSE(a.startsWith("HELLOX", folly::AsciiCaseInsensitive()));
325   EXPECT_FALSE(a.startsWith("x", folly::AsciiCaseInsensitive()));
326   EXPECT_FALSE(a.startsWith("X", folly::AsciiCaseInsensitive()));
327
328   {
329     auto b = a;
330     EXPECT_TRUE(b.removePrefix(""));
331     EXPECT_EQ("hello", b);
332   }
333   {
334     auto b = a;
335     EXPECT_TRUE(b.removePrefix("h"));
336     EXPECT_EQ("ello", b);
337   }
338   {
339     auto b = a;
340     EXPECT_TRUE(b.removePrefix('h'));
341     EXPECT_EQ("ello", b);
342   }
343   {
344     auto b = a;
345     EXPECT_TRUE(b.removePrefix("hello"));
346     EXPECT_EQ("", b);
347   }
348   {
349     auto b = a;
350     EXPECT_FALSE(b.removePrefix("hellox"));
351     EXPECT_EQ("hello", b);
352   }
353   {
354     auto b = a;
355     EXPECT_FALSE(b.removePrefix("x"));
356     EXPECT_EQ("hello", b);
357   }
358   {
359     auto b = a;
360     EXPECT_FALSE(b.removePrefix('x'));
361     EXPECT_EQ("hello", b);
362   }
363 }
364
365 TEST(StringPiece, Suffix) {
366   StringPiece a("hello");
367   EXPECT_TRUE(a.endsWith(""));
368   EXPECT_TRUE(a.endsWith("o"));
369   EXPECT_TRUE(a.endsWith('o'));
370   EXPECT_TRUE(a.endsWith("hello"));
371   EXPECT_FALSE(a.endsWith("xhello"));
372   EXPECT_FALSE(a.endsWith("x"));
373   EXPECT_FALSE(a.endsWith('x'));
374
375   EXPECT_TRUE(a.endsWith("", folly::AsciiCaseInsensitive()));
376   EXPECT_TRUE(a.endsWith("o", folly::AsciiCaseInsensitive()));
377   EXPECT_TRUE(a.endsWith("O", folly::AsciiCaseInsensitive()));
378   EXPECT_TRUE(a.endsWith("hello", folly::AsciiCaseInsensitive()));
379   EXPECT_TRUE(a.endsWith("hellO", folly::AsciiCaseInsensitive()));
380   EXPECT_FALSE(a.endsWith("xhello", folly::AsciiCaseInsensitive()));
381   EXPECT_FALSE(a.endsWith("Xhello", folly::AsciiCaseInsensitive()));
382   EXPECT_FALSE(a.endsWith("x", folly::AsciiCaseInsensitive()));
383   EXPECT_FALSE(a.endsWith("X", folly::AsciiCaseInsensitive()));
384
385   {
386     auto b = a;
387     EXPECT_TRUE(b.removeSuffix(""));
388     EXPECT_EQ("hello", b);
389   }
390   {
391     auto b = a;
392     EXPECT_TRUE(b.removeSuffix("o"));
393     EXPECT_EQ("hell", b);
394   }
395   {
396     auto b = a;
397     EXPECT_TRUE(b.removeSuffix('o'));
398     EXPECT_EQ("hell", b);
399   }
400   {
401     auto b = a;
402     EXPECT_TRUE(b.removeSuffix("hello"));
403     EXPECT_EQ("", b);
404   }
405   {
406     auto b = a;
407     EXPECT_FALSE(b.removeSuffix("xhello"));
408     EXPECT_EQ("hello", b);
409   }
410   {
411     auto b = a;
412     EXPECT_FALSE(b.removeSuffix("x"));
413     EXPECT_EQ("hello", b);
414   }
415   {
416     auto b = a;
417     EXPECT_FALSE(b.removeSuffix('x'));
418     EXPECT_EQ("hello", b);
419   }
420 }
421
422 TEST(StringPiece, Equals) {
423   StringPiece a("hello");
424
425   EXPECT_TRUE(a.equals("HELLO", AsciiCaseInsensitive()));
426   EXPECT_FALSE(a.equals("HELLOX", AsciiCaseInsensitive()));
427 }
428
429 TEST(StringPiece, PrefixEmpty) {
430   StringPiece a;
431   EXPECT_TRUE(a.startsWith(""));
432   EXPECT_FALSE(a.startsWith("a"));
433   EXPECT_FALSE(a.startsWith('a'));
434   EXPECT_TRUE(a.removePrefix(""));
435   EXPECT_EQ("", a);
436   EXPECT_FALSE(a.removePrefix("a"));
437   EXPECT_EQ("", a);
438   EXPECT_FALSE(a.removePrefix('a'));
439   EXPECT_EQ("", a);
440 }
441
442 TEST(StringPiece, SuffixEmpty) {
443   StringPiece a;
444   EXPECT_TRUE(a.endsWith(""));
445   EXPECT_FALSE(a.endsWith("a"));
446   EXPECT_FALSE(a.endsWith('a'));
447   EXPECT_TRUE(a.removeSuffix(""));
448   EXPECT_EQ("", a);
449   EXPECT_FALSE(a.removeSuffix("a"));
450   EXPECT_EQ("", a);
451   EXPECT_FALSE(a.removeSuffix('a'));
452   EXPECT_EQ("", a);
453 }
454
455 TEST(StringPiece, erase) {
456   StringPiece a("hello");
457   auto b = a.begin();
458   auto e = b + 1;
459   a.erase(b, e);
460   EXPECT_EQ("ello", a);
461
462   e = a.end();
463   b = e - 1;
464   a.erase(b, e);
465   EXPECT_EQ("ell", a);
466
467   b = a.end() - 1;
468   e = a.end() - 1;
469   EXPECT_THROW(a.erase(b, e), std::out_of_range);
470
471   b = a.begin();
472   e = a.end();
473   a.erase(b, e);
474   EXPECT_EQ("", a);
475
476   a = "hello";
477   b = a.begin();
478   e = b + 2;
479   a.erase(b, e);
480   EXPECT_EQ("llo", a);
481
482   b = a.end() - 2;
483   e = a.end();
484   a.erase(b, e);
485   EXPECT_EQ("l", a);
486
487   a = "      hello  ";
488   boost::algorithm::trim(a);
489   EXPECT_EQ(a, "hello");
490 }
491
492 TEST(StringPiece, split_step_char_delimiter) {
493   //              0         1         2
494   //              012345678901234567890123456
495   auto const s = "this is just  a test string";
496   auto const e = std::next(s, std::strlen(s));
497   EXPECT_EQ('\0', *e);
498
499   folly::StringPiece p(s);
500   EXPECT_EQ(s, p.begin());
501   EXPECT_EQ(e, p.end());
502   EXPECT_EQ(s, p);
503
504   auto x = p.split_step(' ');
505   EXPECT_EQ(std::next(s, 5), p.begin());
506   EXPECT_EQ(e, p.end());
507   EXPECT_EQ("this", x);
508
509   x = p.split_step(' ');
510   EXPECT_EQ(std::next(s, 8), p.begin());
511   EXPECT_EQ(e, p.end());
512   EXPECT_EQ("is", x);
513
514   x = p.split_step('u');
515   EXPECT_EQ(std::next(s, 10), p.begin());
516   EXPECT_EQ(e, p.end());
517   EXPECT_EQ("j", x);
518
519   x = p.split_step(' ');
520   EXPECT_EQ(std::next(s, 13), p.begin());
521   EXPECT_EQ(e, p.end());
522   EXPECT_EQ("st", x);
523
524   x = p.split_step(' ');
525   EXPECT_EQ(std::next(s, 14), p.begin());
526   EXPECT_EQ(e, p.end());
527   EXPECT_EQ("", x);
528
529   x = p.split_step(' ');
530   EXPECT_EQ(std::next(s, 16), p.begin());
531   EXPECT_EQ(e, p.end());
532   EXPECT_EQ("a", x);
533
534   x = p.split_step(' ');
535   EXPECT_EQ(std::next(s, 21), p.begin());
536   EXPECT_EQ(e, p.end());
537   EXPECT_EQ("test", x);
538
539   x = p.split_step(' ');
540   EXPECT_EQ(e, p.begin());
541   EXPECT_EQ(e, p.end());
542   EXPECT_EQ("string", x);
543
544   x = p.split_step(' ');
545   EXPECT_EQ(e, p.begin());
546   EXPECT_EQ(e, p.end());
547   EXPECT_EQ("", x);
548 }
549
550 TEST(StringPiece, split_step_range_delimiter) {
551   //              0         1         2         3
552   //              0123456789012345678901234567890123
553   auto const s = "this  is  just    a   test  string";
554   auto const e = std::next(s, std::strlen(s));
555   EXPECT_EQ('\0', *e);
556
557   folly::StringPiece p(s);
558   EXPECT_EQ(s, p.begin());
559   EXPECT_EQ(e, p.end());
560   EXPECT_EQ(s, p);
561
562   auto x = p.split_step("  ");
563   EXPECT_EQ(std::next(s, 6), p.begin());
564   EXPECT_EQ(e, p.end());
565   EXPECT_EQ("this", x);
566
567   x = p.split_step("  ");
568   EXPECT_EQ(std::next(s, 10), p.begin());
569   EXPECT_EQ(e, p.end());
570   EXPECT_EQ("is", x);
571
572   x = p.split_step("u");
573   EXPECT_EQ(std::next(s, 12), p.begin());
574   EXPECT_EQ(e, p.end());
575   EXPECT_EQ("j", x);
576
577   x = p.split_step("  ");
578   EXPECT_EQ(std::next(s, 16), p.begin());
579   EXPECT_EQ(e, p.end());
580   EXPECT_EQ("st", x);
581
582   x = p.split_step("  ");
583   EXPECT_EQ(std::next(s, 18), p.begin());
584   EXPECT_EQ(e, p.end());
585   EXPECT_EQ("", x);
586
587   x = p.split_step("  ");
588   EXPECT_EQ(std::next(s, 21), p.begin());
589   EXPECT_EQ(e, p.end());
590   EXPECT_EQ("a", x);
591
592   x = p.split_step("  ");
593   EXPECT_EQ(std::next(s, 28), p.begin());
594   EXPECT_EQ(e, p.end());
595   EXPECT_EQ(" test", x);
596
597   x = p.split_step("  ");
598   EXPECT_EQ(e, p.begin());
599   EXPECT_EQ(e, p.end());
600   EXPECT_EQ("string", x);
601
602   x = p.split_step("  ");
603   EXPECT_EQ(e, p.begin());
604   EXPECT_EQ(e, p.end());
605   EXPECT_EQ("", x);
606
607   x = p.split_step(" ");
608   EXPECT_EQ(e, p.begin());
609   EXPECT_EQ(e, p.end());
610   EXPECT_EQ("", x);
611 }
612
613 void split_step_with_process_noop(folly::StringPiece) {}
614
615 TEST(StringPiece, split_step_with_process_char_delimiter) {
616   //              0         1         2
617   //              012345678901234567890123456
618   auto const s = "this is just  a test string";
619   auto const e = std::next(s, std::strlen(s));
620   EXPECT_EQ('\0', *e);
621
622   folly::StringPiece p(s);
623   EXPECT_EQ(s, p.begin());
624   EXPECT_EQ(e, p.end());
625   EXPECT_EQ(s, p);
626
627   EXPECT_EQ(1, (p.split_step(' ', [&](folly::StringPiece x) {
628               EXPECT_EQ(std::next(s, 5), p.begin());
629               EXPECT_EQ(e, p.end());
630               EXPECT_EQ("this", x);
631               return 1;
632             })));
633
634   EXPECT_EQ(2, (p.split_step(' ', [&](folly::StringPiece x) {
635               EXPECT_EQ(std::next(s, 8), p.begin());
636               EXPECT_EQ(e, p.end());
637               EXPECT_EQ("is", x);
638               return 2;
639             })));
640
641   EXPECT_EQ(3, (p.split_step('u', [&](folly::StringPiece x) {
642               EXPECT_EQ(std::next(s, 10), p.begin());
643               EXPECT_EQ(e, p.end());
644               EXPECT_EQ("j", x);
645               return 3;
646             })));
647
648   EXPECT_EQ(4, (p.split_step(' ', [&](folly::StringPiece x) {
649               EXPECT_EQ(std::next(s, 13), p.begin());
650               EXPECT_EQ(e, p.end());
651               EXPECT_EQ("st", x);
652               return 4;
653             })));
654
655   EXPECT_EQ(5, (p.split_step(' ', [&](folly::StringPiece x) {
656               EXPECT_EQ(std::next(s, 14), p.begin());
657               EXPECT_EQ(e, p.end());
658               EXPECT_EQ("", x);
659               return 5;
660             })));
661
662   EXPECT_EQ(6, (p.split_step(' ', [&](folly::StringPiece x) {
663               EXPECT_EQ(std::next(s, 16), p.begin());
664               EXPECT_EQ(e, p.end());
665               EXPECT_EQ("a", x);
666               return 6;
667             })));
668
669   EXPECT_EQ(7, (p.split_step(' ', [&](folly::StringPiece x) {
670               EXPECT_EQ(std::next(s, 21), p.begin());
671               EXPECT_EQ(e, p.end());
672               EXPECT_EQ("test", x);
673               return 7;
674             })));
675
676   EXPECT_EQ(8, (p.split_step(' ', [&](folly::StringPiece x) {
677               EXPECT_EQ(e, p.begin());
678               EXPECT_EQ(e, p.end());
679               EXPECT_EQ("string", x);
680               return 8;
681             })));
682
683   EXPECT_EQ(9, (p.split_step(' ', [&](folly::StringPiece x) {
684               EXPECT_EQ(e, p.begin());
685               EXPECT_EQ(e, p.end());
686               EXPECT_EQ("", x);
687               return 9;
688             })));
689
690   EXPECT_TRUE(
691       (std::is_same<
692           void,
693           decltype(p.split_step(' ', split_step_with_process_noop))>::value));
694
695   EXPECT_NO_THROW(p.split_step(' ', split_step_with_process_noop));
696 }
697
698 TEST(StringPiece, split_step_with_process_range_delimiter) {
699   //              0         1         2         3
700   //              0123456789012345678901234567890123
701   auto const s = "this  is  just    a   test  string";
702   auto const e = std::next(s, std::strlen(s));
703   EXPECT_EQ('\0', *e);
704
705   folly::StringPiece p(s);
706   EXPECT_EQ(s, p.begin());
707   EXPECT_EQ(e, p.end());
708   EXPECT_EQ(s, p);
709
710   EXPECT_EQ(1, (p.split_step("  ", [&](folly::StringPiece x) {
711               EXPECT_EQ(std::next(s, 6), p.begin());
712               EXPECT_EQ(e, p.end());
713               EXPECT_EQ("this", x);
714               return 1;
715             })));
716
717   EXPECT_EQ(2, (p.split_step("  ", [&](folly::StringPiece x) {
718               EXPECT_EQ(std::next(s, 10), p.begin());
719               EXPECT_EQ(e, p.end());
720               EXPECT_EQ("is", x);
721               return 2;
722             })));
723
724   EXPECT_EQ(3, (p.split_step("u", [&](folly::StringPiece x) {
725               EXPECT_EQ(std::next(s, 12), p.begin());
726               EXPECT_EQ(e, p.end());
727               EXPECT_EQ("j", x);
728               return 3;
729             })));
730
731   EXPECT_EQ(4, (p.split_step("  ", [&](folly::StringPiece x) {
732               EXPECT_EQ(std::next(s, 16), p.begin());
733               EXPECT_EQ(e, p.end());
734               EXPECT_EQ("st", x);
735               return 4;
736             })));
737
738   EXPECT_EQ(5, (p.split_step("  ", [&](folly::StringPiece x) {
739               EXPECT_EQ(std::next(s, 18), p.begin());
740               EXPECT_EQ(e, p.end());
741               EXPECT_EQ("", x);
742               return 5;
743             })));
744
745   EXPECT_EQ(6, (p.split_step("  ", [&](folly::StringPiece x) {
746               EXPECT_EQ(std::next(s, 21), p.begin());
747               EXPECT_EQ(e, p.end());
748               EXPECT_EQ("a", x);
749               return 6;
750             })));
751
752   EXPECT_EQ(7, (p.split_step("  ", [&](folly::StringPiece x) {
753               EXPECT_EQ(std::next(s, 28), p.begin());
754               EXPECT_EQ(e, p.end());
755               EXPECT_EQ(" test", x);
756               return 7;
757             })));
758
759   EXPECT_EQ(8, (p.split_step("  ", [&](folly::StringPiece x) {
760               EXPECT_EQ(e, p.begin());
761               EXPECT_EQ(e, p.end());
762               EXPECT_EQ("string", x);
763               return 8;
764             })));
765
766   EXPECT_EQ(9, (p.split_step("  ", [&](folly::StringPiece x) {
767               EXPECT_EQ(e, p.begin());
768               EXPECT_EQ(e, p.end());
769               EXPECT_EQ("", x);
770               return 9;
771             })));
772
773   EXPECT_EQ(10, (p.split_step("  ", [&](folly::StringPiece x) {
774               EXPECT_EQ(e, p.begin());
775               EXPECT_EQ(e, p.end());
776               EXPECT_EQ("", x);
777               return 10;
778             })));
779
780   EXPECT_TRUE(
781       (std::is_same<
782           void,
783           decltype(p.split_step(' ', split_step_with_process_noop))>::value));
784
785   EXPECT_NO_THROW(p.split_step(' ', split_step_with_process_noop));
786 }
787
788 TEST(StringPiece, split_step_with_process_char_delimiter_additional_args) {
789   //              0         1         2
790   //              012345678901234567890123456
791   auto const s = "this is just  a test string";
792   auto const e = std::next(s, std::strlen(s));
793   auto const delimiter = ' ';
794   EXPECT_EQ('\0', *e);
795
796   folly::StringPiece p(s);
797   EXPECT_EQ(s, p.begin());
798   EXPECT_EQ(e, p.end());
799   EXPECT_EQ(s, p);
800
801   auto const functor = [](folly::StringPiece s, folly::StringPiece expected) {
802     EXPECT_EQ(expected, s);
803     return expected;
804   };
805
806   auto const checker = [&](folly::StringPiece expected) {
807     EXPECT_EQ(expected, p.split_step(delimiter, functor, expected));
808   };
809
810   checker("this");
811   checker("is");
812   checker("just");
813   checker("");
814   checker("a");
815   checker("test");
816   checker("string");
817   checker("");
818   checker("");
819
820   EXPECT_TRUE(p.empty());
821 }
822
823 TEST(StringPiece, split_step_with_process_range_delimiter_additional_args) {
824   //              0         1         2         3
825   //              0123456789012345678901234567890123
826   auto const s = "this  is  just    a   test  string";
827   auto const e = std::next(s, std::strlen(s));
828   auto const delimiter = "  ";
829   EXPECT_EQ('\0', *e);
830
831   folly::StringPiece p(s);
832   EXPECT_EQ(s, p.begin());
833   EXPECT_EQ(e, p.end());
834   EXPECT_EQ(s, p);
835
836   auto const functor = [](folly::StringPiece s, folly::StringPiece expected) {
837     EXPECT_EQ(expected, s);
838     return expected;
839   };
840
841   auto const checker = [&](folly::StringPiece expected) {
842     EXPECT_EQ(expected, p.split_step(delimiter, functor, expected));
843   };
844
845   checker("this");
846   checker("is");
847   checker("just");
848   checker("");
849   checker("a");
850   checker(" test");
851   checker("string");
852   checker("");
853   checker("");
854
855   EXPECT_TRUE(p.empty());
856 }
857
858 TEST(StringPiece, NoInvalidImplicitConversions) {
859   struct IsString {
860     bool operator()(folly::Range<int*>) {
861       return false;
862     }
863     bool operator()(folly::StringPiece) {
864       return true;
865     }
866   };
867
868   std::string s = "hello";
869   EXPECT_TRUE(IsString()(s));
870 }
871
872 TEST(qfind, UInt32_Ranges) {
873   vector<uint32_t> a({1, 2, 3, 260, 5});
874   vector<uint32_t> b({2, 3, 4});
875
876   auto a_range = folly::Range<const uint32_t*>(&a[0], a.size());
877   auto b_range = folly::Range<const uint32_t*>(&b[0], b.size());
878
879   EXPECT_EQ(qfind(a_range, b_range), string::npos);
880
881   a[3] = 4;
882   EXPECT_EQ(qfind(a_range, b_range), 1);
883 }
884
885 template <typename NeedleFinder>
886 class NeedleFinderTest : public ::testing::Test {
887  public:
888   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
889     return NeedleFinder::find_first_byte_of(haystack, needles);
890   }
891 };
892
893 struct SseNeedleFinder {
894   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
895     // This will only use the SSE version if it is supported on this CPU
896     // (selected using ifunc).
897     return detail::qfind_first_byte_of(haystack, needles);
898   }
899 };
900
901 struct NoSseNeedleFinder {
902   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
903     return detail::qfind_first_byte_of_nosse(haystack, needles);
904   }
905 };
906
907 struct ByteSetNeedleFinder {
908   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
909     return detail::qfind_first_byte_of_byteset(haystack, needles);
910   }
911 };
912
913 using NeedleFinders =
914     ::testing::Types<SseNeedleFinder, NoSseNeedleFinder, ByteSetNeedleFinder>;
915 TYPED_TEST_CASE(NeedleFinderTest, NeedleFinders);
916
917 TYPED_TEST(NeedleFinderTest, Null) {
918   { // null characters in the string
919     string s(10, char(0));
920     s[5] = 'b';
921     string delims("abc");
922     EXPECT_EQ(5, this->find_first_byte_of(s, delims));
923   }
924   { // null characters in delim
925     string s("abc");
926     string delims(10, char(0));
927     delims[3] = 'c';
928     delims[7] = 'b';
929     EXPECT_EQ(1, this->find_first_byte_of(s, delims));
930   }
931   { // range not terminated by null character
932     string buf = "abcdefghijklmnopqrstuvwxyz";
933     StringPiece s(buf.data() + 5, 3);
934     StringPiece delims("z");
935     EXPECT_EQ(string::npos, this->find_first_byte_of(s, delims));
936   }
937 }
938
939 TYPED_TEST(NeedleFinderTest, DelimDuplicates) {
940   string delims(1000, 'b');
941   EXPECT_EQ(1, this->find_first_byte_of("abc", delims));
942   EXPECT_EQ(string::npos, this->find_first_byte_of("ac", delims));
943 }
944
945 TYPED_TEST(NeedleFinderTest, Empty) {
946   string a = "abc";
947   string b = "";
948   EXPECT_EQ(string::npos, this->find_first_byte_of(a, b));
949   EXPECT_EQ(string::npos, this->find_first_byte_of(b, a));
950   EXPECT_EQ(string::npos, this->find_first_byte_of(b, b));
951 }
952
953 TYPED_TEST(NeedleFinderTest, Unaligned) {
954   // works correctly even if input buffers are not 16-byte aligned
955   string s = "0123456789ABCDEFGH";
956   for (size_t i = 0; i < s.size(); ++i) {
957     StringPiece a(s.c_str() + i);
958     for (size_t j = 0; j < s.size(); ++j) {
959       StringPiece b(s.c_str() + j);
960       EXPECT_EQ((i > j) ? 0 : j - i, this->find_first_byte_of(a, b));
961     }
962   }
963 }
964
965 // for some algorithms (specifically those that create a set of needles),
966 // we check for the edge-case of _all_ possible needles being sought.
967 TYPED_TEST(NeedleFinderTest, Needles256) {
968   string needles;
969   const auto minValue = std::numeric_limits<StringPiece::value_type>::min();
970   const auto maxValue = std::numeric_limits<StringPiece::value_type>::max();
971   // make the size ~big to avoid any edge-case branches for tiny haystacks
972   const int haystackSize = 50;
973   for (int i = minValue; i <= maxValue; i++) { // <=
974     needles.push_back(i);
975   }
976   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
977   for (int i = minValue; i <= maxValue; i++) {
978     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
979   }
980
981   needles.append("these are redundant characters");
982   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
983   for (int i = minValue; i <= maxValue; i++) {
984     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
985   }
986 }
987
988 TYPED_TEST(NeedleFinderTest, Base) {
989   for (size_t i = 0; i < 32; ++i) {
990     for (int j = 0; j < 32; ++j) {
991       string s = string(i, 'X') + "abca" + string(i, 'X');
992       string delims = string(j, 'Y') + "a" + string(j, 'Y');
993       EXPECT_EQ(i, this->find_first_byte_of(s, delims));
994     }
995   }
996 }
997
998 const size_t kPageSize = 4096;
999 // Updates contents so that any read accesses past the last byte will
1000 // cause a SIGSEGV.  It accomplishes this by changing access to the page that
1001 // begins immediately after the end of the contents (as allocators and mmap()
1002 // all operate on page boundaries, this is a reasonable assumption).
1003 // This function will also initialize buf, which caller must free().
1004 void createProtectedBuf(StringPiece& contents, char** buf) {
1005   ASSERT_LE(contents.size(), kPageSize);
1006   const size_t kSuccess = 0;
1007   char* pageAlignedBuf = (char*)aligned_malloc(2 * kPageSize, kPageSize);
1008   if (pageAlignedBuf == nullptr) {
1009     FAIL();
1010   }
1011   // Protect the page after the first full page-aligned region of the
1012   // malloc'ed buffer
1013   mprotect(pageAlignedBuf + kPageSize, kPageSize, PROT_NONE);
1014   size_t newBegin = kPageSize - contents.size();
1015   memcpy(pageAlignedBuf + newBegin, contents.data(), contents.size());
1016   contents.reset(pageAlignedBuf + newBegin, contents.size());
1017   *buf = pageAlignedBuf;
1018 }
1019
1020 void freeProtectedBuf(char* buf) {
1021   mprotect(buf + kPageSize, kPageSize, PROT_READ | PROT_WRITE);
1022   aligned_free(buf);
1023 }
1024
1025 TYPED_TEST(NeedleFinderTest, NoSegFault) {
1026   const string base = string(32, 'a') + string("b");
1027   const string delims = string(32, 'c') + string("b");
1028   for (int i = 0; i <= 32; i++) {
1029     for (int j = 0; j <= 33; j++) {
1030       for (int shouldFind = 0; shouldFind <= 1; ++shouldFind) {
1031         StringPiece s1(base);
1032         s1.advance(i);
1033         ASSERT_TRUE(!s1.empty());
1034         if (!shouldFind) {
1035           s1.pop_back();
1036         }
1037         StringPiece s2(delims);
1038         s2.advance(j);
1039         char* buf1;
1040         char* buf2;
1041         createProtectedBuf(s1, &buf1);
1042         createProtectedBuf(s2, &buf2);
1043         // printf("s1: '%s' (%ld) \ts2: '%s' (%ld)\n",
1044         //        string(s1.data(), s1.size()).c_str(), s1.size(),
1045         //        string(s2.data(), s2.size()).c_str(), s2.size());
1046         auto r1 = this->find_first_byte_of(s1, s2);
1047         auto f1 =
1048             std::find_first_of(s1.begin(), s1.end(), s2.begin(), s2.end());
1049         auto e1 = (f1 == s1.end()) ? StringPiece::npos : f1 - s1.begin();
1050         EXPECT_EQ(r1, e1);
1051         auto r2 = this->find_first_byte_of(s2, s1);
1052         auto f2 =
1053             std::find_first_of(s2.begin(), s2.end(), s1.begin(), s1.end());
1054         auto e2 = (f2 == s2.end()) ? StringPiece::npos : f2 - s2.begin();
1055         EXPECT_EQ(r2, e2);
1056         freeProtectedBuf(buf1);
1057         freeProtectedBuf(buf2);
1058       }
1059     }
1060   }
1061 }
1062
1063 TEST(NonConstTest, StringPiece) {
1064   std::string hello("hello");
1065   MutableStringPiece sp(&hello.front(), hello.size());
1066   sp[0] = 'x';
1067   EXPECT_EQ("xello", hello);
1068   {
1069     StringPiece s(sp);
1070     EXPECT_EQ("xello", s);
1071   }
1072   {
1073     ByteRange r1(sp);
1074     MutableByteRange r2(sp);
1075   }
1076 }
1077
1078 // Similar to the begin() template functions, but instread of returing
1079 // an iterator, return a pointer to data.
1080 template <class Container>
1081 typename Container::value_type* dataPtr(Container& cont) {
1082   // NOTE: &cont[0] is undefined if cont is empty (it creates a
1083   // reference to nullptr - which is not dereferenced, but still UBSAN).
1084   return cont.data();
1085 }
1086 template <class T, size_t N>
1087 constexpr T* dataPtr(T (&arr)[N]) noexcept {
1088   return &arr[0];
1089 }
1090
1091 template <class C>
1092 void testRangeFunc(C&& x, size_t n) {
1093   const auto& cx = x;
1094   // type, conversion checks
1095   Range<int*> r1 = range(std::forward<C>(x));
1096   Range<const int*> r2 = range(std::forward<C>(x));
1097   Range<const int*> r3 = range(cx);
1098   Range<const int*> r5 = range(std::move(cx));
1099   EXPECT_EQ(r1.begin(), dataPtr(x));
1100   EXPECT_EQ(r1.end(), dataPtr(x) + n);
1101   EXPECT_EQ(n, r1.size());
1102   EXPECT_EQ(n, r2.size());
1103   EXPECT_EQ(n, r3.size());
1104   EXPECT_EQ(n, r5.size());
1105 }
1106
1107 TEST(RangeFunc, Vector) {
1108   std::vector<int> x;
1109   testRangeFunc(x, 0);
1110   x.push_back(2);
1111   testRangeFunc(x, 1);
1112   testRangeFunc(std::vector<int>{1, 2}, 2);
1113 }
1114
1115 TEST(RangeFunc, Array) {
1116   std::array<int, 3> x;
1117   testRangeFunc(x, 3);
1118 }
1119
1120 TEST(RangeFunc, CArray) {
1121   int x[]{1, 2, 3, 4};
1122   testRangeFunc(x, 4);
1123 }
1124
1125 TEST(RangeFunc, ConstexprCArray) {
1126   static constexpr const int numArray[4] = {3, 17, 1, 9};
1127   constexpr const auto numArrayRange = range(numArray);
1128   EXPECT_EQ(17, numArrayRange[1]);
1129   constexpr const auto numArrayRangeSize = numArrayRange.size();
1130   EXPECT_EQ(4, numArrayRangeSize);
1131 }
1132
1133 TEST(RangeFunc, ConstexprStdArray) {
1134   static constexpr const std::array<int, 4> numArray = {{3, 17, 1, 9}};
1135   constexpr const auto numArrayRange = range(numArray);
1136   EXPECT_EQ(17, numArrayRange[1]);
1137   constexpr const auto numArrayRangeSize = numArrayRange.size();
1138   EXPECT_EQ(4, numArrayRangeSize);
1139 }
1140
1141 TEST(RangeFunc, ConstexprStdArrayZero) {
1142   static constexpr const std::array<int, 0> numArray = {};
1143   constexpr const auto numArrayRange = range(numArray);
1144   constexpr const auto numArrayRangeSize = numArrayRange.size();
1145   EXPECT_EQ(0, numArrayRangeSize);
1146 }
1147
1148 TEST(RangeFunc, ConstexprIteratorPair) {
1149   static constexpr const int numArray[4] = {3, 17, 1, 9};
1150   constexpr const auto numPtr = static_cast<const int*>(numArray);
1151   constexpr const auto numIterRange = range(numPtr + 1, numPtr + 3);
1152   EXPECT_EQ(1, numIterRange[1]);
1153   constexpr const auto numIterRangeSize = numIterRange.size();
1154   EXPECT_EQ(2, numIterRangeSize);
1155 }
1156
1157 TEST(RangeFunc, ConstexprCollection) {
1158   class IntCollection {
1159    public:
1160     constexpr IntCollection(const int* d, size_t s) : data_(d), size_(s) {}
1161     constexpr const int* data() const {
1162       return data_;
1163     }
1164     constexpr size_t size() const {
1165       return size_;
1166     }
1167
1168    private:
1169     const int* data_;
1170     size_t size_;
1171   };
1172   static constexpr const int numArray[4] = {3, 17, 1, 9};
1173   constexpr const auto numPtr = static_cast<const int*>(numArray);
1174   constexpr const auto numColl = IntCollection(numPtr + 1, 2);
1175   constexpr const auto numCollRange = range(numColl);
1176   EXPECT_EQ(1, numCollRange[1]);
1177   constexpr const auto numCollRangeSize = numCollRange.size();
1178   EXPECT_EQ(2, numCollRangeSize);
1179 }
1180
1181 std::string get_rand_str(
1182     size_t size,
1183     std::uniform_int_distribution<>& dist,
1184     std::mt19937& gen) {
1185   std::string ret(size, '\0');
1186   for (size_t i = 0; i < size; ++i) {
1187     ret[i] = static_cast<char>(dist(gen));
1188   }
1189
1190   return ret;
1191 }
1192
1193 namespace folly {
1194 bool operator==(MutableStringPiece mp, StringPiece sp) {
1195   return mp.compare(sp) == 0;
1196 }
1197
1198 bool operator==(StringPiece sp, MutableStringPiece mp) {
1199   return mp.compare(sp) == 0;
1200 }
1201 }
1202
1203 TEST(ReplaceAt, exhaustiveTest) {
1204   char input[] = "this is nice and long input";
1205   auto msp = MutableStringPiece(input);
1206   auto str = std::string(input);
1207   std::random_device rd;
1208   std::mt19937 gen(rd());
1209   std::uniform_int_distribution<> dist('a', 'z');
1210
1211   for (int i = 0; i < 100; ++i) {
1212     for (size_t j = 1; j <= msp.size(); ++j) {
1213       auto replacement = get_rand_str(j, dist, gen);
1214       for (size_t pos = 0; pos < msp.size() - j; ++pos) {
1215         msp.replaceAt(pos, replacement);
1216         str.replace(pos, replacement.size(), replacement);
1217         EXPECT_EQ(msp.compare(str), 0);
1218       }
1219     }
1220   }
1221
1222   // too far
1223   EXPECT_EQ(msp.replaceAt(msp.size() - 2, StringPiece("meh")), false);
1224 }
1225
1226 TEST(ReplaceAll, basicTest) {
1227   char input[] = "this is nice and long input";
1228   auto orig = std::string(input);
1229   auto msp = MutableStringPiece(input);
1230
1231   EXPECT_EQ(msp.replaceAll("is", "si"), 2);
1232   EXPECT_EQ("thsi si nice and long input", msp);
1233   EXPECT_EQ(msp.replaceAll("si", "is"), 2);
1234   EXPECT_EQ(msp, orig);
1235
1236   EXPECT_EQ(msp.replaceAll("abcd", "efgh"), 0); // nothing to replace
1237   EXPECT_EQ(msp, orig);
1238
1239   // at the very beginning
1240   EXPECT_EQ(msp.replaceAll("this", "siht"), 1);
1241   EXPECT_EQ("siht is nice and long input", msp);
1242   EXPECT_EQ(msp.replaceAll("siht", "this"), 1);
1243   EXPECT_EQ(msp, orig);
1244
1245   // at the very end
1246   EXPECT_EQ(msp.replaceAll("input", "soput"), 1);
1247   EXPECT_EQ("this is nice and long soput", msp);
1248   EXPECT_EQ(msp.replaceAll("soput", "input"), 1);
1249   EXPECT_EQ(msp, orig);
1250
1251   // all spaces
1252   EXPECT_EQ(msp.replaceAll(" ", "@"), 5);
1253   EXPECT_EQ("this@is@nice@and@long@input", msp);
1254   EXPECT_EQ(msp.replaceAll("@", " "), 5);
1255   EXPECT_EQ(msp, orig);
1256 }
1257
1258 TEST(ReplaceAll, randomTest) {
1259   char input[] = "abcdefghijklmnoprstuwqz"; // no pattern repeata inside
1260   auto orig = std::string(input);
1261   auto msp = MutableStringPiece(input);
1262
1263   std::random_device rd;
1264   std::mt19937 gen(rd());
1265   std::uniform_int_distribution<> dist('A', 'Z');
1266
1267   for (int i = 0; i < 100; ++i) {
1268     for (size_t j = 1; j <= orig.size(); ++j) {
1269       auto replacement = get_rand_str(j, dist, gen);
1270       for (size_t pos = 0; pos < msp.size() - j; ++pos) {
1271         auto piece = orig.substr(pos, j);
1272         EXPECT_EQ(msp.replaceAll(piece, replacement), 1);
1273         EXPECT_EQ(msp.find(replacement), pos);
1274         EXPECT_EQ(msp.replaceAll(replacement, piece), 1);
1275         EXPECT_EQ(msp, orig);
1276       }
1277     }
1278   }
1279 }
1280
1281 TEST(ReplaceAll, BadArg) {
1282   int count = 0;
1283   auto fst = "longer";
1284   auto snd = "small";
1285   char input[] = "meh meh meh";
1286   auto all = MutableStringPiece(input);
1287
1288   try {
1289     all.replaceAll(fst, snd);
1290   } catch (std::invalid_argument&) {
1291     ++count;
1292   }
1293
1294   try {
1295     all.replaceAll(snd, fst);
1296   } catch (std::invalid_argument&) {
1297     ++count;
1298   }
1299
1300   EXPECT_EQ(count, 2);
1301 }
1302
1303 TEST(Range, Constructors) {
1304   vector<int> c = {1, 2, 3};
1305   typedef Range<vector<int>::iterator> RangeType;
1306   typedef Range<vector<int>::const_iterator> ConstRangeType;
1307   RangeType cr(c.begin(), c.end());
1308   auto subpiece1 = ConstRangeType(cr, 1, 5);
1309   auto subpiece2 = ConstRangeType(cr, 1);
1310   EXPECT_EQ(subpiece1.size(), 2);
1311   EXPECT_EQ(subpiece1.begin(), subpiece2.begin());
1312   EXPECT_EQ(subpiece1.end(), subpiece2.end());
1313 }
1314
1315 TEST(Range, ArrayConstructors) {
1316   auto charArray = std::array<char, 4>{{'t', 'e', 's', 't'}};
1317   auto constCharArray = std::array<char, 6>{{'f', 'o', 'o', 'b', 'a', 'r'}};
1318   auto emptyArray = std::array<char, 0>{};
1319
1320   auto sp1 = StringPiece{charArray};
1321   EXPECT_EQ(4, sp1.size());
1322   EXPECT_EQ(charArray.data(), sp1.data());
1323
1324   auto sp2 = StringPiece(constCharArray);
1325   EXPECT_EQ(6, sp2.size());
1326   EXPECT_EQ(constCharArray.data(), sp2.data());
1327
1328   auto msp = MutableStringPiece(charArray);
1329   EXPECT_EQ(4, msp.size());
1330   EXPECT_EQ(charArray.data(), msp.data());
1331
1332   auto esp = StringPiece(emptyArray);
1333   EXPECT_EQ(0, esp.size());
1334   EXPECT_EQ(nullptr, esp.data());
1335
1336   auto emsp = MutableStringPiece(emptyArray);
1337   EXPECT_EQ(0, emsp.size());
1338   EXPECT_EQ(nullptr, emsp.data());
1339
1340   static constexpr std::array<int, 4> numArray = {{3, 17, 1, 9}};
1341   constexpr auto numRange = Range<const int*>{numArray};
1342   EXPECT_EQ(17, numRange[1]);
1343
1344   static constexpr std::array<int, 0> emptyNumArray{};
1345   constexpr auto emptyNumRange = Range<const int*>{emptyNumArray};
1346   EXPECT_EQ(0, emptyNumRange.size());
1347 }
1348
1349 TEST(Range, ConstexprAccessors) {
1350   constexpr StringPiece piece = range("hello");
1351   static_assert(piece.size() == 6u, "");
1352   static_assert(piece.end() - piece.begin() == 6u, "");
1353   static_assert(piece.data() == piece.begin(), "");
1354   static_assert(piece.start() == piece.begin(), "");
1355   static_assert(piece.cbegin() == piece.begin(), "");
1356   static_assert(piece.cend() == piece.end(), "");
1357   static_assert(*piece.begin() == 'h', "");
1358   static_assert(*(piece.end() - 1) == '\0', "");
1359 }