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