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