Sort #include lines
[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(static_cast<const void*>(a.begin()),
269             static_cast<const void*>(b.begin()));
270   EXPECT_EQ(static_cast<const void*>(a.end()),
271             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((std::is_same<
691     void,
692     decltype(p.split_step(' ', split_step_with_process_noop))
693   >::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((std::is_same<
781     void,
782     decltype(p.split_step(' ', split_step_with_process_noop))
783   >::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 = [](
802     folly::StringPiece s,
803     folly::StringPiece expected
804   ) {
805     EXPECT_EQ(expected, s);
806     return expected;
807   };
808
809   auto const checker = [&](folly::StringPiece expected) {
810     EXPECT_EQ(expected, p.split_step(delimiter, functor, expected));
811   };
812
813   checker("this");
814   checker("is");
815   checker("just");
816   checker("");
817   checker("a");
818   checker("test");
819   checker("string");
820   checker("");
821   checker("");
822
823   EXPECT_TRUE(p.empty());
824 }
825
826 TEST(StringPiece, split_step_with_process_range_delimiter_additional_args) {
827   //              0         1         2         3
828   //              0123456789012345678901234567890123
829   auto const s = "this  is  just    a   test  string";
830   auto const e = std::next(s, std::strlen(s));
831   auto const delimiter = "  ";
832   EXPECT_EQ('\0', *e);
833
834   folly::StringPiece p(s);
835   EXPECT_EQ(s, p.begin());
836   EXPECT_EQ(e, p.end());
837   EXPECT_EQ(s, p);
838
839   auto const functor = [](
840     folly::StringPiece s,
841     folly::StringPiece expected
842   ) {
843     EXPECT_EQ(expected, s);
844     return expected;
845   };
846
847   auto const checker = [&](folly::StringPiece expected) {
848     EXPECT_EQ(expected, p.split_step(delimiter, functor, expected));
849   };
850
851   checker("this");
852   checker("is");
853   checker("just");
854   checker("");
855   checker("a");
856   checker(" test");
857   checker("string");
858   checker("");
859   checker("");
860
861   EXPECT_TRUE(p.empty());
862 }
863
864 TEST(StringPiece, NoInvalidImplicitConversions) {
865   struct IsString {
866     bool operator()(folly::Range<int*>) { return false; }
867     bool operator()(folly::StringPiece) { return true; }
868   };
869
870   std::string s = "hello";
871   EXPECT_TRUE(IsString()(s));
872 }
873
874 TEST(qfind, UInt32_Ranges) {
875   vector<uint32_t> a({1, 2, 3, 260, 5});
876   vector<uint32_t> b({2, 3, 4});
877
878   auto a_range = folly::Range<const uint32_t*>(&a[0], a.size());
879   auto b_range = folly::Range<const uint32_t*>(&b[0], b.size());
880
881   EXPECT_EQ(qfind(a_range, b_range), string::npos);
882
883   a[3] = 4;
884   EXPECT_EQ(qfind(a_range, b_range), 1);
885 }
886
887 template <typename NeedleFinder>
888 class NeedleFinderTest : public ::testing::Test {
889  public:
890   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
891     return NeedleFinder::find_first_byte_of(haystack, needles);
892   }
893 };
894
895 struct SseNeedleFinder {
896   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
897     // This will only use the SSE version if it is supported on this CPU
898     // (selected using ifunc).
899     return detail::qfind_first_byte_of(haystack, needles);
900   }
901 };
902
903 struct NoSseNeedleFinder {
904   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
905     return detail::qfind_first_byte_of_nosse(haystack, needles);
906   }
907 };
908
909 struct ByteSetNeedleFinder {
910   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
911     return detail::qfind_first_byte_of_byteset(haystack, needles);
912   }
913 };
914
915 typedef ::testing::Types<SseNeedleFinder,
916                          NoSseNeedleFinder,
917                          ByteSetNeedleFinder> NeedleFinders;
918 TYPED_TEST_CASE(NeedleFinderTest, NeedleFinders);
919
920 TYPED_TEST(NeedleFinderTest, Null) {
921   { // null characters in the string
922     string s(10, char(0));
923     s[5] = 'b';
924     string delims("abc");
925     EXPECT_EQ(5, this->find_first_byte_of(s, delims));
926   }
927   { // null characters in delim
928     string s("abc");
929     string delims(10, char(0));
930     delims[3] = 'c';
931     delims[7] = 'b';
932     EXPECT_EQ(1, this->find_first_byte_of(s, delims));
933   }
934   { // range not terminated by null character
935     string buf = "abcdefghijklmnopqrstuvwxyz";
936     StringPiece s(buf.data() + 5, 3);
937     StringPiece delims("z");
938     EXPECT_EQ(string::npos, this->find_first_byte_of(s, delims));
939   }
940 }
941
942 TYPED_TEST(NeedleFinderTest, DelimDuplicates) {
943   string delims(1000, 'b');
944   EXPECT_EQ(1, this->find_first_byte_of("abc", delims));
945   EXPECT_EQ(string::npos, this->find_first_byte_of("ac", delims));
946 }
947
948 TYPED_TEST(NeedleFinderTest, Empty) {
949   string a = "abc";
950   string b = "";
951   EXPECT_EQ(string::npos, this->find_first_byte_of(a, b));
952   EXPECT_EQ(string::npos, this->find_first_byte_of(b, a));
953   EXPECT_EQ(string::npos, this->find_first_byte_of(b, b));
954 }
955
956 TYPED_TEST(NeedleFinderTest, Unaligned) {
957   // works correctly even if input buffers are not 16-byte aligned
958   string s = "0123456789ABCDEFGH";
959   for (size_t i = 0; i < s.size(); ++i) {
960     StringPiece a(s.c_str() + i);
961     for (size_t j = 0; j < s.size(); ++j) {
962       StringPiece b(s.c_str() + j);
963       EXPECT_EQ((i > j) ? 0 : j - i, this->find_first_byte_of(a, b));
964     }
965   }
966 }
967
968 // for some algorithms (specifically those that create a set of needles),
969 // we check for the edge-case of _all_ possible needles being sought.
970 TYPED_TEST(NeedleFinderTest, Needles256) {
971   string needles;
972   const auto minValue = std::numeric_limits<StringPiece::value_type>::min();
973   const auto maxValue = std::numeric_limits<StringPiece::value_type>::max();
974   // make the size ~big to avoid any edge-case branches for tiny haystacks
975   const int haystackSize = 50;
976   for (int i = minValue; i <= maxValue; i++) { // <=
977     needles.push_back(i);
978   }
979   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
980   for (int i = minValue; i <= maxValue; i++) {
981     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
982   }
983
984   needles.append("these are redundant characters");
985   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
986   for (int i = minValue; i <= maxValue; i++) {
987     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
988   }
989 }
990
991 TYPED_TEST(NeedleFinderTest, Base) {
992   for (size_t i = 0; i < 32; ++i) {
993     for (int j = 0; j < 32; ++j) {
994       string s = string(i, 'X') + "abca" + string(i, 'X');
995       string delims = string(j, 'Y') + "a" + string(j, 'Y');
996       EXPECT_EQ(i, this->find_first_byte_of(s, delims));
997     }
998   }
999 }
1000
1001 const size_t kPageSize = 4096;
1002 // Updates contents so that any read accesses past the last byte will
1003 // cause a SIGSEGV.  It accomplishes this by changing access to the page that
1004 // begins immediately after the end of the contents (as allocators and mmap()
1005 // all operate on page boundaries, this is a reasonable assumption).
1006 // This function will also initialize buf, which caller must free().
1007 void createProtectedBuf(StringPiece& contents, char** buf) {
1008   ASSERT_LE(contents.size(), kPageSize);
1009   const size_t kSuccess = 0;
1010   char* pageAlignedBuf = (char*)aligned_malloc(2 * kPageSize, kPageSize);
1011   if (pageAlignedBuf == nullptr) {
1012     ASSERT_FALSE(true);
1013   }
1014   // Protect the page after the first full page-aligned region of the
1015   // malloc'ed buffer
1016   mprotect(pageAlignedBuf + kPageSize, kPageSize, PROT_NONE);
1017   size_t newBegin = kPageSize - contents.size();
1018   memcpy(pageAlignedBuf + newBegin, contents.data(), contents.size());
1019   contents.reset(pageAlignedBuf + newBegin, contents.size());
1020   *buf = pageAlignedBuf;
1021 }
1022
1023 void freeProtectedBuf(char* buf) {
1024   mprotect(buf + kPageSize, kPageSize, PROT_READ | PROT_WRITE);
1025   aligned_free(buf);
1026 }
1027
1028 TYPED_TEST(NeedleFinderTest, NoSegFault) {
1029   const string base = string(32, 'a') + string("b");
1030   const string delims = string(32, 'c') + string("b");
1031   for (int i = 0; i <= 32; i++) {
1032     for (int j = 0; j <= 33; j++) {
1033       for (int shouldFind = 0; shouldFind <= 1; ++shouldFind) {
1034         StringPiece s1(base);
1035         s1.advance(i);
1036         ASSERT_TRUE(!s1.empty());
1037         if (!shouldFind) {
1038           s1.pop_back();
1039         }
1040         StringPiece s2(delims);
1041         s2.advance(j);
1042         char* buf1;
1043         char* buf2;
1044         createProtectedBuf(s1, &buf1);
1045         createProtectedBuf(s2, &buf2);
1046         // printf("s1: '%s' (%ld) \ts2: '%s' (%ld)\n",
1047         //        string(s1.data(), s1.size()).c_str(), s1.size(),
1048         //        string(s2.data(), s2.size()).c_str(), s2.size());
1049         auto r1 = this->find_first_byte_of(s1, s2);
1050         auto f1 = std::find_first_of(s1.begin(), s1.end(),
1051                                      s2.begin(), s2.end());
1052         auto e1 = (f1 == s1.end()) ? StringPiece::npos : f1 - s1.begin();
1053         EXPECT_EQ(r1, e1);
1054         auto r2 = this->find_first_byte_of(s2, s1);
1055         auto f2 = std::find_first_of(s2.begin(), s2.end(),
1056                                      s1.begin(), s1.end());
1057         auto e2 = (f2 == s2.end()) ? StringPiece::npos : f2 - s2.begin();
1058         EXPECT_EQ(r2, e2);
1059         freeProtectedBuf(buf1);
1060         freeProtectedBuf(buf2);
1061       }
1062     }
1063   }
1064 }
1065
1066 TEST(NonConstTest, StringPiece) {
1067   std::string hello("hello");
1068   MutableStringPiece sp(&hello.front(), hello.size());
1069   sp[0] = 'x';
1070   EXPECT_EQ("xello", hello);
1071   {
1072     StringPiece s(sp);
1073     EXPECT_EQ("xello", s);
1074   }
1075   {
1076     ByteRange r1(sp);
1077     MutableByteRange r2(sp);
1078   }
1079 }
1080
1081 // Similar to the begin() template functions, but instread of returing
1082 // an iterator, return a pointer to data.
1083 template <class Container>
1084 typename Container::value_type* dataPtr(Container& cont) {
1085   // NOTE: &cont[0] is undefined if cont is empty (it creates a
1086   // reference to nullptr - which is not dereferenced, but still UBSAN).
1087   return cont.data();
1088 }
1089 template <class T, size_t N>
1090 constexpr T* dataPtr(T (&arr)[N]) noexcept {
1091   return &arr[0];
1092 }
1093
1094 template<class C>
1095 void testRangeFunc(C&& x, size_t n) {
1096   const auto& cx = x;
1097   // type, conversion checks
1098   Range<int*> r1 = range(std::forward<C>(x));
1099   Range<const int*> r2 = range(std::forward<C>(x));
1100   Range<const int*> r3 = range(cx);
1101   Range<const int*> r5 = range(std::move(cx));
1102   EXPECT_EQ(r1.begin(), dataPtr(x));
1103   EXPECT_EQ(r1.end(), dataPtr(x) + n);
1104   EXPECT_EQ(n, r1.size());
1105   EXPECT_EQ(n, r2.size());
1106   EXPECT_EQ(n, r3.size());
1107   EXPECT_EQ(n, r5.size());
1108 }
1109
1110 TEST(RangeFunc, Vector) {
1111   std::vector<int> x;
1112   testRangeFunc(x, 0);
1113   x.push_back(2);
1114   testRangeFunc(x, 1);
1115   testRangeFunc(std::vector<int>{1, 2}, 2);
1116 }
1117
1118 TEST(RangeFunc, Array) {
1119   std::array<int, 3> x;
1120   testRangeFunc(x, 3);
1121 }
1122
1123 TEST(RangeFunc, CArray) {
1124   int x[] {1, 2, 3, 4};
1125   testRangeFunc(x, 4);
1126 }
1127
1128 TEST(RangeFunc, ConstexprCArray) {
1129   static constexpr const int numArray[4] = {3, 17, 1, 9};
1130   constexpr const auto numArrayRange = range(numArray);
1131   EXPECT_EQ(17, numArrayRange[1]);
1132   constexpr const auto numArrayRangeSize = numArrayRange.size();
1133   EXPECT_EQ(4, numArrayRangeSize);
1134 }
1135
1136 TEST(RangeFunc, ConstexprStdArray) {
1137   static constexpr const std::array<int, 4> numArray = {{3, 17, 1, 9}};
1138   constexpr const auto numArrayRange = range(numArray);
1139   EXPECT_EQ(17, numArrayRange[1]);
1140   constexpr const auto numArrayRangeSize = numArrayRange.size();
1141   EXPECT_EQ(4, numArrayRangeSize);
1142 }
1143
1144 TEST(RangeFunc, ConstexprStdArrayZero) {
1145   static constexpr const std::array<int, 0> numArray = {};
1146   constexpr const auto numArrayRange = range(numArray);
1147   constexpr const auto numArrayRangeSize = numArrayRange.size();
1148   EXPECT_EQ(0, numArrayRangeSize);
1149 }
1150
1151 TEST(RangeFunc, ConstexprIteratorPair) {
1152   static constexpr const int numArray[4] = {3, 17, 1, 9};
1153   constexpr const auto numPtr = static_cast<const int*>(numArray);
1154   constexpr const auto numIterRange = range(numPtr + 1, numPtr + 3);
1155   EXPECT_EQ(1, numIterRange[1]);
1156   constexpr const auto numIterRangeSize = numIterRange.size();
1157   EXPECT_EQ(2, numIterRangeSize);
1158 }
1159
1160 TEST(RangeFunc, ConstexprCollection) {
1161   class IntCollection {
1162    public:
1163     constexpr IntCollection(const int* d, size_t s) : data_(d), size_(s) {}
1164     constexpr const int* data() const {
1165       return data_;
1166     }
1167     constexpr size_t size() const {
1168       return size_;
1169     }
1170
1171    private:
1172     const int* data_;
1173     size_t size_;
1174   };
1175   static constexpr const int numArray[4] = {3, 17, 1, 9};
1176   constexpr const auto numPtr = static_cast<const int*>(numArray);
1177   constexpr const auto numColl = IntCollection(numPtr + 1, 2);
1178   constexpr const auto numCollRange = range(numColl);
1179   EXPECT_EQ(1, numCollRange[1]);
1180   constexpr const auto numCollRangeSize = numCollRange.size();
1181   EXPECT_EQ(2, numCollRangeSize);
1182 }
1183
1184 std::string get_rand_str(size_t size,
1185                          std::uniform_int_distribution<>& dist,
1186                          std::mt19937& gen) {
1187   std::string ret(size, '\0');
1188   for (size_t i = 0; i < size; ++i) {
1189     ret[i] = static_cast<char>(dist(gen));
1190   }
1191
1192   return ret;
1193 }
1194
1195 namespace folly {
1196 bool operator==(MutableStringPiece mp, StringPiece sp) {
1197   return mp.compare(sp) == 0;
1198 }
1199
1200 bool operator==(StringPiece sp, MutableStringPiece mp) {
1201   return mp.compare(sp) == 0;
1202 }
1203 }
1204
1205 TEST(ReplaceAt, exhaustiveTest) {
1206   char input[] = "this is nice and long input";
1207   auto msp = MutableStringPiece(input);
1208   auto str = std::string(input);
1209   std::random_device rd;
1210   std::mt19937 gen(rd());
1211   std::uniform_int_distribution<> dist('a', 'z');
1212
1213   for (int i=0; i < 100; ++i) {
1214     for (size_t j = 1; j <= msp.size(); ++j) {
1215       auto replacement = get_rand_str(j, dist, gen);
1216       for (size_t pos = 0; pos < msp.size() - j; ++pos) {
1217         msp.replaceAt(pos, replacement);
1218         str.replace(pos, replacement.size(), replacement);
1219         EXPECT_EQ(msp.compare(str), 0);
1220       }
1221     }
1222   }
1223
1224   // too far
1225   EXPECT_EQ(msp.replaceAt(msp.size() - 2, StringPiece("meh")), false);
1226 }
1227
1228 TEST(ReplaceAll, basicTest) {
1229   char input[] = "this is nice and long input";
1230   auto orig = std::string(input);
1231   auto msp = MutableStringPiece(input);
1232
1233   EXPECT_EQ(msp.replaceAll("is", "si"), 2);
1234   EXPECT_EQ("thsi si nice and long input", msp);
1235   EXPECT_EQ(msp.replaceAll("si", "is"), 2);
1236   EXPECT_EQ(msp, orig);
1237
1238   EXPECT_EQ(msp.replaceAll("abcd", "efgh"), 0); // nothing to replace
1239   EXPECT_EQ(msp, orig);
1240
1241   // at the very beginning
1242   EXPECT_EQ(msp.replaceAll("this", "siht"), 1);
1243   EXPECT_EQ("siht is nice and long input", msp);
1244   EXPECT_EQ(msp.replaceAll("siht", "this"), 1);
1245   EXPECT_EQ(msp, orig);
1246
1247   // at the very end
1248   EXPECT_EQ(msp.replaceAll("input", "soput"), 1);
1249   EXPECT_EQ("this is nice and long soput", msp);
1250   EXPECT_EQ(msp.replaceAll("soput", "input"), 1);
1251   EXPECT_EQ(msp, orig);
1252
1253   // all spaces
1254   EXPECT_EQ(msp.replaceAll(" ", "@"), 5);
1255   EXPECT_EQ("this@is@nice@and@long@input", msp);
1256   EXPECT_EQ(msp.replaceAll("@", " "), 5);
1257   EXPECT_EQ(msp, orig);
1258 }
1259
1260 TEST(ReplaceAll, randomTest) {
1261   char input[] = "abcdefghijklmnoprstuwqz"; // no pattern repeata inside
1262   auto orig = std::string(input);
1263   auto msp = MutableStringPiece(input);
1264
1265   std::random_device rd;
1266   std::mt19937 gen(rd());
1267   std::uniform_int_distribution<> dist('A', 'Z');
1268
1269   for (int i=0; i < 100; ++i) {
1270     for (size_t j = 1; j <= orig.size(); ++j) {
1271       auto replacement = get_rand_str(j, dist, gen);
1272       for (size_t pos = 0; pos < msp.size() - j; ++pos) {
1273         auto piece = orig.substr(pos, j);
1274         EXPECT_EQ(msp.replaceAll(piece, replacement), 1);
1275         EXPECT_EQ(msp.find(replacement), pos);
1276         EXPECT_EQ(msp.replaceAll(replacement, piece), 1);
1277         EXPECT_EQ(msp, orig);
1278       }
1279     }
1280   }
1281 }
1282
1283 TEST(ReplaceAll, BadArg) {
1284   int count = 0;
1285   auto fst = "longer";
1286   auto snd = "small";
1287   char input[] = "meh meh meh";
1288   auto all =  MutableStringPiece(input);
1289
1290   try {
1291     all.replaceAll(fst, snd);
1292   } catch (std::invalid_argument&) {
1293     ++count;
1294   }
1295
1296   try {
1297     all.replaceAll(snd, fst);
1298   } catch (std::invalid_argument&) {
1299     ++count;
1300   }
1301
1302   EXPECT_EQ(count, 2);
1303 }
1304
1305 TEST(Range, Constructors) {
1306   vector<int> c = {1, 2, 3};
1307   typedef Range<vector<int>::iterator> RangeType;
1308   typedef Range<vector<int>::const_iterator> ConstRangeType;
1309   RangeType cr(c.begin(), c.end());
1310   auto subpiece1 = ConstRangeType(cr, 1, 5);
1311   auto subpiece2 = ConstRangeType(cr, 1);
1312   EXPECT_EQ(subpiece1.size(), 2);
1313   EXPECT_EQ(subpiece1.begin(), subpiece2.begin());
1314   EXPECT_EQ(subpiece1.end(), subpiece2.end());
1315 }
1316
1317 TEST(Range, ArrayConstructors) {
1318   auto charArray = std::array<char, 4>{{'t', 'e', 's', 't'}};
1319   auto constCharArray = std::array<char, 6>{{'f', 'o', 'o', 'b', 'a', 'r'}};
1320   auto emptyArray = std::array<char, 0>{};
1321
1322   auto sp1 = StringPiece{charArray};
1323   EXPECT_EQ(4, sp1.size());
1324   EXPECT_EQ(charArray.data(), sp1.data());
1325
1326   auto sp2 = StringPiece(constCharArray);
1327   EXPECT_EQ(6, sp2.size());
1328   EXPECT_EQ(constCharArray.data(), sp2.data());
1329
1330   auto msp = MutableStringPiece(charArray);
1331   EXPECT_EQ(4, msp.size());
1332   EXPECT_EQ(charArray.data(), msp.data());
1333
1334   auto esp = StringPiece(emptyArray);
1335   EXPECT_EQ(0, esp.size());
1336   EXPECT_EQ(nullptr, esp.data());
1337
1338   auto emsp = MutableStringPiece(emptyArray);
1339   EXPECT_EQ(0, emsp.size());
1340   EXPECT_EQ(nullptr, emsp.data());
1341
1342   static constexpr std::array<int, 4> numArray = {{3, 17, 1, 9}};
1343   constexpr auto numRange = Range<const int*>{numArray};
1344   EXPECT_EQ(17, numRange[1]);
1345
1346   static constexpr std::array<int, 0> emptyNumArray{};
1347   constexpr auto emptyNumRange = Range<const int*>{emptyNumArray};
1348   EXPECT_EQ(0, emptyNumRange.size());
1349 }
1350
1351 TEST(Range, ConstexprAccessors) {
1352   constexpr StringPiece piece = range("hello");
1353   static_assert(piece.size() == 6u, "");
1354   static_assert(piece.end() - piece.begin() == 6u, "");
1355   static_assert(piece.data() == piece.begin(), "");
1356   static_assert(piece.start() == piece.begin(), "");
1357   static_assert(piece.cbegin() == piece.begin(), "");
1358   static_assert(piece.cend() == piece.end(), "");
1359   static_assert(*piece.begin() == 'h', "");
1360   static_assert(*(piece.end() - 1) == '\0', "");
1361 }