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