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