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