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