StringPiece comparisons are broken
[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   // find_first_of
125   s.reset(foobarbaz, strlen(foobarbaz));
126   EXPECT_EQ(s.find_first_of("bar"), 3);
127   EXPECT_EQ(s.find_first_of("ba", 3), 3);
128   EXPECT_EQ(s.find_first_of("ba", 4), 4);
129   EXPECT_EQ(s.find_first_of("xyxy"), StringPiece::npos);
130   EXPECT_EQ(s.find_first_of("xyxy", 1), StringPiece::npos);
131   // starting position too far
132   EXPECT_EQ(s.find_first_of("foo", 4), StringPiece::npos);
133   // starting pos that is obviously past the end -- This works for std::string
134   EXPECT_EQ(s.toString().find_first_of("xyxy", 55), StringPiece::npos);
135   EXPECT_EQ(s.find_first_of("z", s.size()), StringPiece::npos);
136   EXPECT_EQ(s.find_first_of("z", 55), StringPiece::npos);
137   // empty needle. Note that this returns npos, while find() returns 0!
138   EXPECT_EQ(s.find_first_of(""), std::string().find_first_of(""));
139   EXPECT_EQ(s.find_first_of(""), StringPiece::npos);
140
141   // single char find_first_ofs
142   EXPECT_EQ(s.find_first_of('b'), 3);
143   EXPECT_EQ(s.find_first_of('b', 3), 3);
144   EXPECT_EQ(s.find_first_of('b', 4), 6);
145   EXPECT_EQ(s.find_first_of('o', 2), 2);
146   EXPECT_EQ(s.find_first_of('y'), StringPiece::npos);
147   EXPECT_EQ(s.find_first_of('y', 1), StringPiece::npos);
148   // starting position too far
149   EXPECT_EQ(s.find_first_of('o', 4), StringPiece::npos);
150   // starting pos that is obviously past the end -- This works for std::string
151   EXPECT_EQ(s.toString().find_first_of('y', 55), StringPiece::npos);
152   EXPECT_EQ(s.find_first_of('z', s.size()), StringPiece::npos);
153   EXPECT_EQ(s.find_first_of('z', 55), StringPiece::npos);
154   // null char
155   EXPECT_EQ(s.find_first_of('\0'), std::string().find_first_of('\0'));
156   EXPECT_EQ(s.find_first_of('\0'), StringPiece::npos);
157
158   // just "barbaz"
159   s.reset(foobarbaz + 3, strlen(foobarbaz + 3));
160   EXPECT_EQ(s.size(), 6);
161   EXPECT_EQ(s.start(), foobarbaz + 3);
162   EXPECT_EQ(s, "barbaz");
163
164   // just "bar"
165   s.reset(foobarbaz + 3, 3);
166   EXPECT_EQ(s.size(), 3);
167   EXPECT_EQ(s, "bar");
168
169   // clear
170   s.clear();
171   EXPECT_EQ(s.toString(), "");
172
173   // test an empty StringPiece
174   StringPiece s2;
175   EXPECT_EQ(s2.size(), 0);
176
177   // Test comparison operators
178   foo = "";
179   EXPECT_LE(s, foo);
180   EXPECT_LE(foo, s);
181   EXPECT_GE(s, foo);
182   EXPECT_GE(foo, s);
183   EXPECT_EQ(s, foo);
184   EXPECT_EQ(foo, s);
185
186   foo = "abc";
187   EXPECT_LE(s, foo);
188   EXPECT_LT(s, foo);
189   EXPECT_GE(foo, s);
190   EXPECT_GT(foo, s);
191   EXPECT_NE(s, foo);
192
193   EXPECT_LE(s, s);
194   EXPECT_LE(s, s);
195   EXPECT_GE(s, s);
196   EXPECT_GE(s, s);
197   EXPECT_EQ(s, s);
198   EXPECT_EQ(s, s);
199
200   s = "abc";
201   s2 = "abc";
202   EXPECT_LE(s, s2);
203   EXPECT_LE(s2, s);
204   EXPECT_GE(s, s2);
205   EXPECT_GE(s2, s);
206   EXPECT_EQ(s, s2);
207   EXPECT_EQ(s2, s);
208 }
209
210 template <class T>
211 void expectLT(const T& a, const T& b) {
212   EXPECT_TRUE(a < b);
213   EXPECT_TRUE(a <= b);
214   EXPECT_FALSE(a == b);
215   EXPECT_FALSE(a >= b);
216   EXPECT_FALSE(a > b);
217
218   EXPECT_FALSE(b < a);
219   EXPECT_FALSE(b <= a);
220   EXPECT_TRUE(b >= a);
221   EXPECT_TRUE(b > a);
222 }
223
224 template <class T>
225 void expectEQ(const T& a, const T& b) {
226   EXPECT_FALSE(a < b);
227   EXPECT_TRUE(a <= b);
228   EXPECT_TRUE(a == b);
229   EXPECT_TRUE(a >= b);
230   EXPECT_FALSE(a > b);
231 }
232
233 TEST(StringPiece, EightBitComparisons) {
234   char values[] = {'\x00', '\x20', '\x40', '\x7f', '\x80', '\xc0', '\xff'};
235   constexpr size_t count = sizeof(values) / sizeof(values[0]);
236   for (size_t i = 0; i < count; ++i) {
237     std::string a(1, values[i]);
238     // Defeat copy-on-write
239     std::string aCopy(a.data(), a.size());
240     expectEQ(a, aCopy);
241     expectEQ(StringPiece(a), StringPiece(aCopy));
242
243     for (size_t j = i + 1; j < count; ++j) {
244       std::string b(1, values[j]);
245       expectLT(a, b);
246       expectLT(StringPiece(a), StringPiece(b));
247     }
248   }
249 }
250
251 TEST(StringPiece, ToByteRange) {
252   StringPiece a("hello");
253   ByteRange b(a);
254   EXPECT_EQ(static_cast<const void*>(a.begin()),
255             static_cast<const void*>(b.begin()));
256   EXPECT_EQ(static_cast<const void*>(a.end()),
257             static_cast<const void*>(b.end()));
258
259   // and convert back again
260   StringPiece c(b);
261   EXPECT_EQ(a.begin(), c.begin());
262   EXPECT_EQ(a.end(), c.end());
263 }
264
265 TEST(StringPiece, InvalidRange) {
266   StringPiece a("hello");
267   EXPECT_EQ(a, a.subpiece(0, 10));
268   EXPECT_EQ(StringPiece("ello"), a.subpiece(1));
269   EXPECT_EQ(StringPiece("ello"), a.subpiece(1, std::string::npos));
270   EXPECT_EQ(StringPiece("ell"), a.subpiece(1, 3));
271   EXPECT_THROW(a.subpiece(6, 7), std::out_of_range);
272   EXPECT_THROW(a.subpiece(6), std::out_of_range);
273
274   std::string b("hello");
275   EXPECT_EQ(a, StringPiece(b, 0, 10));
276   EXPECT_EQ("ello", a.subpiece(1));
277   EXPECT_EQ("ello", a.subpiece(1, std::string::npos));
278   EXPECT_EQ("ell", a.subpiece(1, 3));
279   EXPECT_THROW(a.subpiece(6, 7), std::out_of_range);
280   EXPECT_THROW(a.subpiece(6), std::out_of_range);
281 }
282
283 template <typename NeedleFinder>
284 class NeedleFinderTest : public ::testing::Test {
285  public:
286   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
287     return NeedleFinder::find_first_byte_of(haystack, needles);
288   }
289 };
290
291 struct SseNeedleFinder {
292   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
293     // This will only use the SSE version if it is supported on this CPU
294     // (selected using ifunc).
295     return detail::qfind_first_byte_of(haystack, needles);
296   }
297 };
298
299 struct NoSseNeedleFinder {
300   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
301     return detail::qfind_first_byte_of_nosse(haystack, needles);
302   }
303 };
304
305 struct MemchrNeedleFinder {
306   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
307     return detail::qfind_first_byte_of_memchr(haystack, needles);
308   }
309 };
310
311 struct ByteSetNeedleFinder {
312   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
313     return detail::qfind_first_byte_of_byteset(haystack, needles);
314   }
315 };
316
317 typedef ::testing::Types<SseNeedleFinder, NoSseNeedleFinder, MemchrNeedleFinder,
318                          ByteSetNeedleFinder> NeedleFinders;
319 TYPED_TEST_CASE(NeedleFinderTest, NeedleFinders);
320
321 TYPED_TEST(NeedleFinderTest, Null) {
322   { // null characters in the string
323     string s(10, char(0));
324     s[5] = 'b';
325     string delims("abc");
326     EXPECT_EQ(5, this->find_first_byte_of(s, delims));
327   }
328   { // null characters in delim
329     string s("abc");
330     string delims(10, char(0));
331     delims[3] = 'c';
332     delims[7] = 'b';
333     EXPECT_EQ(1, this->find_first_byte_of(s, delims));
334   }
335   { // range not terminated by null character
336     string buf = "abcdefghijklmnopqrstuvwxyz";
337     StringPiece s(buf.data() + 5, 3);
338     StringPiece delims("z");
339     EXPECT_EQ(string::npos, this->find_first_byte_of(s, delims));
340   }
341 }
342
343 TYPED_TEST(NeedleFinderTest, DelimDuplicates) {
344   string delims(1000, 'b');
345   EXPECT_EQ(1, this->find_first_byte_of("abc", delims));
346   EXPECT_EQ(string::npos, this->find_first_byte_of("ac", delims));
347 }
348
349 TYPED_TEST(NeedleFinderTest, Empty) {
350   string a = "abc";
351   string b = "";
352   EXPECT_EQ(string::npos, this->find_first_byte_of(a, b));
353   EXPECT_EQ(string::npos, this->find_first_byte_of(b, a));
354   EXPECT_EQ(string::npos, this->find_first_byte_of(b, b));
355 }
356
357 TYPED_TEST(NeedleFinderTest, Unaligned) {
358   // works correctly even if input buffers are not 16-byte aligned
359   string s = "0123456789ABCDEFGH";
360   for (int i = 0; i < s.size(); ++i) {
361     StringPiece a(s.c_str() + i);
362     for (int j = 0; j < s.size(); ++j) {
363       StringPiece b(s.c_str() + j);
364       EXPECT_EQ((i > j) ? 0 : j - i, this->find_first_byte_of(a, b));
365     }
366   }
367 }
368
369 // for some algorithms (specifically those that create a set of needles),
370 // we check for the edge-case of _all_ possible needles being sought.
371 TYPED_TEST(NeedleFinderTest, Needles256) {
372   string needles;
373   const auto minValue = std::numeric_limits<StringPiece::value_type>::min();
374   const auto maxValue = std::numeric_limits<StringPiece::value_type>::max();
375   // make the size ~big to avoid any edge-case branches for tiny haystacks
376   const int haystackSize = 50;
377   for (int i = minValue; i <= maxValue; i++) {  // <=
378     needles.push_back(i);
379   }
380   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
381   for (int i = minValue; i <= maxValue; i++) {
382     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
383   }
384
385   needles.append("these are redundant characters");
386   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
387   for (int i = minValue; i <= maxValue; i++) {
388     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
389   }
390 }
391
392 TYPED_TEST(NeedleFinderTest, Base) {
393   for (int i = 0; i < 32; ++i) {
394     for (int j = 0; j < 32; ++j) {
395       string s = string(i, 'X') + "abca" + string(i, 'X');
396       string delims = string(j, 'Y') + "a" + string(j, 'Y');
397       EXPECT_EQ(i, this->find_first_byte_of(s, delims));
398     }
399   }
400 }
401
402 const size_t kPageSize = 4096;
403 // Updates contents so that any read accesses past the last byte will
404 // cause a SIGSEGV.  It accomplishes this by changing access to the page that
405 // begins immediately after the end of the contents (as allocators and mmap()
406 // all operate on page boundaries, this is a reasonable assumption).
407 // This function will also initialize buf, which caller must free().
408 void createProtectedBuf(StringPiece& contents, char** buf) {
409   ASSERT_LE(contents.size(), kPageSize);
410   const size_t kSuccess = 0;
411   char* tmp;
412   if (kSuccess != posix_memalign((void**)buf, kPageSize, 2 * kPageSize)) {
413     ASSERT_FALSE(true);
414   }
415   mprotect(*buf + kPageSize, kPageSize, PROT_NONE);
416   size_t newBegin = kPageSize - contents.size();
417   memcpy(*buf + newBegin, contents.data(), contents.size());
418   contents.reset(*buf + newBegin, contents.size());
419 }
420
421 TYPED_TEST(NeedleFinderTest, NoSegFault) {
422   const string base = string(32, 'a') + string("b");
423   const string delims = string(32, 'c') + string("b");
424   for (int i = 0; i <= 32; i++) {
425     for (int j = 0; j <= 33; j++) {
426       for (int shouldFind = 0; shouldFind <= 1; ++shouldFind) {
427         StringPiece s1(base);
428         s1.advance(i);
429         ASSERT_TRUE(!s1.empty());
430         if (!shouldFind) {
431           s1.pop_back();
432         }
433         StringPiece s2(delims);
434         s2.advance(j);
435         char* buf1;
436         char* buf2;
437         createProtectedBuf(s1, &buf1);
438         createProtectedBuf(s2, &buf2);
439         // printf("s1: '%s' (%ld) \ts2: '%s' (%ld)\n",
440         //        string(s1.data(), s1.size()).c_str(), s1.size(),
441         //        string(s2.data(), s2.size()).c_str(), s2.size());
442         auto r1 = this->find_first_byte_of(s1, s2);
443         auto f1 = std::find_first_of(s1.begin(), s1.end(),
444                                      s2.begin(), s2.end());
445         auto e1 = (f1 == s1.end()) ? StringPiece::npos : f1 - s1.begin();
446         EXPECT_EQ(r1, e1);
447         auto r2 = this->find_first_byte_of(s2, s1);
448         auto f2 = std::find_first_of(s2.begin(), s2.end(),
449                                      s1.begin(), s1.end());
450         auto e2 = (f2 == s2.end()) ? StringPiece::npos : f2 - s2.begin();
451         EXPECT_EQ(r2, e2);
452         free(buf1);
453         free(buf2);
454       }
455     }
456   }
457 }