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