Add and fix BUCK files for folly
[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(qfind, UInt32_Ranges) {
809   vector<uint32_t> a({1, 2, 3, 260, 5});
810   vector<uint32_t> b({2, 3, 4});
811
812   auto a_range = folly::Range<const uint32_t*>(&a[0], a.size());
813   auto b_range = folly::Range<const uint32_t*>(&b[0], b.size());
814
815   EXPECT_EQ(qfind(a_range, b_range), string::npos);
816
817   a[3] = 4;
818   EXPECT_EQ(qfind(a_range, b_range), 1);
819 }
820
821 template <typename NeedleFinder>
822 class NeedleFinderTest : public ::testing::Test {
823  public:
824   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
825     return NeedleFinder::find_first_byte_of(haystack, needles);
826   }
827 };
828
829 struct SseNeedleFinder {
830   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
831     // This will only use the SSE version if it is supported on this CPU
832     // (selected using ifunc).
833     return detail::qfind_first_byte_of(haystack, needles);
834   }
835 };
836
837 struct NoSseNeedleFinder {
838   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
839     return detail::qfind_first_byte_of_nosse(haystack, needles);
840   }
841 };
842
843 struct MemchrNeedleFinder {
844   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
845     return detail::qfind_first_byte_of_memchr(haystack, needles);
846   }
847 };
848
849 struct ByteSetNeedleFinder {
850   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
851     return detail::qfind_first_byte_of_byteset(haystack, needles);
852   }
853 };
854
855 typedef ::testing::Types<SseNeedleFinder, NoSseNeedleFinder, MemchrNeedleFinder,
856                          ByteSetNeedleFinder> NeedleFinders;
857 TYPED_TEST_CASE(NeedleFinderTest, NeedleFinders);
858
859 TYPED_TEST(NeedleFinderTest, Null) {
860   { // null characters in the string
861     string s(10, char(0));
862     s[5] = 'b';
863     string delims("abc");
864     EXPECT_EQ(5, this->find_first_byte_of(s, delims));
865   }
866   { // null characters in delim
867     string s("abc");
868     string delims(10, char(0));
869     delims[3] = 'c';
870     delims[7] = 'b';
871     EXPECT_EQ(1, this->find_first_byte_of(s, delims));
872   }
873   { // range not terminated by null character
874     string buf = "abcdefghijklmnopqrstuvwxyz";
875     StringPiece s(buf.data() + 5, 3);
876     StringPiece delims("z");
877     EXPECT_EQ(string::npos, this->find_first_byte_of(s, delims));
878   }
879 }
880
881 TYPED_TEST(NeedleFinderTest, DelimDuplicates) {
882   string delims(1000, 'b');
883   EXPECT_EQ(1, this->find_first_byte_of("abc", delims));
884   EXPECT_EQ(string::npos, this->find_first_byte_of("ac", delims));
885 }
886
887 TYPED_TEST(NeedleFinderTest, Empty) {
888   string a = "abc";
889   string b = "";
890   EXPECT_EQ(string::npos, this->find_first_byte_of(a, b));
891   EXPECT_EQ(string::npos, this->find_first_byte_of(b, a));
892   EXPECT_EQ(string::npos, this->find_first_byte_of(b, b));
893 }
894
895 TYPED_TEST(NeedleFinderTest, Unaligned) {
896   // works correctly even if input buffers are not 16-byte aligned
897   string s = "0123456789ABCDEFGH";
898   for (int i = 0; i < s.size(); ++i) {
899     StringPiece a(s.c_str() + i);
900     for (int j = 0; j < s.size(); ++j) {
901       StringPiece b(s.c_str() + j);
902       EXPECT_EQ((i > j) ? 0 : j - i, this->find_first_byte_of(a, b));
903     }
904   }
905 }
906
907 // for some algorithms (specifically those that create a set of needles),
908 // we check for the edge-case of _all_ possible needles being sought.
909 TYPED_TEST(NeedleFinderTest, Needles256) {
910   string needles;
911   const auto minValue = std::numeric_limits<StringPiece::value_type>::min();
912   const auto maxValue = std::numeric_limits<StringPiece::value_type>::max();
913   // make the size ~big to avoid any edge-case branches for tiny haystacks
914   const int haystackSize = 50;
915   for (int i = minValue; i <= maxValue; i++) {  // <=
916     needles.push_back(i);
917   }
918   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
919   for (int i = minValue; i <= maxValue; i++) {
920     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
921   }
922
923   needles.append("these are redundant characters");
924   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
925   for (int i = minValue; i <= maxValue; i++) {
926     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
927   }
928 }
929
930 TYPED_TEST(NeedleFinderTest, Base) {
931   for (int i = 0; i < 32; ++i) {
932     for (int j = 0; j < 32; ++j) {
933       string s = string(i, 'X') + "abca" + string(i, 'X');
934       string delims = string(j, 'Y') + "a" + string(j, 'Y');
935       EXPECT_EQ(i, this->find_first_byte_of(s, delims));
936     }
937   }
938 }
939
940 const size_t kPageSize = 4096;
941 // Updates contents so that any read accesses past the last byte will
942 // cause a SIGSEGV.  It accomplishes this by changing access to the page that
943 // begins immediately after the end of the contents (as allocators and mmap()
944 // all operate on page boundaries, this is a reasonable assumption).
945 // This function will also initialize buf, which caller must free().
946 void createProtectedBuf(StringPiece& contents, char** buf) {
947   ASSERT_LE(contents.size(), kPageSize);
948   const size_t kSuccess = 0;
949   if (kSuccess != posix_memalign((void**)buf, kPageSize, 4 * kPageSize)) {
950     ASSERT_FALSE(true);
951   }
952   mprotect(*buf + kPageSize, kPageSize, PROT_NONE);
953   size_t newBegin = kPageSize - contents.size();
954   memcpy(*buf + newBegin, contents.data(), contents.size());
955   contents.reset(*buf + newBegin, contents.size());
956 }
957
958 void freeProtectedBuf(char* buf) {
959   mprotect(buf + kPageSize, kPageSize, PROT_READ | PROT_WRITE);
960   free(buf);
961 }
962
963 TYPED_TEST(NeedleFinderTest, NoSegFault) {
964   const string base = string(32, 'a') + string("b");
965   const string delims = string(32, 'c') + string("b");
966   for (int i = 0; i <= 32; i++) {
967     for (int j = 0; j <= 33; j++) {
968       for (int shouldFind = 0; shouldFind <= 1; ++shouldFind) {
969         StringPiece s1(base);
970         s1.advance(i);
971         ASSERT_TRUE(!s1.empty());
972         if (!shouldFind) {
973           s1.pop_back();
974         }
975         StringPiece s2(delims);
976         s2.advance(j);
977         char* buf1;
978         char* buf2;
979         createProtectedBuf(s1, &buf1);
980         createProtectedBuf(s2, &buf2);
981         // printf("s1: '%s' (%ld) \ts2: '%s' (%ld)\n",
982         //        string(s1.data(), s1.size()).c_str(), s1.size(),
983         //        string(s2.data(), s2.size()).c_str(), s2.size());
984         auto r1 = this->find_first_byte_of(s1, s2);
985         auto f1 = std::find_first_of(s1.begin(), s1.end(),
986                                      s2.begin(), s2.end());
987         auto e1 = (f1 == s1.end()) ? StringPiece::npos : f1 - s1.begin();
988         EXPECT_EQ(r1, e1);
989         auto r2 = this->find_first_byte_of(s2, s1);
990         auto f2 = std::find_first_of(s2.begin(), s2.end(),
991                                      s1.begin(), s1.end());
992         auto e2 = (f2 == s2.end()) ? StringPiece::npos : f2 - s2.begin();
993         EXPECT_EQ(r2, e2);
994         freeProtectedBuf(buf1);
995         freeProtectedBuf(buf2);
996       }
997     }
998   }
999 }
1000
1001 TEST(NonConstTest, StringPiece) {
1002   std::string hello("hello");
1003   MutableStringPiece sp(&hello.front(), hello.size());
1004   sp[0] = 'x';
1005   EXPECT_EQ("xello", hello);
1006   {
1007     StringPiece s(sp);
1008     EXPECT_EQ("xello", s);
1009   }
1010   {
1011     ByteRange r1(sp);
1012     MutableByteRange r2(sp);
1013   }
1014 }
1015
1016 template<class C>
1017 void testRangeFunc(C&& x, size_t n) {
1018   const auto& cx = x;
1019   // type, conversion checks
1020   Range<int*> r1 = range(std::forward<C>(x));
1021   Range<const int*> r2 = range(std::forward<C>(x));
1022   Range<const int*> r3 = range(cx);
1023   Range<const int*> r5 = range(std::move(cx));
1024   EXPECT_EQ(r1.begin(), &x[0]);
1025   EXPECT_EQ(r1.end(), &x[n]);
1026   EXPECT_EQ(n, r1.size());
1027   EXPECT_EQ(n, r2.size());
1028   EXPECT_EQ(n, r3.size());
1029   EXPECT_EQ(n, r5.size());
1030 }
1031
1032 TEST(RangeFunc, Vector) {
1033   std::vector<int> x;
1034   testRangeFunc(x, 0);
1035   x.push_back(2);
1036   testRangeFunc(x, 1);
1037   testRangeFunc(std::vector<int>{1, 2}, 2);
1038 }
1039
1040 TEST(RangeFunc, Array) {
1041   std::array<int, 3> x;
1042   testRangeFunc(x, 3);
1043 }
1044
1045 TEST(RangeFunc, CArray) {
1046   int x[] {1, 2, 3, 4};
1047   testRangeFunc(x, 4);
1048 }
1049
1050 std::string get_rand_str(
1051     int size, std::uniform_int_distribution<>& dist, std::mt19937& gen) {
1052   std::string ret(size, '\0');
1053   for (int i=0; i<size; ++i) {
1054     ret[i] = static_cast<char>(dist(gen));
1055   }
1056
1057   return ret;
1058 }
1059
1060 namespace folly {
1061 bool operator==(MutableStringPiece mp, StringPiece sp) {
1062   return mp.compare(sp) == 0;
1063 }
1064
1065 bool operator==(StringPiece sp, MutableStringPiece mp) {
1066   return mp.compare(sp) == 0;
1067 }
1068 }
1069
1070 TEST(ReplaceAt, exhaustiveTest) {
1071   char input[] = "this is nice and long input";
1072   auto msp = MutableStringPiece(input);
1073   auto str = std::string(input);
1074   std::random_device rd;
1075   std::mt19937 gen(rd());
1076   std::uniform_int_distribution<> dist('a', 'z');
1077
1078   for (int i=0; i < 100; ++i) {
1079     for (int j = 1; j <= msp.size(); ++j) {
1080       auto replacement = get_rand_str(j, dist, gen);
1081       for (int pos=0; pos < msp.size() - j; ++pos) {
1082         msp.replaceAt(pos, replacement);
1083         str.replace(pos, replacement.size(), replacement);
1084         EXPECT_EQ(msp.compare(str), 0);
1085       }
1086     }
1087   }
1088
1089   // too far
1090   EXPECT_EQ(msp.replaceAt(msp.size() - 2, StringPiece("meh")), false);
1091 }
1092
1093 TEST(ReplaceAll, basicTest) {
1094   char input[] = "this is nice and long input";
1095   auto orig = std::string(input);
1096   auto msp = MutableStringPiece(input);
1097
1098   EXPECT_EQ(msp.replaceAll("is", "si"), 2);
1099   EXPECT_EQ("thsi si nice and long input", msp);
1100   EXPECT_EQ(msp.replaceAll("si", "is"), 2);
1101   EXPECT_EQ(msp, orig);
1102
1103   EXPECT_EQ(msp.replaceAll("abcd", "efgh"), 0); // nothing to replace
1104   EXPECT_EQ(msp, orig);
1105
1106   // at the very beginning
1107   EXPECT_EQ(msp.replaceAll("this", "siht"), 1);
1108   EXPECT_EQ("siht is nice and long input", msp);
1109   EXPECT_EQ(msp.replaceAll("siht", "this"), 1);
1110   EXPECT_EQ(msp, orig);
1111
1112   // at the very end
1113   EXPECT_EQ(msp.replaceAll("input", "soput"), 1);
1114   EXPECT_EQ("this is nice and long soput", msp);
1115   EXPECT_EQ(msp.replaceAll("soput", "input"), 1);
1116   EXPECT_EQ(msp, orig);
1117
1118   // all spaces
1119   EXPECT_EQ(msp.replaceAll(" ", "@"), 5);
1120   EXPECT_EQ("this@is@nice@and@long@input", msp);
1121   EXPECT_EQ(msp.replaceAll("@", " "), 5);
1122   EXPECT_EQ(msp, orig);
1123 }
1124
1125 TEST(ReplaceAll, randomTest) {
1126   char input[] = "abcdefghijklmnoprstuwqz"; // no pattern repeata inside
1127   auto orig = std::string(input);
1128   auto msp = MutableStringPiece(input);
1129
1130   std::random_device rd;
1131   std::mt19937 gen(rd());
1132   std::uniform_int_distribution<> dist('A', 'Z');
1133
1134   for (int i=0; i < 100; ++i) {
1135     for (int j = 1; j <= orig.size(); ++j) {
1136       auto replacement = get_rand_str(j, dist, gen);
1137       for (int pos=0; pos < msp.size() - j; ++pos) {
1138         auto piece = orig.substr(pos, j);
1139         EXPECT_EQ(msp.replaceAll(piece, replacement), 1);
1140         EXPECT_EQ(msp.find(replacement), pos);
1141         EXPECT_EQ(msp.replaceAll(replacement, piece), 1);
1142         EXPECT_EQ(msp, orig);
1143       }
1144     }
1145   }
1146 }
1147
1148 TEST(ReplaceAll, BadArg) {
1149   int count = 0;
1150   auto fst = "longer";
1151   auto snd = "small";
1152   char input[] = "meh meh meh";
1153   auto all =  MutableStringPiece(input);
1154
1155   try {
1156     all.replaceAll(fst, snd);
1157   } catch (std::invalid_argument&) {
1158     ++count;
1159   }
1160
1161   try {
1162     all.replaceAll(snd, fst);
1163   } catch (std::invalid_argument&) {
1164     ++count;
1165   }
1166
1167   EXPECT_EQ(count, 2);
1168 }