Detect C++ implementations that support constexpr strlen()
[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 #if FOLLY_HAVE_CONSTEXPR_STRLEN
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 #endif
304
305 TEST(qfind, UInt32_Ranges) {
306   vector<uint32_t> a({1, 2, 3, 260, 5});
307   vector<uint32_t> b({2, 3, 4});
308
309   auto a_range = folly::Range<const uint32_t*>(&a[0], a.size());
310   auto b_range = folly::Range<const uint32_t*>(&b[0], b.size());
311
312   EXPECT_EQ(qfind(a_range, b_range), string::npos);
313
314   a[3] = 4;
315   EXPECT_EQ(qfind(a_range, b_range), 1);
316 }
317
318 template <typename NeedleFinder>
319 class NeedleFinderTest : public ::testing::Test {
320  public:
321   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
322     return NeedleFinder::find_first_byte_of(haystack, needles);
323   }
324 };
325
326 struct SseNeedleFinder {
327   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
328     // This will only use the SSE version if it is supported on this CPU
329     // (selected using ifunc).
330     return detail::qfind_first_byte_of(haystack, needles);
331   }
332 };
333
334 struct NoSseNeedleFinder {
335   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
336     return detail::qfind_first_byte_of_nosse(haystack, needles);
337   }
338 };
339
340 struct MemchrNeedleFinder {
341   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
342     return detail::qfind_first_byte_of_memchr(haystack, needles);
343   }
344 };
345
346 struct ByteSetNeedleFinder {
347   static size_t find_first_byte_of(StringPiece haystack, StringPiece needles) {
348     return detail::qfind_first_byte_of_byteset(haystack, needles);
349   }
350 };
351
352 typedef ::testing::Types<SseNeedleFinder, NoSseNeedleFinder, MemchrNeedleFinder,
353                          ByteSetNeedleFinder> NeedleFinders;
354 TYPED_TEST_CASE(NeedleFinderTest, NeedleFinders);
355
356 TYPED_TEST(NeedleFinderTest, Null) {
357   { // null characters in the string
358     string s(10, char(0));
359     s[5] = 'b';
360     string delims("abc");
361     EXPECT_EQ(5, this->find_first_byte_of(s, delims));
362   }
363   { // null characters in delim
364     string s("abc");
365     string delims(10, char(0));
366     delims[3] = 'c';
367     delims[7] = 'b';
368     EXPECT_EQ(1, this->find_first_byte_of(s, delims));
369   }
370   { // range not terminated by null character
371     string buf = "abcdefghijklmnopqrstuvwxyz";
372     StringPiece s(buf.data() + 5, 3);
373     StringPiece delims("z");
374     EXPECT_EQ(string::npos, this->find_first_byte_of(s, delims));
375   }
376 }
377
378 TYPED_TEST(NeedleFinderTest, DelimDuplicates) {
379   string delims(1000, 'b');
380   EXPECT_EQ(1, this->find_first_byte_of("abc", delims));
381   EXPECT_EQ(string::npos, this->find_first_byte_of("ac", delims));
382 }
383
384 TYPED_TEST(NeedleFinderTest, Empty) {
385   string a = "abc";
386   string b = "";
387   EXPECT_EQ(string::npos, this->find_first_byte_of(a, b));
388   EXPECT_EQ(string::npos, this->find_first_byte_of(b, a));
389   EXPECT_EQ(string::npos, this->find_first_byte_of(b, b));
390 }
391
392 TYPED_TEST(NeedleFinderTest, Unaligned) {
393   // works correctly even if input buffers are not 16-byte aligned
394   string s = "0123456789ABCDEFGH";
395   for (int i = 0; i < s.size(); ++i) {
396     StringPiece a(s.c_str() + i);
397     for (int j = 0; j < s.size(); ++j) {
398       StringPiece b(s.c_str() + j);
399       EXPECT_EQ((i > j) ? 0 : j - i, this->find_first_byte_of(a, b));
400     }
401   }
402 }
403
404 // for some algorithms (specifically those that create a set of needles),
405 // we check for the edge-case of _all_ possible needles being sought.
406 TYPED_TEST(NeedleFinderTest, Needles256) {
407   string needles;
408   const auto minValue = std::numeric_limits<StringPiece::value_type>::min();
409   const auto maxValue = std::numeric_limits<StringPiece::value_type>::max();
410   // make the size ~big to avoid any edge-case branches for tiny haystacks
411   const int haystackSize = 50;
412   for (int i = minValue; i <= maxValue; i++) {  // <=
413     needles.push_back(i);
414   }
415   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
416   for (int i = minValue; i <= maxValue; i++) {
417     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
418   }
419
420   needles.append("these are redundant characters");
421   EXPECT_EQ(StringPiece::npos, this->find_first_byte_of("", needles));
422   for (int i = minValue; i <= maxValue; i++) {
423     EXPECT_EQ(0, this->find_first_byte_of(string(haystackSize, i), needles));
424   }
425 }
426
427 TYPED_TEST(NeedleFinderTest, Base) {
428   for (int i = 0; i < 32; ++i) {
429     for (int j = 0; j < 32; ++j) {
430       string s = string(i, 'X') + "abca" + string(i, 'X');
431       string delims = string(j, 'Y') + "a" + string(j, 'Y');
432       EXPECT_EQ(i, this->find_first_byte_of(s, delims));
433     }
434   }
435 }
436
437 const size_t kPageSize = 4096;
438 // Updates contents so that any read accesses past the last byte will
439 // cause a SIGSEGV.  It accomplishes this by changing access to the page that
440 // begins immediately after the end of the contents (as allocators and mmap()
441 // all operate on page boundaries, this is a reasonable assumption).
442 // This function will also initialize buf, which caller must free().
443 void createProtectedBuf(StringPiece& contents, char** buf) {
444   ASSERT_LE(contents.size(), kPageSize);
445   const size_t kSuccess = 0;
446   if (kSuccess != posix_memalign((void**)buf, kPageSize, 4 * kPageSize)) {
447     ASSERT_FALSE(true);
448   }
449   mprotect(*buf + kPageSize, kPageSize, PROT_NONE);
450   size_t newBegin = kPageSize - contents.size();
451   memcpy(*buf + newBegin, contents.data(), contents.size());
452   contents.reset(*buf + newBegin, contents.size());
453 }
454
455 void freeProtectedBuf(char* buf) {
456   mprotect(buf + kPageSize, kPageSize, PROT_READ | PROT_WRITE);
457   free(buf);
458 }
459
460 TYPED_TEST(NeedleFinderTest, NoSegFault) {
461   const string base = string(32, 'a') + string("b");
462   const string delims = string(32, 'c') + string("b");
463   for (int i = 0; i <= 32; i++) {
464     for (int j = 0; j <= 33; j++) {
465       for (int shouldFind = 0; shouldFind <= 1; ++shouldFind) {
466         StringPiece s1(base);
467         s1.advance(i);
468         ASSERT_TRUE(!s1.empty());
469         if (!shouldFind) {
470           s1.pop_back();
471         }
472         StringPiece s2(delims);
473         s2.advance(j);
474         char* buf1;
475         char* buf2;
476         createProtectedBuf(s1, &buf1);
477         createProtectedBuf(s2, &buf2);
478         // printf("s1: '%s' (%ld) \ts2: '%s' (%ld)\n",
479         //        string(s1.data(), s1.size()).c_str(), s1.size(),
480         //        string(s2.data(), s2.size()).c_str(), s2.size());
481         auto r1 = this->find_first_byte_of(s1, s2);
482         auto f1 = std::find_first_of(s1.begin(), s1.end(),
483                                      s2.begin(), s2.end());
484         auto e1 = (f1 == s1.end()) ? StringPiece::npos : f1 - s1.begin();
485         EXPECT_EQ(r1, e1);
486         auto r2 = this->find_first_byte_of(s2, s1);
487         auto f2 = std::find_first_of(s2.begin(), s2.end(),
488                                      s1.begin(), s1.end());
489         auto e2 = (f2 == s2.end()) ? StringPiece::npos : f2 - s2.begin();
490         EXPECT_EQ(r2, e2);
491         freeProtectedBuf(buf1);
492         freeProtectedBuf(buf2);
493       }
494     }
495   }
496 }