Range<T>::rfind()
[folly.git] / folly / test / RangeTest.cpp
1 /*
2  * Copyright 2013 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 <limits>
23 #include <stdlib.h>
24 #include <string>
25 #include <sys/mman.h>
26 #include <boost/range/concepts.hpp>
27 #include <gtest/gtest.h>
28
29 namespace folly { namespace detail {
30
31 // declaration of functions in Range.cpp
32 size_t qfind_first_byte_of_memchr(const StringPiece& haystack,
33                                   const StringPiece& needles);
34
35 size_t qfind_first_byte_of_byteset(const StringPiece& haystack,
36                                    const StringPiece& needles);
37
38 }}  // namespaces
39
40 using namespace folly;
41 using namespace std;
42
43 BOOST_CONCEPT_ASSERT((boost::RandomAccessRangeConcept<StringPiece>));
44
45 TEST(StringPiece, All) {
46   const char* foo = "foo";
47   const char* foo2 = "foo";
48   string fooStr(foo);
49   string foo2Str(foo2);
50
51   // we expect the compiler to optimize things so that there's only one copy
52   // of the string literal "foo", even though we've got it in multiple places
53   EXPECT_EQ(foo, foo2);  // remember, this uses ==, not strcmp, so it's a ptr
54                          // comparison rather than lexical
55
56   // the string object creates copies though, so the c_str of these should be
57   // distinct
58   EXPECT_NE(fooStr.c_str(), foo2Str.c_str());
59
60   // test the basic StringPiece functionality
61   StringPiece s(foo);
62   EXPECT_EQ(s.size(), 3);
63
64   EXPECT_EQ(s.start(), foo);              // ptr comparison
65   EXPECT_NE(s.start(), fooStr.c_str());   // ptr comparison
66   EXPECT_NE(s.start(), foo2Str.c_str());  // ptr comparison
67
68   EXPECT_EQ(s.toString(), foo);              // lexical comparison
69   EXPECT_EQ(s.toString(), fooStr.c_str());   // lexical comparison
70   EXPECT_EQ(s.toString(), foo2Str.c_str());  // lexical comparison
71
72   EXPECT_EQ(s, foo);                      // lexical comparison
73   EXPECT_EQ(s, fooStr);                   // lexical comparison
74   EXPECT_EQ(s, foo2Str);                  // lexical comparison
75   EXPECT_EQ(foo, s);
76
77   // check using StringPiece to reference substrings
78   const char* foobarbaz = "foobarbaz";
79
80   // the full "foobarbaz"
81   s.reset(foobarbaz, strlen(foobarbaz));
82   EXPECT_EQ(s.size(), 9);
83   EXPECT_EQ(s.start(), foobarbaz);
84   EXPECT_EQ(s, "foobarbaz");
85
86   // only the 'foo'
87   s.assign(foobarbaz, foobarbaz + 3);
88   EXPECT_EQ(s.size(), 3);
89   EXPECT_EQ(s.start(), foobarbaz);
90   EXPECT_EQ(s, "foo");
91
92   // find
93   s.reset(foobarbaz, strlen(foobarbaz));
94   EXPECT_EQ(s.find("bar"), 3);
95   EXPECT_EQ(s.find("ba", 3), 3);
96   EXPECT_EQ(s.find("ba", 4), 6);
97   EXPECT_EQ(s.find("notfound"), StringPiece::npos);
98   EXPECT_EQ(s.find("notfound", 1), StringPiece::npos);
99   EXPECT_EQ(s.find("bar", 4), StringPiece::npos);  // starting position too far
100   // starting pos that is obviously past the end -- This works for std::string
101   EXPECT_EQ(s.toString().find("notfound", 55), StringPiece::npos);
102   EXPECT_EQ(s.find("z", s.size()), StringPiece::npos);
103   EXPECT_EQ(s.find("z", 55), StringPiece::npos);
104   // empty needle
105   EXPECT_EQ(s.find(""), std::string().find(""));
106   EXPECT_EQ(s.find(""), 0);
107
108   // single char finds
109   EXPECT_EQ(s.find('b'), 3);
110   EXPECT_EQ(s.find('b', 3), 3);
111   EXPECT_EQ(s.find('b', 4), 6);
112   EXPECT_EQ(s.find('o', 2), 2);
113   EXPECT_EQ(s.find('y'), StringPiece::npos);
114   EXPECT_EQ(s.find('y', 1), StringPiece::npos);
115   EXPECT_EQ(s.find('o', 4), StringPiece::npos);  // starting position too far
116   // starting pos that is obviously past the end -- This works for std::string
117   EXPECT_EQ(s.toString().find('y', 55), StringPiece::npos);
118   EXPECT_EQ(s.find('z', s.size()), StringPiece::npos);
119   EXPECT_EQ(s.find('z', 55), StringPiece::npos);
120   // null char
121   EXPECT_EQ(s.find('\0'), std::string().find('\0'));
122   EXPECT_EQ(s.find('\0'), StringPiece::npos);
123
124   // single char rfinds
125   EXPECT_EQ(s.rfind('b'), 6);
126   EXPECT_EQ(s.rfind('y'), StringPiece::npos);
127   EXPECT_EQ(s.str().rfind('y'), StringPiece::npos);
128   EXPECT_EQ(ByteRange(s).rfind('b'), 6);
129   EXPECT_EQ(ByteRange(s).rfind('y'), StringPiece::npos);
130   // null char
131   EXPECT_EQ(s.rfind('\0'), s.str().rfind('\0'));
132   EXPECT_EQ(s.rfind('\0'), StringPiece::npos);
133
134   // find_first_of
135   s.reset(foobarbaz, strlen(foobarbaz));
136   EXPECT_EQ(s.find_first_of("bar"), 3);
137   EXPECT_EQ(s.find_first_of("ba", 3), 3);
138   EXPECT_EQ(s.find_first_of("ba", 4), 4);
139   EXPECT_EQ(s.find_first_of("xyxy"), StringPiece::npos);
140   EXPECT_EQ(s.find_first_of("xyxy", 1), StringPiece::npos);
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 template <typename NeedleFinder>
294 class NeedleFinderTest : public ::testing::Test {
295  public:
296   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
297     return NeedleFinder::find_first_byte_of(haystack, needles);
298   }
299 };
300
301 struct SseNeedleFinder {
302   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
303     // This will only use the SSE version if it is supported on this CPU
304     // (selected using ifunc).
305     return detail::qfind_first_byte_of(haystack, needles);
306   }
307 };
308
309 struct NoSseNeedleFinder {
310   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
311     return detail::qfind_first_byte_of_nosse(haystack, needles);
312   }
313 };
314
315 struct MemchrNeedleFinder {
316   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
317     return detail::qfind_first_byte_of_memchr(haystack, needles);
318   }
319 };
320
321 struct ByteSetNeedleFinder {
322   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
323     return detail::qfind_first_byte_of_byteset(haystack, needles);
324   }
325 };
326
327 typedef ::testing::Types<SseNeedleFinder, NoSseNeedleFinder, MemchrNeedleFinder,
328                          ByteSetNeedleFinder> NeedleFinders;
329 TYPED_TEST_CASE(NeedleFinderTest, NeedleFinders);
330
331 TYPED_TEST(NeedleFinderTest, Null) {
332   { // null characters in the string
333     string s(10, char(0));
334     s[5] = 'b';
335     string delims("abc");
336     EXPECT_EQ(5, this->find_first_byte_of(s, delims));
337   }
338   { // null characters in delim
339     string s("abc");
340     string delims(10, char(0));
341     delims[3] = 'c';
342     delims[7] = 'b';
343     EXPECT_EQ(1, this->find_first_byte_of(s, delims));
344   }
345   { // range not terminated by null character
346     string buf = "abcdefghijklmnopqrstuvwxyz";
347     StringPiece s(buf.data() + 5, 3);
348     StringPiece delims("z");
349     EXPECT_EQ(string::npos, this->find_first_byte_of(s, delims));
350   }
351 }
352
353 TYPED_TEST(NeedleFinderTest, DelimDuplicates) {
354   string delims(1000, 'b');
355   EXPECT_EQ(1, this->find_first_byte_of("abc", delims));
356   EXPECT_EQ(string::npos, this->find_first_byte_of("ac", delims));
357 }
358
359 TYPED_TEST(NeedleFinderTest, Empty) {
360   string a = "abc";
361   string b = "";
362   EXPECT_EQ(string::npos, this->find_first_byte_of(a, b));
363   EXPECT_EQ(string::npos, this->find_first_byte_of(b, a));
364   EXPECT_EQ(string::npos, this->find_first_byte_of(b, b));
365 }
366
367 TYPED_TEST(NeedleFinderTest, Unaligned) {
368   // works correctly even if input buffers are not 16-byte aligned
369   string s = "0123456789ABCDEFGH";
370   for (int i = 0; i < s.size(); ++i) {
371     StringPiece a(s.c_str() + i);
372     for (int j = 0; j < s.size(); ++j) {
373       StringPiece b(s.c_str() + j);
374       EXPECT_EQ((i > j) ? 0 : j - i, this->find_first_byte_of(a, b));
375     }
376   }
377 }
378
379 // for some algorithms (specifically those that create a set of needles),
380 // we check for the edge-case of _all_ possible needles being sought.
381 TYPED_TEST(NeedleFinderTest, Needles256) {
382   string needles;
383   const auto minValue = std::numeric_limits<StringPiece::value_type>::min();
384   const auto maxValue = std::numeric_limits<StringPiece::value_type>::max();
385   // make the size ~big to avoid any edge-case branches for tiny haystacks
386   const int haystackSize = 50;
387   for (int i = minValue; i <= maxValue; i++) {  // <=
388     needles.push_back(i);
389   }
390   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
391   for (int i = minValue; i <= maxValue; i++) {
392     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
393   }
394
395   needles.append("these are redundant characters");
396   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
397   for (int i = minValue; i <= maxValue; i++) {
398     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
399   }
400 }
401
402 TYPED_TEST(NeedleFinderTest, Base) {
403   for (int i = 0; i < 32; ++i) {
404     for (int j = 0; j < 32; ++j) {
405       string s = string(i, 'X') + "abca" + string(i, 'X');
406       string delims = string(j, 'Y') + "a" + string(j, 'Y');
407       EXPECT_EQ(i, this->find_first_byte_of(s, delims));
408     }
409   }
410 }
411
412 const size_t kPageSize = 4096;
413 // Updates contents so that any read accesses past the last byte will
414 // cause a SIGSEGV.  It accomplishes this by changing access to the page that
415 // begins immediately after the end of the contents (as allocators and mmap()
416 // all operate on page boundaries, this is a reasonable assumption).
417 // This function will also initialize buf, which caller must free().
418 void createProtectedBuf(StringPiece& contents, char** buf) {
419   ASSERT_LE(contents.size(), kPageSize);
420   const size_t kSuccess = 0;
421   char* tmp;
422   if (kSuccess != posix_memalign((void**)buf, kPageSize, 2 * kPageSize)) {
423     ASSERT_FALSE(true);
424   }
425   mprotect(*buf + kPageSize, kPageSize, PROT_NONE);
426   size_t newBegin = kPageSize - contents.size();
427   memcpy(*buf + newBegin, contents.data(), contents.size());
428   contents.reset(*buf + newBegin, contents.size());
429 }
430
431 TYPED_TEST(NeedleFinderTest, NoSegFault) {
432   const string base = string(32, 'a') + string("b");
433   const string delims = string(32, 'c') + string("b");
434   for (int i = 0; i <= 32; i++) {
435     for (int j = 0; j <= 33; j++) {
436       for (int shouldFind = 0; shouldFind <= 1; ++shouldFind) {
437         StringPiece s1(base);
438         s1.advance(i);
439         ASSERT_TRUE(!s1.empty());
440         if (!shouldFind) {
441           s1.pop_back();
442         }
443         StringPiece s2(delims);
444         s2.advance(j);
445         char* buf1;
446         char* buf2;
447         createProtectedBuf(s1, &buf1);
448         createProtectedBuf(s2, &buf2);
449         // printf("s1: '%s' (%ld) \ts2: '%s' (%ld)\n",
450         //        string(s1.data(), s1.size()).c_str(), s1.size(),
451         //        string(s2.data(), s2.size()).c_str(), s2.size());
452         auto r1 = this->find_first_byte_of(s1, s2);
453         auto f1 = std::find_first_of(s1.begin(), s1.end(),
454                                      s2.begin(), s2.end());
455         auto e1 = (f1 == s1.end()) ? StringPiece::npos : f1 - s1.begin();
456         EXPECT_EQ(r1, e1);
457         auto r2 = this->find_first_byte_of(s2, s1);
458         auto f2 = std::find_first_of(s2.begin(), s2.end(),
459                                      s1.begin(), s1.end());
460         auto e2 = (f2 == s2.end()) ? StringPiece::npos : f2 - s2.begin();
461         EXPECT_EQ(r2, e2);
462         free(buf1);
463         free(buf2);
464       }
465     }
466   }
467 }