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