add missing include to ThreadId.h
[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   EXPECT_TRUE(a.startsWith("", folly::AsciiCaseInsensitive()));
319   EXPECT_TRUE(a.startsWith("hello", folly::AsciiCaseInsensitive()));
320   EXPECT_TRUE(a.startsWith("hellO", folly::AsciiCaseInsensitive()));
321   EXPECT_TRUE(a.startsWith("HELL", folly::AsciiCaseInsensitive()));
322   EXPECT_TRUE(a.startsWith("H", folly::AsciiCaseInsensitive()));
323   EXPECT_FALSE(a.startsWith("HELLOX", folly::AsciiCaseInsensitive()));
324   EXPECT_FALSE(a.startsWith("x", folly::AsciiCaseInsensitive()));
325   EXPECT_FALSE(a.startsWith("X", folly::AsciiCaseInsensitive()));
326
327   {
328     auto b = a;
329     EXPECT_TRUE(b.removePrefix(""));
330     EXPECT_EQ("hello", b);
331   }
332   {
333     auto b = a;
334     EXPECT_TRUE(b.removePrefix("h"));
335     EXPECT_EQ("ello", b);
336   }
337   {
338     auto b = a;
339     EXPECT_TRUE(b.removePrefix('h'));
340     EXPECT_EQ("ello", b);
341   }
342   {
343     auto b = a;
344     EXPECT_TRUE(b.removePrefix("hello"));
345     EXPECT_EQ("", b);
346   }
347   {
348     auto b = a;
349     EXPECT_FALSE(b.removePrefix("hellox"));
350     EXPECT_EQ("hello", b);
351   }
352   {
353     auto b = a;
354     EXPECT_FALSE(b.removePrefix("x"));
355     EXPECT_EQ("hello", b);
356   }
357   {
358     auto b = a;
359     EXPECT_FALSE(b.removePrefix('x'));
360     EXPECT_EQ("hello", b);
361   }
362 }
363
364 TEST(StringPiece, Suffix) {
365   StringPiece a("hello");
366   EXPECT_TRUE(a.endsWith(""));
367   EXPECT_TRUE(a.endsWith("o"));
368   EXPECT_TRUE(a.endsWith('o'));
369   EXPECT_TRUE(a.endsWith("hello"));
370   EXPECT_FALSE(a.endsWith("xhello"));
371   EXPECT_FALSE(a.endsWith("x"));
372   EXPECT_FALSE(a.endsWith('x'));
373
374   EXPECT_TRUE(a.endsWith("", folly::AsciiCaseInsensitive()));
375   EXPECT_TRUE(a.endsWith("o", folly::AsciiCaseInsensitive()));
376   EXPECT_TRUE(a.endsWith("O", folly::AsciiCaseInsensitive()));
377   EXPECT_TRUE(a.endsWith("hello", folly::AsciiCaseInsensitive()));
378   EXPECT_TRUE(a.endsWith("hellO", folly::AsciiCaseInsensitive()));
379   EXPECT_FALSE(a.endsWith("xhello", folly::AsciiCaseInsensitive()));
380   EXPECT_FALSE(a.endsWith("Xhello", folly::AsciiCaseInsensitive()));
381   EXPECT_FALSE(a.endsWith("x", folly::AsciiCaseInsensitive()));
382   EXPECT_FALSE(a.endsWith("X", folly::AsciiCaseInsensitive()));
383
384   {
385     auto b = a;
386     EXPECT_TRUE(b.removeSuffix(""));
387     EXPECT_EQ("hello", b);
388   }
389   {
390     auto b = a;
391     EXPECT_TRUE(b.removeSuffix("o"));
392     EXPECT_EQ("hell", b);
393   }
394   {
395     auto b = a;
396     EXPECT_TRUE(b.removeSuffix('o'));
397     EXPECT_EQ("hell", b);
398   }
399   {
400     auto b = a;
401     EXPECT_TRUE(b.removeSuffix("hello"));
402     EXPECT_EQ("", b);
403   }
404   {
405     auto b = a;
406     EXPECT_FALSE(b.removeSuffix("xhello"));
407     EXPECT_EQ("hello", b);
408   }
409   {
410     auto b = a;
411     EXPECT_FALSE(b.removeSuffix("x"));
412     EXPECT_EQ("hello", b);
413   }
414   {
415     auto b = a;
416     EXPECT_FALSE(b.removeSuffix('x'));
417     EXPECT_EQ("hello", b);
418   }
419 }
420
421 TEST(StringPiece, Equals) {
422   StringPiece a("hello");
423
424   EXPECT_TRUE(a.equals("HELLO", AsciiCaseInsensitive()));
425   EXPECT_FALSE(a.equals("HELLOX", AsciiCaseInsensitive()));
426 }
427
428 TEST(StringPiece, PrefixEmpty) {
429   StringPiece a;
430   EXPECT_TRUE(a.startsWith(""));
431   EXPECT_FALSE(a.startsWith("a"));
432   EXPECT_FALSE(a.startsWith('a'));
433   EXPECT_TRUE(a.removePrefix(""));
434   EXPECT_EQ("", a);
435   EXPECT_FALSE(a.removePrefix("a"));
436   EXPECT_EQ("", a);
437   EXPECT_FALSE(a.removePrefix('a'));
438   EXPECT_EQ("", a);
439 }
440
441 TEST(StringPiece, SuffixEmpty) {
442   StringPiece a;
443   EXPECT_TRUE(a.endsWith(""));
444   EXPECT_FALSE(a.endsWith("a"));
445   EXPECT_FALSE(a.endsWith('a'));
446   EXPECT_TRUE(a.removeSuffix(""));
447   EXPECT_EQ("", a);
448   EXPECT_FALSE(a.removeSuffix("a"));
449   EXPECT_EQ("", a);
450   EXPECT_FALSE(a.removeSuffix('a'));
451   EXPECT_EQ("", a);
452 }
453
454 TEST(StringPiece, erase) {
455   StringPiece a("hello");
456   auto b = a.begin();
457   auto e = b + 1;
458   a.erase(b, e);
459   EXPECT_EQ("ello", a);
460
461   e = a.end();
462   b = e - 1;
463   a.erase(b, e);
464   EXPECT_EQ("ell", a);
465
466   b = a.end() - 1;
467   e = a.end() - 1;
468   EXPECT_THROW(a.erase(b, e), std::out_of_range);
469
470   b = a.begin();
471   e = a.end();
472   a.erase(b, e);
473   EXPECT_EQ("", a);
474
475   a = "hello";
476   b = a.begin();
477   e = b + 2;
478   a.erase(b, e);
479   EXPECT_EQ("llo", a);
480
481   b = a.end() - 2;
482   e = a.end();
483   a.erase(b, e);
484   EXPECT_EQ("l", a);
485
486   a = "      hello  ";
487   boost::algorithm::trim(a);
488   EXPECT_EQ(a, "hello");
489 }
490
491 TEST(StringPiece, split_step_char_delimiter) {
492   //              0         1         2
493   //              012345678901234567890123456
494   auto const s = "this is just  a test string";
495   auto const e = std::next(s, std::strlen(s));
496   EXPECT_EQ('\0', *e);
497
498   folly::StringPiece p(s);
499   EXPECT_EQ(s, p.begin());
500   EXPECT_EQ(e, p.end());
501   EXPECT_EQ(s, p);
502
503   auto x = p.split_step(' ');
504   EXPECT_EQ(std::next(s, 5), p.begin());
505   EXPECT_EQ(e, p.end());
506   EXPECT_EQ("this", x);
507
508   x = p.split_step(' ');
509   EXPECT_EQ(std::next(s, 8), p.begin());
510   EXPECT_EQ(e, p.end());
511   EXPECT_EQ("is", x);
512
513   x = p.split_step('u');
514   EXPECT_EQ(std::next(s, 10), p.begin());
515   EXPECT_EQ(e, p.end());
516   EXPECT_EQ("j", x);
517
518   x = p.split_step(' ');
519   EXPECT_EQ(std::next(s, 13), p.begin());
520   EXPECT_EQ(e, p.end());
521   EXPECT_EQ("st", x);
522
523   x = p.split_step(' ');
524   EXPECT_EQ(std::next(s, 14), p.begin());
525   EXPECT_EQ(e, p.end());
526   EXPECT_EQ("", x);
527
528   x = p.split_step(' ');
529   EXPECT_EQ(std::next(s, 16), p.begin());
530   EXPECT_EQ(e, p.end());
531   EXPECT_EQ("a", x);
532
533   x = p.split_step(' ');
534   EXPECT_EQ(std::next(s, 21), p.begin());
535   EXPECT_EQ(e, p.end());
536   EXPECT_EQ("test", x);
537
538   x = p.split_step(' ');
539   EXPECT_EQ(e, p.begin());
540   EXPECT_EQ(e, p.end());
541   EXPECT_EQ("string", x);
542
543   x = p.split_step(' ');
544   EXPECT_EQ(e, p.begin());
545   EXPECT_EQ(e, p.end());
546   EXPECT_EQ("", x);
547 }
548
549 TEST(StringPiece, split_step_range_delimiter) {
550   //              0         1         2         3
551   //              0123456789012345678901234567890123
552   auto const s = "this  is  just    a   test  string";
553   auto const e = std::next(s, std::strlen(s));
554   EXPECT_EQ('\0', *e);
555
556   folly::StringPiece p(s);
557   EXPECT_EQ(s, p.begin());
558   EXPECT_EQ(e, p.end());
559   EXPECT_EQ(s, p);
560
561   auto x = p.split_step("  ");
562   EXPECT_EQ(std::next(s, 6), p.begin());
563   EXPECT_EQ(e, p.end());
564   EXPECT_EQ("this", x);
565
566   x = p.split_step("  ");
567   EXPECT_EQ(std::next(s, 10), p.begin());
568   EXPECT_EQ(e, p.end());
569   EXPECT_EQ("is", x);
570
571   x = p.split_step("u");
572   EXPECT_EQ(std::next(s, 12), p.begin());
573   EXPECT_EQ(e, p.end());
574   EXPECT_EQ("j", x);
575
576   x = p.split_step("  ");
577   EXPECT_EQ(std::next(s, 16), p.begin());
578   EXPECT_EQ(e, p.end());
579   EXPECT_EQ("st", x);
580
581   x = p.split_step("  ");
582   EXPECT_EQ(std::next(s, 18), p.begin());
583   EXPECT_EQ(e, p.end());
584   EXPECT_EQ("", x);
585
586   x = p.split_step("  ");
587   EXPECT_EQ(std::next(s, 21), p.begin());
588   EXPECT_EQ(e, p.end());
589   EXPECT_EQ("a", x);
590
591   x = p.split_step("  ");
592   EXPECT_EQ(std::next(s, 28), p.begin());
593   EXPECT_EQ(e, p.end());
594   EXPECT_EQ(" test", x);
595
596   x = p.split_step("  ");
597   EXPECT_EQ(e, p.begin());
598   EXPECT_EQ(e, p.end());
599   EXPECT_EQ("string", x);
600
601   x = p.split_step("  ");
602   EXPECT_EQ(e, p.begin());
603   EXPECT_EQ(e, p.end());
604   EXPECT_EQ("", x);
605
606   x = p.split_step(" ");
607   EXPECT_EQ(e, p.begin());
608   EXPECT_EQ(e, p.end());
609   EXPECT_EQ("", x);
610 }
611
612 void split_step_with_process_noop(folly::StringPiece) {}
613
614 TEST(StringPiece, split_step_with_process_char_delimiter) {
615   //              0         1         2
616   //              012345678901234567890123456
617   auto const s = "this is just  a test string";
618   auto const e = std::next(s, std::strlen(s));
619   EXPECT_EQ('\0', *e);
620
621   folly::StringPiece p(s);
622   EXPECT_EQ(s, p.begin());
623   EXPECT_EQ(e, p.end());
624   EXPECT_EQ(s, p);
625
626   EXPECT_EQ(1, (p.split_step(' ', [&](folly::StringPiece x) {
627     EXPECT_EQ(std::next(s, 5), p.begin());
628     EXPECT_EQ(e, p.end());
629     EXPECT_EQ("this", x);
630     return 1;
631   })));
632
633   EXPECT_EQ(2, (p.split_step(' ', [&](folly::StringPiece x) {
634     EXPECT_EQ(std::next(s, 8), p.begin());
635     EXPECT_EQ(e, p.end());
636     EXPECT_EQ("is", x);
637     return 2;
638   })));
639
640   EXPECT_EQ(3, (p.split_step('u', [&](folly::StringPiece x) {
641     EXPECT_EQ(std::next(s, 10), p.begin());
642     EXPECT_EQ(e, p.end());
643     EXPECT_EQ("j", x);
644     return 3;
645   })));
646
647   EXPECT_EQ(4, (p.split_step(' ', [&](folly::StringPiece x) {
648     EXPECT_EQ(std::next(s, 13), p.begin());
649     EXPECT_EQ(e, p.end());
650     EXPECT_EQ("st", x);
651     return 4;
652   })));
653
654   EXPECT_EQ(5, (p.split_step(' ', [&](folly::StringPiece x) {
655     EXPECT_EQ(std::next(s, 14), p.begin());
656     EXPECT_EQ(e, p.end());
657     EXPECT_EQ("", x);
658     return 5;
659   })));
660
661   EXPECT_EQ(6, (p.split_step(' ', [&](folly::StringPiece x) {
662     EXPECT_EQ(std::next(s, 16), p.begin());
663     EXPECT_EQ(e, p.end());
664     EXPECT_EQ("a", x);
665     return 6;
666   })));
667
668   EXPECT_EQ(7, (p.split_step(' ', [&](folly::StringPiece x) {
669     EXPECT_EQ(std::next(s, 21), p.begin());
670     EXPECT_EQ(e, p.end());
671     EXPECT_EQ("test", x);
672     return 7;
673   })));
674
675   EXPECT_EQ(8, (p.split_step(' ', [&](folly::StringPiece x) {
676     EXPECT_EQ(e, p.begin());
677     EXPECT_EQ(e, p.end());
678     EXPECT_EQ("string", x);
679     return 8;
680   })));
681
682   EXPECT_EQ(9, (p.split_step(' ', [&](folly::StringPiece x) {
683     EXPECT_EQ(e, p.begin());
684     EXPECT_EQ(e, p.end());
685     EXPECT_EQ("", x);
686     return 9;
687   })));
688
689   EXPECT_TRUE((std::is_same<
690     void,
691     decltype(p.split_step(' ', split_step_with_process_noop))
692   >::value));
693
694   EXPECT_NO_THROW(p.split_step(' ', split_step_with_process_noop));
695 }
696
697 TEST(StringPiece, split_step_with_process_range_delimiter) {
698   //              0         1         2         3
699   //              0123456789012345678901234567890123
700   auto const s = "this  is  just    a   test  string";
701   auto const e = std::next(s, std::strlen(s));
702   EXPECT_EQ('\0', *e);
703
704   folly::StringPiece p(s);
705   EXPECT_EQ(s, p.begin());
706   EXPECT_EQ(e, p.end());
707   EXPECT_EQ(s, p);
708
709   EXPECT_EQ(1, (p.split_step("  ", [&](folly::StringPiece x) {
710     EXPECT_EQ(std::next(s, 6), p.begin());
711     EXPECT_EQ(e, p.end());
712     EXPECT_EQ("this", x);
713     return 1;
714   })));
715
716   EXPECT_EQ(2, (p.split_step("  ", [&](folly::StringPiece x) {
717     EXPECT_EQ(std::next(s, 10), p.begin());
718     EXPECT_EQ(e, p.end());
719     EXPECT_EQ("is", x);
720     return 2;
721   })));
722
723   EXPECT_EQ(3, (p.split_step("u", [&](folly::StringPiece x) {
724     EXPECT_EQ(std::next(s, 12), p.begin());
725     EXPECT_EQ(e, p.end());
726     EXPECT_EQ("j", x);
727     return 3;
728   })));
729
730   EXPECT_EQ(4, (p.split_step("  ", [&](folly::StringPiece x) {
731     EXPECT_EQ(std::next(s, 16), p.begin());
732     EXPECT_EQ(e, p.end());
733     EXPECT_EQ("st", x);
734     return 4;
735   })));
736
737   EXPECT_EQ(5, (p.split_step("  ", [&](folly::StringPiece x) {
738     EXPECT_EQ(std::next(s, 18), p.begin());
739     EXPECT_EQ(e, p.end());
740     EXPECT_EQ("", x);
741     return 5;
742   })));
743
744   EXPECT_EQ(6, (p.split_step("  ", [&](folly::StringPiece x) {
745     EXPECT_EQ(std::next(s, 21), p.begin());
746     EXPECT_EQ(e, p.end());
747     EXPECT_EQ("a", x);
748     return 6;
749   })));
750
751   EXPECT_EQ(7, (p.split_step("  ", [&](folly::StringPiece x) {
752     EXPECT_EQ(std::next(s, 28), p.begin());
753     EXPECT_EQ(e, p.end());
754     EXPECT_EQ(" test", x);
755     return 7;
756   })));
757
758   EXPECT_EQ(8, (p.split_step("  ", [&](folly::StringPiece x) {
759     EXPECT_EQ(e, p.begin());
760     EXPECT_EQ(e, p.end());
761     EXPECT_EQ("string", x);
762     return 8;
763   })));
764
765   EXPECT_EQ(9, (p.split_step("  ", [&](folly::StringPiece x) {
766     EXPECT_EQ(e, p.begin());
767     EXPECT_EQ(e, p.end());
768     EXPECT_EQ("", x);
769     return 9;
770   })));
771
772   EXPECT_EQ(10, (p.split_step("  ", [&](folly::StringPiece x) {
773     EXPECT_EQ(e, p.begin());
774     EXPECT_EQ(e, p.end());
775     EXPECT_EQ("", x);
776     return 10;
777   })));
778
779   EXPECT_TRUE((std::is_same<
780     void,
781     decltype(p.split_step(' ', split_step_with_process_noop))
782   >::value));
783
784   EXPECT_NO_THROW(p.split_step(' ', split_step_with_process_noop));
785 }
786
787 TEST(StringPiece, split_step_with_process_char_delimiter_additional_args) {
788   //              0         1         2
789   //              012345678901234567890123456
790   auto const s = "this is just  a test string";
791   auto const e = std::next(s, std::strlen(s));
792   auto const delimiter = ' ';
793   EXPECT_EQ('\0', *e);
794
795   folly::StringPiece p(s);
796   EXPECT_EQ(s, p.begin());
797   EXPECT_EQ(e, p.end());
798   EXPECT_EQ(s, p);
799
800   auto const functor = [](
801     folly::StringPiece s,
802     folly::StringPiece expected
803   ) {
804     EXPECT_EQ(expected, s);
805     return expected;
806   };
807
808   auto const checker = [&](folly::StringPiece expected) {
809     EXPECT_EQ(expected, p.split_step(delimiter, functor, expected));
810   };
811
812   checker("this");
813   checker("is");
814   checker("just");
815   checker("");
816   checker("a");
817   checker("test");
818   checker("string");
819   checker("");
820   checker("");
821
822   EXPECT_TRUE(p.empty());
823 }
824
825 TEST(StringPiece, split_step_with_process_range_delimiter_additional_args) {
826   //              0         1         2         3
827   //              0123456789012345678901234567890123
828   auto const s = "this  is  just    a   test  string";
829   auto const e = std::next(s, std::strlen(s));
830   auto const delimiter = "  ";
831   EXPECT_EQ('\0', *e);
832
833   folly::StringPiece p(s);
834   EXPECT_EQ(s, p.begin());
835   EXPECT_EQ(e, p.end());
836   EXPECT_EQ(s, p);
837
838   auto const functor = [](
839     folly::StringPiece s,
840     folly::StringPiece expected
841   ) {
842     EXPECT_EQ(expected, s);
843     return expected;
844   };
845
846   auto const checker = [&](folly::StringPiece expected) {
847     EXPECT_EQ(expected, p.split_step(delimiter, functor, expected));
848   };
849
850   checker("this");
851   checker("is");
852   checker("just");
853   checker("");
854   checker("a");
855   checker(" test");
856   checker("string");
857   checker("");
858   checker("");
859
860   EXPECT_TRUE(p.empty());
861 }
862
863 TEST(StringPiece, NoInvalidImplicitConversions) {
864   struct IsString {
865     bool operator()(folly::Range<int*>) { return false; }
866     bool operator()(folly::StringPiece) { return true; }
867   };
868
869   std::string s = "hello";
870   EXPECT_TRUE(IsString()(s));
871 }
872
873 TEST(qfind, UInt32_Ranges) {
874   vector<uint32_t> a({1, 2, 3, 260, 5});
875   vector<uint32_t> b({2, 3, 4});
876
877   auto a_range = folly::Range<const uint32_t*>(&a[0], a.size());
878   auto b_range = folly::Range<const uint32_t*>(&b[0], b.size());
879
880   EXPECT_EQ(qfind(a_range, b_range), string::npos);
881
882   a[3] = 4;
883   EXPECT_EQ(qfind(a_range, b_range), 1);
884 }
885
886 template <typename NeedleFinder>
887 class NeedleFinderTest : public ::testing::Test {
888  public:
889   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
890     return NeedleFinder::find_first_byte_of(haystack, needles);
891   }
892 };
893
894 struct SseNeedleFinder {
895   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
896     // This will only use the SSE version if it is supported on this CPU
897     // (selected using ifunc).
898     return detail::qfind_first_byte_of(haystack, needles);
899   }
900 };
901
902 struct NoSseNeedleFinder {
903   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
904     return detail::qfind_first_byte_of_nosse(haystack, needles);
905   }
906 };
907
908 struct ByteSetNeedleFinder {
909   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
910     return detail::qfind_first_byte_of_byteset(haystack, needles);
911   }
912 };
913
914 typedef ::testing::Types<SseNeedleFinder,
915                          NoSseNeedleFinder,
916                          ByteSetNeedleFinder> NeedleFinders;
917 TYPED_TEST_CASE(NeedleFinderTest, NeedleFinders);
918
919 TYPED_TEST(NeedleFinderTest, Null) {
920   { // null characters in the string
921     string s(10, char(0));
922     s[5] = 'b';
923     string delims("abc");
924     EXPECT_EQ(5, this->find_first_byte_of(s, delims));
925   }
926   { // null characters in delim
927     string s("abc");
928     string delims(10, char(0));
929     delims[3] = 'c';
930     delims[7] = 'b';
931     EXPECT_EQ(1, this->find_first_byte_of(s, delims));
932   }
933   { // range not terminated by null character
934     string buf = "abcdefghijklmnopqrstuvwxyz";
935     StringPiece s(buf.data() + 5, 3);
936     StringPiece delims("z");
937     EXPECT_EQ(string::npos, this->find_first_byte_of(s, delims));
938   }
939 }
940
941 TYPED_TEST(NeedleFinderTest, DelimDuplicates) {
942   string delims(1000, 'b');
943   EXPECT_EQ(1, this->find_first_byte_of("abc", delims));
944   EXPECT_EQ(string::npos, this->find_first_byte_of("ac", delims));
945 }
946
947 TYPED_TEST(NeedleFinderTest, Empty) {
948   string a = "abc";
949   string b = "";
950   EXPECT_EQ(string::npos, this->find_first_byte_of(a, b));
951   EXPECT_EQ(string::npos, this->find_first_byte_of(b, a));
952   EXPECT_EQ(string::npos, this->find_first_byte_of(b, b));
953 }
954
955 TYPED_TEST(NeedleFinderTest, Unaligned) {
956   // works correctly even if input buffers are not 16-byte aligned
957   string s = "0123456789ABCDEFGH";
958   for (size_t i = 0; i < s.size(); ++i) {
959     StringPiece a(s.c_str() + i);
960     for (size_t j = 0; j < s.size(); ++j) {
961       StringPiece b(s.c_str() + j);
962       EXPECT_EQ((i > j) ? 0 : j - i, this->find_first_byte_of(a, b));
963     }
964   }
965 }
966
967 // for some algorithms (specifically those that create a set of needles),
968 // we check for the edge-case of _all_ possible needles being sought.
969 TYPED_TEST(NeedleFinderTest, Needles256) {
970   string needles;
971   const auto minValue = std::numeric_limits<StringPiece::value_type>::min();
972   const auto maxValue = std::numeric_limits<StringPiece::value_type>::max();
973   // make the size ~big to avoid any edge-case branches for tiny haystacks
974   const int haystackSize = 50;
975   for (int i = minValue; i <= maxValue; i++) { // <=
976     needles.push_back(i);
977   }
978   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
979   for (int i = minValue; i <= maxValue; i++) {
980     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
981   }
982
983   needles.append("these are redundant characters");
984   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
985   for (int i = minValue; i <= maxValue; i++) {
986     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
987   }
988 }
989
990 TYPED_TEST(NeedleFinderTest, Base) {
991   for (size_t i = 0; i < 32; ++i) {
992     for (int j = 0; j < 32; ++j) {
993       string s = string(i, 'X') + "abca" + string(i, 'X');
994       string delims = string(j, 'Y') + "a" + string(j, 'Y');
995       EXPECT_EQ(i, this->find_first_byte_of(s, delims));
996     }
997   }
998 }
999
1000 const size_t kPageSize = 4096;
1001 // Updates contents so that any read accesses past the last byte will
1002 // cause a SIGSEGV.  It accomplishes this by changing access to the page that
1003 // begins immediately after the end of the contents (as allocators and mmap()
1004 // all operate on page boundaries, this is a reasonable assumption).
1005 // This function will also initialize buf, which caller must free().
1006 void createProtectedBuf(StringPiece& contents, char** buf) {
1007   ASSERT_LE(contents.size(), kPageSize);
1008   const size_t kSuccess = 0;
1009   char* pageAlignedBuf = (char*)aligned_malloc(2 * kPageSize, kPageSize);
1010   if (pageAlignedBuf == nullptr) {
1011     ASSERT_FALSE(true);
1012   }
1013   // Protect the page after the first full page-aligned region of the
1014   // malloc'ed buffer
1015   mprotect(pageAlignedBuf + kPageSize, kPageSize, PROT_NONE);
1016   size_t newBegin = kPageSize - contents.size();
1017   memcpy(pageAlignedBuf + newBegin, contents.data(), contents.size());
1018   contents.reset(pageAlignedBuf + newBegin, contents.size());
1019   *buf = pageAlignedBuf;
1020 }
1021
1022 void freeProtectedBuf(char* buf) {
1023   mprotect(buf + kPageSize, kPageSize, PROT_READ | PROT_WRITE);
1024   aligned_free(buf);
1025 }
1026
1027 TYPED_TEST(NeedleFinderTest, NoSegFault) {
1028   const string base = string(32, 'a') + string("b");
1029   const string delims = string(32, 'c') + string("b");
1030   for (int i = 0; i <= 32; i++) {
1031     for (int j = 0; j <= 33; j++) {
1032       for (int shouldFind = 0; shouldFind <= 1; ++shouldFind) {
1033         StringPiece s1(base);
1034         s1.advance(i);
1035         ASSERT_TRUE(!s1.empty());
1036         if (!shouldFind) {
1037           s1.pop_back();
1038         }
1039         StringPiece s2(delims);
1040         s2.advance(j);
1041         char* buf1;
1042         char* buf2;
1043         createProtectedBuf(s1, &buf1);
1044         createProtectedBuf(s2, &buf2);
1045         // printf("s1: '%s' (%ld) \ts2: '%s' (%ld)\n",
1046         //        string(s1.data(), s1.size()).c_str(), s1.size(),
1047         //        string(s2.data(), s2.size()).c_str(), s2.size());
1048         auto r1 = this->find_first_byte_of(s1, s2);
1049         auto f1 = std::find_first_of(s1.begin(), s1.end(),
1050                                      s2.begin(), s2.end());
1051         auto e1 = (f1 == s1.end()) ? StringPiece::npos : f1 - s1.begin();
1052         EXPECT_EQ(r1, e1);
1053         auto r2 = this->find_first_byte_of(s2, s1);
1054         auto f2 = std::find_first_of(s2.begin(), s2.end(),
1055                                      s1.begin(), s1.end());
1056         auto e2 = (f2 == s2.end()) ? StringPiece::npos : f2 - s2.begin();
1057         EXPECT_EQ(r2, e2);
1058         freeProtectedBuf(buf1);
1059         freeProtectedBuf(buf2);
1060       }
1061     }
1062   }
1063 }
1064
1065 TEST(NonConstTest, StringPiece) {
1066   std::string hello("hello");
1067   MutableStringPiece sp(&hello.front(), hello.size());
1068   sp[0] = 'x';
1069   EXPECT_EQ("xello", hello);
1070   {
1071     StringPiece s(sp);
1072     EXPECT_EQ("xello", s);
1073   }
1074   {
1075     ByteRange r1(sp);
1076     MutableByteRange r2(sp);
1077   }
1078 }
1079
1080 // Similar to the begin() template functions, but instread of returing
1081 // an iterator, return a pointer to data.
1082 template <class Container>
1083 typename Container::value_type* dataPtr(Container& cont) {
1084   // NOTE: &cont[0] is undefined if cont is empty (it creates a
1085   // reference to nullptr - which is not dereferenced, but still UBSAN).
1086   return cont.data();
1087 }
1088 template <class T, size_t N>
1089 constexpr T* dataPtr(T (&arr)[N]) noexcept {
1090   return &arr[0];
1091 }
1092
1093 template<class C>
1094 void testRangeFunc(C&& x, size_t n) {
1095   const auto& cx = x;
1096   // type, conversion checks
1097   Range<int*> r1 = range(std::forward<C>(x));
1098   Range<const int*> r2 = range(std::forward<C>(x));
1099   Range<const int*> r3 = range(cx);
1100   Range<const int*> r5 = range(std::move(cx));
1101   EXPECT_EQ(r1.begin(), dataPtr(x));
1102   EXPECT_EQ(r1.end(), dataPtr(x) + n);
1103   EXPECT_EQ(n, r1.size());
1104   EXPECT_EQ(n, r2.size());
1105   EXPECT_EQ(n, r3.size());
1106   EXPECT_EQ(n, r5.size());
1107 }
1108
1109 TEST(RangeFunc, Vector) {
1110   std::vector<int> x;
1111   testRangeFunc(x, 0);
1112   x.push_back(2);
1113   testRangeFunc(x, 1);
1114   testRangeFunc(std::vector<int>{1, 2}, 2);
1115 }
1116
1117 TEST(RangeFunc, Array) {
1118   std::array<int, 3> x;
1119   testRangeFunc(x, 3);
1120 }
1121
1122 TEST(RangeFunc, CArray) {
1123   int x[] {1, 2, 3, 4};
1124   testRangeFunc(x, 4);
1125 }
1126
1127 TEST(RangeFunc, ConstexprCArray) {
1128   static constexpr const int numArray[4] = {3, 17, 1, 9};
1129   constexpr const auto numArrayRange = range(numArray);
1130   EXPECT_EQ(17, numArrayRange[1]);
1131   constexpr const auto numArrayRangeSize = numArrayRange.size();
1132   EXPECT_EQ(4, numArrayRangeSize);
1133 }
1134
1135 TEST(RangeFunc, ConstexprStdArray) {
1136   static constexpr const std::array<int, 4> numArray = {{3, 17, 1, 9}};
1137   constexpr const auto numArrayRange = range(numArray);
1138   EXPECT_EQ(17, numArrayRange[1]);
1139   constexpr const auto numArrayRangeSize = numArrayRange.size();
1140   EXPECT_EQ(4, numArrayRangeSize);
1141 }
1142
1143 TEST(RangeFunc, ConstexprStdArrayZero) {
1144   static constexpr const std::array<int, 0> numArray = {};
1145   constexpr const auto numArrayRange = range(numArray);
1146   constexpr const auto numArrayRangeSize = numArrayRange.size();
1147   EXPECT_EQ(0, numArrayRangeSize);
1148 }
1149
1150 TEST(RangeFunc, ConstexprIteratorPair) {
1151   static constexpr const int numArray[4] = {3, 17, 1, 9};
1152   constexpr const auto numPtr = static_cast<const int*>(numArray);
1153   constexpr const auto numIterRange = range(numPtr + 1, numPtr + 3);
1154   EXPECT_EQ(1, numIterRange[1]);
1155   constexpr const auto numIterRangeSize = numIterRange.size();
1156   EXPECT_EQ(2, numIterRangeSize);
1157 }
1158
1159 TEST(RangeFunc, ConstexprCollection) {
1160   class IntCollection {
1161    public:
1162     constexpr IntCollection(const int* d, size_t s) : data_(d), size_(s) {}
1163     constexpr const int* data() const {
1164       return data_;
1165     }
1166     constexpr size_t size() const {
1167       return size_;
1168     }
1169
1170    private:
1171     const int* data_;
1172     size_t size_;
1173   };
1174   static constexpr const int numArray[4] = {3, 17, 1, 9};
1175   constexpr const auto numPtr = static_cast<const int*>(numArray);
1176   constexpr const auto numColl = IntCollection(numPtr + 1, 2);
1177   constexpr const auto numCollRange = range(numColl);
1178   EXPECT_EQ(1, numCollRange[1]);
1179   constexpr const auto numCollRangeSize = numCollRange.size();
1180   EXPECT_EQ(2, numCollRangeSize);
1181 }
1182
1183 std::string get_rand_str(size_t size,
1184                          std::uniform_int_distribution<>& dist,
1185                          std::mt19937& gen) {
1186   std::string ret(size, '\0');
1187   for (size_t i = 0; i < size; ++i) {
1188     ret[i] = static_cast<char>(dist(gen));
1189   }
1190
1191   return ret;
1192 }
1193
1194 namespace folly {
1195 bool operator==(MutableStringPiece mp, StringPiece sp) {
1196   return mp.compare(sp) == 0;
1197 }
1198
1199 bool operator==(StringPiece sp, MutableStringPiece mp) {
1200   return mp.compare(sp) == 0;
1201 }
1202 }
1203
1204 TEST(ReplaceAt, exhaustiveTest) {
1205   char input[] = "this is nice and long input";
1206   auto msp = MutableStringPiece(input);
1207   auto str = std::string(input);
1208   std::random_device rd;
1209   std::mt19937 gen(rd());
1210   std::uniform_int_distribution<> dist('a', 'z');
1211
1212   for (int i=0; i < 100; ++i) {
1213     for (size_t j = 1; j <= msp.size(); ++j) {
1214       auto replacement = get_rand_str(j, dist, gen);
1215       for (size_t pos = 0; pos < msp.size() - j; ++pos) {
1216         msp.replaceAt(pos, replacement);
1217         str.replace(pos, replacement.size(), replacement);
1218         EXPECT_EQ(msp.compare(str), 0);
1219       }
1220     }
1221   }
1222
1223   // too far
1224   EXPECT_EQ(msp.replaceAt(msp.size() - 2, StringPiece("meh")), false);
1225 }
1226
1227 TEST(ReplaceAll, basicTest) {
1228   char input[] = "this is nice and long input";
1229   auto orig = std::string(input);
1230   auto msp = MutableStringPiece(input);
1231
1232   EXPECT_EQ(msp.replaceAll("is", "si"), 2);
1233   EXPECT_EQ("thsi si nice and long input", msp);
1234   EXPECT_EQ(msp.replaceAll("si", "is"), 2);
1235   EXPECT_EQ(msp, orig);
1236
1237   EXPECT_EQ(msp.replaceAll("abcd", "efgh"), 0); // nothing to replace
1238   EXPECT_EQ(msp, orig);
1239
1240   // at the very beginning
1241   EXPECT_EQ(msp.replaceAll("this", "siht"), 1);
1242   EXPECT_EQ("siht is nice and long input", msp);
1243   EXPECT_EQ(msp.replaceAll("siht", "this"), 1);
1244   EXPECT_EQ(msp, orig);
1245
1246   // at the very end
1247   EXPECT_EQ(msp.replaceAll("input", "soput"), 1);
1248   EXPECT_EQ("this is nice and long soput", msp);
1249   EXPECT_EQ(msp.replaceAll("soput", "input"), 1);
1250   EXPECT_EQ(msp, orig);
1251
1252   // all spaces
1253   EXPECT_EQ(msp.replaceAll(" ", "@"), 5);
1254   EXPECT_EQ("this@is@nice@and@long@input", msp);
1255   EXPECT_EQ(msp.replaceAll("@", " "), 5);
1256   EXPECT_EQ(msp, orig);
1257 }
1258
1259 TEST(ReplaceAll, randomTest) {
1260   char input[] = "abcdefghijklmnoprstuwqz"; // no pattern repeata inside
1261   auto orig = std::string(input);
1262   auto msp = MutableStringPiece(input);
1263
1264   std::random_device rd;
1265   std::mt19937 gen(rd());
1266   std::uniform_int_distribution<> dist('A', 'Z');
1267
1268   for (int i=0; i < 100; ++i) {
1269     for (size_t j = 1; j <= orig.size(); ++j) {
1270       auto replacement = get_rand_str(j, dist, gen);
1271       for (size_t pos = 0; pos < msp.size() - j; ++pos) {
1272         auto piece = orig.substr(pos, j);
1273         EXPECT_EQ(msp.replaceAll(piece, replacement), 1);
1274         EXPECT_EQ(msp.find(replacement), pos);
1275         EXPECT_EQ(msp.replaceAll(replacement, piece), 1);
1276         EXPECT_EQ(msp, orig);
1277       }
1278     }
1279   }
1280 }
1281
1282 TEST(ReplaceAll, BadArg) {
1283   int count = 0;
1284   auto fst = "longer";
1285   auto snd = "small";
1286   char input[] = "meh meh meh";
1287   auto all =  MutableStringPiece(input);
1288
1289   try {
1290     all.replaceAll(fst, snd);
1291   } catch (std::invalid_argument&) {
1292     ++count;
1293   }
1294
1295   try {
1296     all.replaceAll(snd, fst);
1297   } catch (std::invalid_argument&) {
1298     ++count;
1299   }
1300
1301   EXPECT_EQ(count, 2);
1302 }
1303
1304 TEST(Range, Constructors) {
1305   vector<int> c = {1, 2, 3};
1306   typedef Range<vector<int>::iterator> RangeType;
1307   typedef Range<vector<int>::const_iterator> ConstRangeType;
1308   RangeType cr(c.begin(), c.end());
1309   auto subpiece1 = ConstRangeType(cr, 1, 5);
1310   auto subpiece2 = ConstRangeType(cr, 1);
1311   EXPECT_EQ(subpiece1.size(), 2);
1312   EXPECT_EQ(subpiece1.begin(), subpiece2.begin());
1313   EXPECT_EQ(subpiece1.end(), subpiece2.end());
1314 }
1315
1316 TEST(Range, ArrayConstructors) {
1317   auto charArray = std::array<char, 4>{{'t', 'e', 's', 't'}};
1318   auto constCharArray = std::array<char, 6>{{'f', 'o', 'o', 'b', 'a', 'r'}};
1319   auto emptyArray = std::array<char, 0>{};
1320
1321   auto sp1 = StringPiece{charArray};
1322   EXPECT_EQ(4, sp1.size());
1323   EXPECT_EQ(charArray.data(), sp1.data());
1324
1325   auto sp2 = StringPiece(constCharArray);
1326   EXPECT_EQ(6, sp2.size());
1327   EXPECT_EQ(constCharArray.data(), sp2.data());
1328
1329   auto msp = MutableStringPiece(charArray);
1330   EXPECT_EQ(4, msp.size());
1331   EXPECT_EQ(charArray.data(), msp.data());
1332
1333   auto esp = StringPiece(emptyArray);
1334   EXPECT_EQ(0, esp.size());
1335   EXPECT_EQ(nullptr, esp.data());
1336
1337   auto emsp = MutableStringPiece(emptyArray);
1338   EXPECT_EQ(0, emsp.size());
1339   EXPECT_EQ(nullptr, emsp.data());
1340
1341   static constexpr std::array<int, 4> numArray = {{3, 17, 1, 9}};
1342   constexpr auto numRange = Range<const int*>{numArray};
1343   EXPECT_EQ(17, numRange[1]);
1344
1345   static constexpr std::array<int, 0> emptyNumArray{};
1346   constexpr auto emptyNumRange = Range<const int*>{emptyNumArray};
1347   EXPECT_EQ(0, emptyNumRange.size());
1348 }
1349
1350 TEST(Range, ConstexprAccessors) {
1351   constexpr StringPiece piece = range("hello");
1352   static_assert(piece.size() == 6u, "");
1353   static_assert(piece.end() - piece.begin() == 6u, "");
1354   static_assert(piece.data() == piece.begin(), "");
1355   static_assert(piece.start() == piece.begin(), "");
1356   static_assert(piece.cbegin() == piece.begin(), "");
1357   static_assert(piece.cend() == piece.end(), "");
1358   static_assert(*piece.begin() == 'h', "");
1359   static_assert(*(piece.end() - 1) == '\0', "");
1360 }