Bugfix uriEscapeTable generate.
[folly.git] / folly / test / StringTest.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 #include <folly/String.h>
18
19 #include <cstdarg>
20 #include <random>
21 #include <boost/algorithm/string.hpp>
22 #include <gtest/gtest.h>
23
24 #include <folly/Benchmark.h>
25
26 using namespace folly;
27 using namespace std;
28
29 TEST(StringPrintf, BasicTest) {
30   EXPECT_EQ("abc", stringPrintf("%s", "abc"));
31   EXPECT_EQ("abc", stringPrintf("%sbc", "a"));
32   EXPECT_EQ("abc", stringPrintf("a%sc", "b"));
33   EXPECT_EQ("abc", stringPrintf("ab%s", "c"));
34
35   EXPECT_EQ("abc", stringPrintf("abc"));
36 }
37
38 TEST(StringPrintf, NumericFormats) {
39   EXPECT_EQ("12", stringPrintf("%d", 12));
40   EXPECT_EQ("5000000000", stringPrintf("%ld", 5000000000UL));
41   EXPECT_EQ("5000000000", stringPrintf("%ld", 5000000000L));
42   EXPECT_EQ("-5000000000", stringPrintf("%ld", -5000000000L));
43   EXPECT_EQ("-1", stringPrintf("%d", 0xffffffff));
44   EXPECT_EQ("-1", stringPrintf("%ld", 0xffffffffffffffff));
45   EXPECT_EQ("-1", stringPrintf("%ld", 0xffffffffffffffffUL));
46
47   EXPECT_EQ("7.7", stringPrintf("%1.1f", 7.7));
48   EXPECT_EQ("7.7", stringPrintf("%1.1lf", 7.7));
49   EXPECT_EQ("7.70000000000000018",
50             stringPrintf("%.17f", 7.7));
51   EXPECT_EQ("7.70000000000000018",
52             stringPrintf("%.17lf", 7.7));
53 }
54
55 TEST(StringPrintf, Appending) {
56   string s;
57   stringAppendf(&s, "a%s", "b");
58   stringAppendf(&s, "%c", 'c');
59   EXPECT_EQ(s, "abc");
60   stringAppendf(&s, " %d", 123);
61   EXPECT_EQ(s, "abc 123");
62 }
63
64 void vprintfCheck(const char* expected, const char* fmt, ...) {
65   va_list apOrig;
66   va_start(apOrig, fmt);
67   SCOPE_EXIT {
68     va_end(apOrig);
69   };
70   va_list ap;
71   va_copy(ap, apOrig);
72   SCOPE_EXIT {
73     va_end(ap);
74   };
75
76   // Check both APIs for calling stringVPrintf()
77   EXPECT_EQ(expected, stringVPrintf(fmt, ap));
78   va_end(ap);
79   va_copy(ap, apOrig);
80
81   std::string out;
82   stringVPrintf(&out, fmt, ap);
83   va_end(ap);
84   va_copy(ap, apOrig);
85   EXPECT_EQ(expected, out);
86
87   // Check stringVAppendf() as well
88   std::string prefix = "foobar";
89   out = prefix;
90   EXPECT_EQ(prefix + expected, stringVAppendf(&out, fmt, ap));
91   va_end(ap);
92   va_copy(ap, apOrig);
93 }
94
95 void vprintfError(const char* fmt, ...) {
96   va_list ap;
97   va_start(ap, fmt);
98   SCOPE_EXIT {
99     va_end(ap);
100   };
101
102   // OSX's sprintf family does not return a negative number on a bad format
103   // string, but Linux does. It's unclear to me which behavior is more
104   // correct.
105 #if !__APPLE__
106   EXPECT_THROW({stringVPrintf(fmt, ap);},
107                std::runtime_error);
108 #endif
109 }
110
111 TEST(StringPrintf, VPrintf) {
112   vprintfCheck("foo", "%s", "foo");
113   vprintfCheck("long string requiring reallocation 1 2 3 0x12345678",
114                "%s %s %d %d %d %#x",
115                "long string", "requiring reallocation", 1, 2, 3, 0x12345678);
116   vprintfError("bogus%", "foo");
117 }
118
119 TEST(StringPrintf, VariousSizes) {
120   // Test a wide variety of output sizes, making sure to cross the
121   // vsnprintf buffer boundary implementation detail.
122   for (int i = 0; i < 4096; ++i) {
123     string expected(i + 1, 'a');
124     expected = "X" + expected + "X";
125     string result = stringPrintf("%s", expected.c_str());
126     EXPECT_EQ(expected.size(), result.size());
127     EXPECT_EQ(expected, result);
128   }
129
130   EXPECT_EQ("abc12345678910111213141516171819202122232425xyz",
131             stringPrintf("abc%d%d%d%d%d%d%d%d%d%d%d%d%d%d"
132                          "%d%d%d%d%d%d%d%d%d%d%dxyz",
133                          1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
134                          17, 18, 19, 20, 21, 22, 23, 24, 25));
135 }
136
137 TEST(StringPrintf, oldStringPrintfTests) {
138   EXPECT_EQ(string("a/b/c/d"),
139             stringPrintf("%s/%s/%s/%s", "a", "b", "c", "d"));
140
141   EXPECT_EQ(string("    5    10"),
142             stringPrintf("%5d %5d", 5, 10));
143
144   // check printing w/ a big buffer
145   for (int size = (1 << 8); size <= (1 << 15); size <<= 1) {
146     string a(size, 'z');
147     string b = stringPrintf("%s", a.c_str());
148     EXPECT_EQ(a.size(), b.size());
149   }
150 }
151
152 TEST(StringPrintf, oldStringAppendf) {
153   string s = "hello";
154   stringAppendf(&s, "%s/%s/%s/%s", "a", "b", "c", "d");
155   EXPECT_EQ(string("helloa/b/c/d"), s);
156 }
157
158 // A simple benchmark that tests various output sizes for a simple
159 // input; the goal is to measure the output buffer resize code cost.
160 void stringPrintfOutputSize(int iters, int param) {
161   string buffer;
162   BENCHMARK_SUSPEND { buffer.resize(param, 'x'); }
163
164   for (int64_t i = 0; i < iters; ++i) {
165     string s = stringPrintf("msg: %d, %d, %s", 10, 20, buffer.c_str());
166   }
167 }
168
169 // The first few of these tend to fit in the inline buffer, while the
170 // subsequent ones cross that limit, trigger a second vsnprintf, and
171 // exercise a different codepath.
172 BENCHMARK_PARAM(stringPrintfOutputSize, 1)
173 BENCHMARK_PARAM(stringPrintfOutputSize, 4)
174 BENCHMARK_PARAM(stringPrintfOutputSize, 16)
175 BENCHMARK_PARAM(stringPrintfOutputSize, 64)
176 BENCHMARK_PARAM(stringPrintfOutputSize, 256)
177 BENCHMARK_PARAM(stringPrintfOutputSize, 1024)
178
179 // Benchmark simple stringAppendf behavior to show a pathology Lovro
180 // reported (t5735468).
181 BENCHMARK(stringPrintfAppendfBenchmark, iters) {
182   for (unsigned int i = 0; i < iters; ++i) {
183     string s;
184     BENCHMARK_SUSPEND { s.reserve(300000); }
185     for (int j = 0; j < 300000; ++j) {
186       stringAppendf(&s, "%d", 1);
187     }
188   }
189 }
190
191 TEST(Escape, cEscape) {
192   EXPECT_EQ("hello world", cEscape<std::string>("hello world"));
193   EXPECT_EQ("hello \\\\world\\\" goodbye",
194             cEscape<std::string>("hello \\world\" goodbye"));
195   EXPECT_EQ("hello\\nworld", cEscape<std::string>("hello\nworld"));
196   EXPECT_EQ("hello\\377\\376", cEscape<std::string>("hello\xff\xfe"));
197 }
198
199 TEST(Escape, cUnescape) {
200   EXPECT_EQ("hello world", cUnescape<std::string>("hello world"));
201   EXPECT_EQ("hello \\world\" goodbye",
202             cUnescape<std::string>("hello \\\\world\\\" goodbye"));
203   EXPECT_EQ("hello\nworld", cUnescape<std::string>("hello\\nworld"));
204   EXPECT_EQ("hello\nworld", cUnescape<std::string>("hello\\012world"));
205   EXPECT_EQ("hello\nworld", cUnescape<std::string>("hello\\x0aworld"));
206   EXPECT_EQ("hello\xff\xfe", cUnescape<std::string>("hello\\377\\376"));
207   EXPECT_EQ("hello\xff\xfe", cUnescape<std::string>("hello\\xff\\xfe"));
208
209   EXPECT_THROW({cUnescape<std::string>("hello\\");},
210                std::invalid_argument);
211   EXPECT_THROW({cUnescape<std::string>("hello\\x");},
212                std::invalid_argument);
213   EXPECT_THROW({cUnescape<std::string>("hello\\q");},
214                std::invalid_argument);
215 }
216
217 TEST(Escape, uriEscape) {
218   EXPECT_EQ("hello%2c%20%2fworld", uriEscape<std::string>("hello, /world"));
219   EXPECT_EQ("hello%2c%20/world", uriEscape<std::string>("hello, /world",
220                                                         UriEscapeMode::PATH));
221   EXPECT_EQ("hello%2c+%2fworld", uriEscape<std::string>("hello, /world",
222                                                         UriEscapeMode::QUERY));
223   EXPECT_EQ(
224     "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~",
225     uriEscape<std::string>(
226       "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~")
227   );
228 }
229
230 TEST(Escape, uriUnescape) {
231   EXPECT_EQ("hello, /world", uriUnescape<std::string>("hello, /world"));
232   EXPECT_EQ("hello, /world", uriUnescape<std::string>("hello%2c%20%2fworld"));
233   EXPECT_EQ("hello,+/world", uriUnescape<std::string>("hello%2c+%2fworld"));
234   EXPECT_EQ("hello, /world", uriUnescape<std::string>("hello%2c+%2fworld",
235                                                       UriEscapeMode::QUERY));
236   EXPECT_EQ("hello/", uriUnescape<std::string>("hello%2f"));
237   EXPECT_EQ("hello/", uriUnescape<std::string>("hello%2F"));
238   EXPECT_THROW({uriUnescape<std::string>("hello%");},
239                std::invalid_argument);
240   EXPECT_THROW({uriUnescape<std::string>("hello%2");},
241                std::invalid_argument);
242   EXPECT_THROW({uriUnescape<std::string>("hello%2g");},
243                std::invalid_argument);
244 }
245
246 namespace {
247 void expectPrintable(StringPiece s) {
248   for (char c : s) {
249     EXPECT_LE(32, c);
250     EXPECT_GE(127, c);
251   }
252 }
253 }  // namespace
254
255 TEST(Escape, uriEscapeAllCombinations) {
256   char c[3];
257   c[2] = '\0';
258   StringPiece in(c, 2);
259   fbstring tmp;
260   fbstring out;
261   for (int i = 0; i < 256; ++i) {
262     c[0] = i;
263     for (int j = 0; j < 256; ++j) {
264       c[1] = j;
265       tmp.clear();
266       out.clear();
267       uriEscape(in, tmp);
268       expectPrintable(tmp);
269       uriUnescape(tmp, out);
270       EXPECT_EQ(in, out);
271     }
272   }
273 }
274
275 namespace {
276 bool isHex(int v) {
277   return ((v >= '0' && v <= '9') ||
278           (v >= 'A' && v <= 'F') ||
279           (v >= 'a' && v <= 'f'));
280 }
281 }  // namespace
282
283 TEST(Escape, uriUnescapePercentDecoding) {
284   char c[4] = {'%', '\0', '\0', '\0'};
285   StringPiece in(c, 3);
286   fbstring out;
287   unsigned int expected = 0;
288   for (int i = 0; i < 256; ++i) {
289     c[1] = i;
290     for (int j = 0; j < 256; ++j) {
291       c[2] = j;
292       if (isHex(i) && isHex(j)) {
293         out.clear();
294         uriUnescape(in, out);
295         EXPECT_EQ(1, out.size());
296         EXPECT_EQ(1, sscanf(c + 1, "%x", &expected));
297         unsigned char v = out[0];
298         EXPECT_EQ(expected, v);
299       } else {
300         EXPECT_THROW({uriUnescape(in, out);}, std::invalid_argument);
301       }
302     }
303   }
304 }
305
306 namespace {
307 fbstring cbmString;
308 fbstring cbmEscapedString;
309 fbstring cEscapedString;
310 fbstring cUnescapedString;
311 const size_t kCBmStringLength = 64 << 10;
312 const uint32_t kCPrintablePercentage = 90;
313
314 fbstring uribmString;
315 fbstring uribmEscapedString;
316 fbstring uriEscapedString;
317 fbstring uriUnescapedString;
318 const size_t kURIBmStringLength = 256;
319 const uint32_t kURIPassThroughPercentage = 50;
320
321 void initBenchmark() {
322   std::mt19937 rnd;
323
324   // C escape
325   std::uniform_int_distribution<uint32_t> printable(32, 126);
326   std::uniform_int_distribution<uint32_t> nonPrintable(0, 160);
327   std::uniform_int_distribution<uint32_t> percentage(0, 99);
328
329   cbmString.reserve(kCBmStringLength);
330   for (size_t i = 0; i < kCBmStringLength; ++i) {
331     unsigned char c;
332     if (percentage(rnd) < kCPrintablePercentage) {
333       c = printable(rnd);
334     } else {
335       c = nonPrintable(rnd);
336       // Generate characters in both non-printable ranges:
337       // 0..31 and 127..255
338       if (c >= 32) {
339         c += (126 - 32) + 1;
340       }
341     }
342     cbmString.push_back(c);
343   }
344
345   cbmEscapedString = cEscape<fbstring>(cbmString);
346
347   // URI escape
348   std::uniform_int_distribution<uint32_t> passthrough('a', 'z');
349   std::string encodeChars = " ?!\"',+[]";
350   std::uniform_int_distribution<uint32_t> encode(0, encodeChars.size() - 1);
351
352   uribmString.reserve(kURIBmStringLength);
353   for (size_t i = 0; i < kURIBmStringLength; ++i) {
354     unsigned char c;
355     if (percentage(rnd) < kURIPassThroughPercentage) {
356       c = passthrough(rnd);
357     } else {
358       c = encodeChars[encode(rnd)];
359     }
360     uribmString.push_back(c);
361   }
362
363   uribmEscapedString = uriEscape<fbstring>(uribmString);
364 }
365
366 BENCHMARK(BM_cEscape, iters) {
367   while (iters--) {
368     cEscapedString = cEscape<fbstring>(cbmString);
369     doNotOptimizeAway(cEscapedString.size());
370   }
371 }
372
373 BENCHMARK(BM_cUnescape, iters) {
374   while (iters--) {
375     cUnescapedString = cUnescape<fbstring>(cbmEscapedString);
376     doNotOptimizeAway(cUnescapedString.size());
377   }
378 }
379
380 BENCHMARK(BM_uriEscape, iters) {
381   while (iters--) {
382     uriEscapedString = uriEscape<fbstring>(uribmString);
383     doNotOptimizeAway(uriEscapedString.size());
384   }
385 }
386
387 BENCHMARK(BM_uriUnescape, iters) {
388   while (iters--) {
389     uriUnescapedString = uriUnescape<fbstring>(uribmEscapedString);
390     doNotOptimizeAway(uriUnescapedString.size());
391   }
392 }
393
394 }  // namespace
395
396 namespace {
397
398 double pow2(int exponent) {
399   return double(int64_t(1) << exponent);
400 }
401
402 }  // namespace
403 struct PrettyTestCase{
404   std::string prettyString;
405   double realValue;
406   PrettyType prettyType;
407 };
408
409 PrettyTestCase prettyTestCases[] =
410 {
411   {string("8.53e+07 s "), 85.3e6,  PRETTY_TIME},
412   {string("8.53e+07 s "), 85.3e6,  PRETTY_TIME},
413   {string("85.3 ms"), 85.3e-3,  PRETTY_TIME},
414   {string("85.3 us"), 85.3e-6,  PRETTY_TIME},
415   {string("85.3 ns"), 85.3e-9,  PRETTY_TIME},
416   {string("85.3 ps"), 85.3e-12,  PRETTY_TIME},
417   {string("8.53e-14 s "), 85.3e-15,  PRETTY_TIME},
418
419   {string("0 s "), 0,  PRETTY_TIME},
420   {string("1 s "), 1.0,  PRETTY_TIME},
421   {string("1 ms"), 1.0e-3,  PRETTY_TIME},
422   {string("1 us"), 1.0e-6,  PRETTY_TIME},
423   {string("1 ns"), 1.0e-9,  PRETTY_TIME},
424   {string("1 ps"), 1.0e-12,  PRETTY_TIME},
425
426   // check bytes printing
427   {string("853 B "), 853.,  PRETTY_BYTES},
428   {string("833 kB"), 853.e3,  PRETTY_BYTES},
429   {string("813.5 MB"), 853.e6,  PRETTY_BYTES},
430   {string("7.944 GB"), 8.53e9,  PRETTY_BYTES},
431   {string("794.4 GB"), 853.e9,  PRETTY_BYTES},
432   {string("775.8 TB"), 853.e12,  PRETTY_BYTES},
433
434   {string("0 B "), 0,  PRETTY_BYTES},
435   {string("1 B "), pow2(0),  PRETTY_BYTES},
436   {string("1 kB"), pow2(10),  PRETTY_BYTES},
437   {string("1 MB"), pow2(20),  PRETTY_BYTES},
438   {string("1 GB"), pow2(30),  PRETTY_BYTES},
439   {string("1 TB"), pow2(40),  PRETTY_BYTES},
440
441   {string("853 B  "), 853.,  PRETTY_BYTES_IEC},
442   {string("833 KiB"), 853.e3,  PRETTY_BYTES_IEC},
443   {string("813.5 MiB"), 853.e6,  PRETTY_BYTES_IEC},
444   {string("7.944 GiB"), 8.53e9,  PRETTY_BYTES_IEC},
445   {string("794.4 GiB"), 853.e9,  PRETTY_BYTES_IEC},
446   {string("775.8 TiB"), 853.e12,  PRETTY_BYTES_IEC},
447
448   {string("0 B  "), 0,  PRETTY_BYTES_IEC},
449   {string("1 B  "), pow2(0),  PRETTY_BYTES_IEC},
450   {string("1 KiB"), pow2(10),  PRETTY_BYTES_IEC},
451   {string("1 MiB"), pow2(20),  PRETTY_BYTES_IEC},
452   {string("1 GiB"), pow2(30),  PRETTY_BYTES_IEC},
453   {string("1 TiB"), pow2(40),  PRETTY_BYTES_IEC},
454
455   // check bytes metric printing
456   {string("853 B "), 853.,  PRETTY_BYTES_METRIC},
457   {string("853 kB"), 853.e3,  PRETTY_BYTES_METRIC},
458   {string("853 MB"), 853.e6,  PRETTY_BYTES_METRIC},
459   {string("8.53 GB"), 8.53e9,  PRETTY_BYTES_METRIC},
460   {string("853 GB"), 853.e9,  PRETTY_BYTES_METRIC},
461   {string("853 TB"), 853.e12,  PRETTY_BYTES_METRIC},
462
463   {string("0 B "), 0,  PRETTY_BYTES_METRIC},
464   {string("1 B "), 1.0,  PRETTY_BYTES_METRIC},
465   {string("1 kB"), 1.0e+3,  PRETTY_BYTES_METRIC},
466   {string("1 MB"), 1.0e+6,  PRETTY_BYTES_METRIC},
467
468   {string("1 GB"), 1.0e+9,  PRETTY_BYTES_METRIC},
469   {string("1 TB"), 1.0e+12,  PRETTY_BYTES_METRIC},
470
471   // check metric-units (powers of 1000) printing
472   {string("853  "), 853.,  PRETTY_UNITS_METRIC},
473   {string("853 k"), 853.e3,  PRETTY_UNITS_METRIC},
474   {string("853 M"), 853.e6,  PRETTY_UNITS_METRIC},
475   {string("8.53 bil"), 8.53e9,  PRETTY_UNITS_METRIC},
476   {string("853 bil"), 853.e9,  PRETTY_UNITS_METRIC},
477   {string("853 tril"), 853.e12,  PRETTY_UNITS_METRIC},
478
479   // check binary-units (powers of 1024) printing
480   {string("0  "), 0,  PRETTY_UNITS_BINARY},
481   {string("1  "), pow2(0),  PRETTY_UNITS_BINARY},
482   {string("1 k"), pow2(10),  PRETTY_UNITS_BINARY},
483   {string("1 M"), pow2(20),  PRETTY_UNITS_BINARY},
484   {string("1 G"), pow2(30),  PRETTY_UNITS_BINARY},
485   {string("1 T"), pow2(40),  PRETTY_UNITS_BINARY},
486
487   {string("1023  "), pow2(10) - 1,  PRETTY_UNITS_BINARY},
488   {string("1024 k"), pow2(20) - 1,  PRETTY_UNITS_BINARY},
489   {string("1024 M"), pow2(30) - 1,  PRETTY_UNITS_BINARY},
490   {string("1024 G"), pow2(40) - 1,  PRETTY_UNITS_BINARY},
491
492   {string("0   "), 0,  PRETTY_UNITS_BINARY_IEC},
493   {string("1   "), pow2(0),  PRETTY_UNITS_BINARY_IEC},
494   {string("1 Ki"), pow2(10),  PRETTY_UNITS_BINARY_IEC},
495   {string("1 Mi"), pow2(20),  PRETTY_UNITS_BINARY_IEC},
496   {string("1 Gi"), pow2(30),  PRETTY_UNITS_BINARY_IEC},
497   {string("1 Ti"), pow2(40),  PRETTY_UNITS_BINARY_IEC},
498
499   {string("1023   "), pow2(10) - 1,  PRETTY_UNITS_BINARY_IEC},
500   {string("1024 Ki"), pow2(20) - 1,  PRETTY_UNITS_BINARY_IEC},
501   {string("1024 Mi"), pow2(30) - 1,  PRETTY_UNITS_BINARY_IEC},
502   {string("1024 Gi"), pow2(40) - 1,  PRETTY_UNITS_BINARY_IEC},
503
504   //check border SI cases
505
506   {string("1 Y"), 1e24,  PRETTY_SI},
507   {string("10 Y"), 1e25,  PRETTY_SI},
508   {string("1 y"), 1e-24,  PRETTY_SI},
509   {string("10 y"), 1e-23,  PRETTY_SI},
510
511   // check that negative values work
512   {string("-85.3 s "), -85.3,  PRETTY_TIME},
513   {string("-85.3 ms"), -85.3e-3,  PRETTY_TIME},
514   {string("-85.3 us"), -85.3e-6,  PRETTY_TIME},
515   {string("-85.3 ns"), -85.3e-9,  PRETTY_TIME},
516   // end of test
517   {string("endoftest"), 0, PRETTY_NUM_TYPES}
518 };
519
520 TEST(PrettyPrint, Basic) {
521   for (int i = 0; prettyTestCases[i].prettyType != PRETTY_NUM_TYPES; ++i){
522     const PrettyTestCase& prettyTest = prettyTestCases[i];
523     EXPECT_EQ(prettyTest.prettyString,
524               prettyPrint(prettyTest.realValue, prettyTest.prettyType));
525   }
526 }
527
528 TEST(PrettyToDouble, Basic) {
529   // check manually created tests
530   for (int i = 0; prettyTestCases[i].prettyType != PRETTY_NUM_TYPES; ++i){
531     PrettyTestCase testCase = prettyTestCases[i];
532     PrettyType formatType = testCase.prettyType;
533     double x = testCase.realValue;
534     std::string testString = testCase.prettyString;
535     double recoveredX;
536     try{
537       recoveredX = prettyToDouble(testString, formatType);
538     } catch (std::range_error &ex){
539       EXPECT_TRUE(false);
540     }
541     double relativeError = fabs(x) < 1e-5 ? (x-recoveredX) :
542                                             (x - recoveredX) / x;
543     EXPECT_NEAR(0, relativeError, 1e-3);
544   }
545
546   // checks for compatibility with prettyPrint over the whole parameter space
547   for (int i = 0 ; i < PRETTY_NUM_TYPES; ++i){
548     PrettyType formatType = static_cast<PrettyType>(i);
549     for (double x = 1e-18; x < 1e40; x *= 1.9){
550       bool addSpace = static_cast<PrettyType> (i) == PRETTY_SI;
551       for (int it = 0; it < 2; ++it, addSpace = true){
552         double recoveredX;
553         try{
554           recoveredX = prettyToDouble(prettyPrint(x, formatType, addSpace),
555                                              formatType);
556         } catch (std::range_error &ex){
557           EXPECT_TRUE(false);
558         }
559         double relativeError = (x - recoveredX) / x;
560         EXPECT_NEAR(0, relativeError, 1e-3);
561       }
562     }
563   }
564
565   // check for incorrect values
566   EXPECT_THROW(prettyToDouble("10Mx", PRETTY_SI), std::range_error);
567   EXPECT_THROW(prettyToDouble("10 Mx", PRETTY_SI), std::range_error);
568   EXPECT_THROW(prettyToDouble("10 M x", PRETTY_SI), std::range_error);
569
570   StringPiece testString = "10Mx";
571   EXPECT_DOUBLE_EQ(prettyToDouble(&testString, PRETTY_UNITS_METRIC), 10e6);
572   EXPECT_EQ(testString, "x");
573 }
574
575 TEST(PrettyPrint, HexDump) {
576   std::string a("abc\x00\x02\xa0", 6);  // embedded NUL
577   EXPECT_EQ(
578     "00000000  61 62 63 00 02 a0                                 "
579     "|abc...          |\n",
580     hexDump(a.data(), a.size()));
581
582   a = "abcdefghijklmnopqrstuvwxyz";
583   EXPECT_EQ(
584     "00000000  61 62 63 64 65 66 67 68  69 6a 6b 6c 6d 6e 6f 70  "
585     "|abcdefghijklmnop|\n"
586     "00000010  71 72 73 74 75 76 77 78  79 7a                    "
587     "|qrstuvwxyz      |\n",
588     hexDump(a.data(), a.size()));
589 }
590
591 TEST(System, errnoStr) {
592   errno = EACCES;
593   EXPECT_EQ(EACCES, errno);
594   EXPECT_EQ(EACCES, errno);  // twice to make sure EXPECT_EQ doesn't change it
595
596   fbstring expected = strerror(ENOENT);
597
598   errno = EACCES;
599   EXPECT_EQ(expected, errnoStr(ENOENT));
600   // Ensure that errno isn't changed
601   EXPECT_EQ(EACCES, errno);
602
603   // Per POSIX, all errno values are positive, so -1 is invalid
604   errnoStr(-1);
605
606   // Ensure that errno isn't changed
607   EXPECT_EQ(EACCES, errno);
608 }
609
610 namespace folly_test {
611 struct ThisIsAVeryLongStructureName {
612 };
613 }  // namespace folly_test
614
615 #if FOLLY_HAVE_CPLUS_DEMANGLE_V3_CALLBACK
616 TEST(System, demangle) {
617   char expected[] = "folly_test::ThisIsAVeryLongStructureName";
618   EXPECT_STREQ(
619       expected,
620       demangle(typeid(folly_test::ThisIsAVeryLongStructureName)).c_str());
621
622   {
623     char buf[sizeof(expected)];
624     EXPECT_EQ(sizeof(expected) - 1,
625               demangle(typeid(folly_test::ThisIsAVeryLongStructureName),
626                        buf, sizeof(buf)));
627     EXPECT_STREQ(expected, buf);
628
629     EXPECT_EQ(sizeof(expected) - 1,
630               demangle(typeid(folly_test::ThisIsAVeryLongStructureName),
631                        buf, 11));
632     EXPECT_STREQ("folly_test", buf);
633   }
634 }
635 #endif
636
637 namespace {
638
639 template<template<class,class> class VectorType>
640 void splitTest() {
641   VectorType<string,std::allocator<string> > parts;
642
643   folly::split(',', "a,b,c", parts);
644   EXPECT_EQ(parts.size(), 3);
645   EXPECT_EQ(parts[0], "a");
646   EXPECT_EQ(parts[1], "b");
647   EXPECT_EQ(parts[2], "c");
648   parts.clear();
649
650   folly::split(',', StringPiece("a,b,c"), parts);
651   EXPECT_EQ(parts.size(), 3);
652   EXPECT_EQ(parts[0], "a");
653   EXPECT_EQ(parts[1], "b");
654   EXPECT_EQ(parts[2], "c");
655   parts.clear();
656
657   folly::split(',', string("a,b,c"), parts);
658   EXPECT_EQ(parts.size(), 3);
659   EXPECT_EQ(parts[0], "a");
660   EXPECT_EQ(parts[1], "b");
661   EXPECT_EQ(parts[2], "c");
662   parts.clear();
663
664   folly::split(',', "a,,c", parts);
665   EXPECT_EQ(parts.size(), 3);
666   EXPECT_EQ(parts[0], "a");
667   EXPECT_EQ(parts[1], "");
668   EXPECT_EQ(parts[2], "c");
669   parts.clear();
670
671   folly::split(',', string("a,,c"), parts);
672   EXPECT_EQ(parts.size(), 3);
673   EXPECT_EQ(parts[0], "a");
674   EXPECT_EQ(parts[1], "");
675   EXPECT_EQ(parts[2], "c");
676   parts.clear();
677
678   folly::split(',', "a,,c", parts, true);
679   EXPECT_EQ(parts.size(), 2);
680   EXPECT_EQ(parts[0], "a");
681   EXPECT_EQ(parts[1], "c");
682   parts.clear();
683
684   folly::split(',', string("a,,c"), parts, true);
685   EXPECT_EQ(parts.size(), 2);
686   EXPECT_EQ(parts[0], "a");
687   EXPECT_EQ(parts[1], "c");
688   parts.clear();
689
690   folly::split(',', string(",,a,,c,,,"), parts, true);
691   EXPECT_EQ(parts.size(), 2);
692   EXPECT_EQ(parts[0], "a");
693   EXPECT_EQ(parts[1], "c");
694   parts.clear();
695
696   // test multiple split w/o clear
697   folly::split(',', ",,a,,c,,,", parts, true);
698   EXPECT_EQ(parts.size(), 2);
699   EXPECT_EQ(parts[0], "a");
700   EXPECT_EQ(parts[1], "c");
701   folly::split(',', ",,a,,c,,,", parts, true);
702   EXPECT_EQ(parts.size(), 4);
703   EXPECT_EQ(parts[2], "a");
704   EXPECT_EQ(parts[3], "c");
705   parts.clear();
706
707   // test splits that with multi-line delimiter
708   folly::split("ab", "dabcabkdbkab", parts, true);
709   EXPECT_EQ(parts.size(), 3);
710   EXPECT_EQ(parts[0], "d");
711   EXPECT_EQ(parts[1], "c");
712   EXPECT_EQ(parts[2], "kdbk");
713   parts.clear();
714
715   // test last part is shorter than the delimiter
716   folly::split("bc", "abcd", parts, true);
717   EXPECT_EQ(parts.size(), 2);
718   EXPECT_EQ(parts[0], "a");
719   EXPECT_EQ(parts[1], "d");
720   parts.clear();
721
722   string orig = "ab2342asdfv~~!";
723   folly::split("", orig, parts, true);
724   EXPECT_EQ(parts.size(), 1);
725   EXPECT_EQ(parts[0], orig);
726   parts.clear();
727
728   folly::split("452x;o38asfsajsdlfdf.j", "asfds", parts, true);
729   EXPECT_EQ(parts.size(), 1);
730   EXPECT_EQ(parts[0], "asfds");
731   parts.clear();
732
733   folly::split("a", "", parts, true);
734   EXPECT_EQ(parts.size(), 0);
735   parts.clear();
736
737   folly::split("a", "", parts);
738   EXPECT_EQ(parts.size(), 1);
739   EXPECT_EQ(parts[0], "");
740   parts.clear();
741
742   folly::split("a", StringPiece(), parts, true);
743   EXPECT_EQ(parts.size(), 0);
744   parts.clear();
745
746   folly::split("a", StringPiece(), parts);
747   EXPECT_EQ(parts.size(), 1);
748   EXPECT_EQ(parts[0], "");
749   parts.clear();
750
751   folly::split("a", "abcdefg", parts, true);
752   EXPECT_EQ(parts.size(), 1);
753   EXPECT_EQ(parts[0], "bcdefg");
754   parts.clear();
755
756   orig = "All, , your base, are , , belong to us";
757   folly::split(", ", orig, parts, true);
758   EXPECT_EQ(parts.size(), 4);
759   EXPECT_EQ(parts[0], "All");
760   EXPECT_EQ(parts[1], "your base");
761   EXPECT_EQ(parts[2], "are ");
762   EXPECT_EQ(parts[3], "belong to us");
763   parts.clear();
764   folly::split(", ", orig, parts);
765   EXPECT_EQ(parts.size(), 6);
766   EXPECT_EQ(parts[0], "All");
767   EXPECT_EQ(parts[1], "");
768   EXPECT_EQ(parts[2], "your base");
769   EXPECT_EQ(parts[3], "are ");
770   EXPECT_EQ(parts[4], "");
771   EXPECT_EQ(parts[5], "belong to us");
772   parts.clear();
773
774   orig = ", Facebook, rul,es!, ";
775   folly::split(", ", orig, parts, true);
776   EXPECT_EQ(parts.size(), 2);
777   EXPECT_EQ(parts[0], "Facebook");
778   EXPECT_EQ(parts[1], "rul,es!");
779   parts.clear();
780   folly::split(", ", orig, parts);
781   EXPECT_EQ(parts.size(), 4);
782   EXPECT_EQ(parts[0], "");
783   EXPECT_EQ(parts[1], "Facebook");
784   EXPECT_EQ(parts[2], "rul,es!");
785   EXPECT_EQ(parts[3], "");
786 }
787
788 template<template<class,class> class VectorType>
789 void piecesTest() {
790   VectorType<StringPiece,std::allocator<StringPiece> > pieces;
791   VectorType<StringPiece,std::allocator<StringPiece> > pieces2;
792
793   folly::split(',', "a,b,c", pieces);
794   EXPECT_EQ(pieces.size(), 3);
795   EXPECT_EQ(pieces[0], "a");
796   EXPECT_EQ(pieces[1], "b");
797   EXPECT_EQ(pieces[2], "c");
798
799   pieces.clear();
800
801   folly::split(',', "a,,c", pieces);
802   EXPECT_EQ(pieces.size(), 3);
803   EXPECT_EQ(pieces[0], "a");
804   EXPECT_EQ(pieces[1], "");
805   EXPECT_EQ(pieces[2], "c");
806   pieces.clear();
807
808   folly::split(',', "a,,c", pieces, true);
809   EXPECT_EQ(pieces.size(), 2);
810   EXPECT_EQ(pieces[0], "a");
811   EXPECT_EQ(pieces[1], "c");
812   pieces.clear();
813
814   folly::split(',', ",,a,,c,,,", pieces, true);
815   EXPECT_EQ(pieces.size(), 2);
816   EXPECT_EQ(pieces[0], "a");
817   EXPECT_EQ(pieces[1], "c");
818   pieces.clear();
819
820   // test multiple split w/o clear
821   folly::split(',', ",,a,,c,,,", pieces, true);
822   EXPECT_EQ(pieces.size(), 2);
823   EXPECT_EQ(pieces[0], "a");
824   EXPECT_EQ(pieces[1], "c");
825   folly::split(',', ",,a,,c,,,", pieces, true);
826   EXPECT_EQ(pieces.size(), 4);
827   EXPECT_EQ(pieces[2], "a");
828   EXPECT_EQ(pieces[3], "c");
829   pieces.clear();
830
831   // test multiple split rounds
832   folly::split(",", "a_b,c_d", pieces);
833   EXPECT_EQ(pieces.size(), 2);
834   EXPECT_EQ(pieces[0], "a_b");
835   EXPECT_EQ(pieces[1], "c_d");
836   folly::split("_", pieces[0], pieces2);
837   EXPECT_EQ(pieces2.size(), 2);
838   EXPECT_EQ(pieces2[0], "a");
839   EXPECT_EQ(pieces2[1], "b");
840   pieces2.clear();
841   folly::split("_", pieces[1], pieces2);
842   EXPECT_EQ(pieces2.size(), 2);
843   EXPECT_EQ(pieces2[0], "c");
844   EXPECT_EQ(pieces2[1], "d");
845   pieces.clear();
846   pieces2.clear();
847
848   // test splits that with multi-line delimiter
849   folly::split("ab", "dabcabkdbkab", pieces, true);
850   EXPECT_EQ(pieces.size(), 3);
851   EXPECT_EQ(pieces[0], "d");
852   EXPECT_EQ(pieces[1], "c");
853   EXPECT_EQ(pieces[2], "kdbk");
854   pieces.clear();
855
856   string orig = "ab2342asdfv~~!";
857   folly::split("", orig.c_str(), pieces, true);
858   EXPECT_EQ(pieces.size(), 1);
859   EXPECT_EQ(pieces[0], orig);
860   pieces.clear();
861
862   folly::split("452x;o38asfsajsdlfdf.j", "asfds", pieces, true);
863   EXPECT_EQ(pieces.size(), 1);
864   EXPECT_EQ(pieces[0], "asfds");
865   pieces.clear();
866
867   folly::split("a", "", pieces, true);
868   EXPECT_EQ(pieces.size(), 0);
869   pieces.clear();
870
871   folly::split("a", "", pieces);
872   EXPECT_EQ(pieces.size(), 1);
873   EXPECT_EQ(pieces[0], "");
874   pieces.clear();
875
876   folly::split("a", "abcdefg", pieces, true);
877   EXPECT_EQ(pieces.size(), 1);
878   EXPECT_EQ(pieces[0], "bcdefg");
879   pieces.clear();
880
881   orig = "All, , your base, are , , belong to us";
882   folly::split(", ", orig, pieces, true);
883   EXPECT_EQ(pieces.size(), 4);
884   EXPECT_EQ(pieces[0], "All");
885   EXPECT_EQ(pieces[1], "your base");
886   EXPECT_EQ(pieces[2], "are ");
887   EXPECT_EQ(pieces[3], "belong to us");
888   pieces.clear();
889   folly::split(", ", orig, pieces);
890   EXPECT_EQ(pieces.size(), 6);
891   EXPECT_EQ(pieces[0], "All");
892   EXPECT_EQ(pieces[1], "");
893   EXPECT_EQ(pieces[2], "your base");
894   EXPECT_EQ(pieces[3], "are ");
895   EXPECT_EQ(pieces[4], "");
896   EXPECT_EQ(pieces[5], "belong to us");
897   pieces.clear();
898
899   orig = ", Facebook, rul,es!, ";
900   folly::split(", ", orig, pieces, true);
901   EXPECT_EQ(pieces.size(), 2);
902   EXPECT_EQ(pieces[0], "Facebook");
903   EXPECT_EQ(pieces[1], "rul,es!");
904   pieces.clear();
905   folly::split(", ", orig, pieces);
906   EXPECT_EQ(pieces.size(), 4);
907   EXPECT_EQ(pieces[0], "");
908   EXPECT_EQ(pieces[1], "Facebook");
909   EXPECT_EQ(pieces[2], "rul,es!");
910   EXPECT_EQ(pieces[3], "");
911   pieces.clear();
912
913   const char* str = "a,b";
914   folly::split(',', StringPiece(str), pieces);
915   EXPECT_EQ(pieces.size(), 2);
916   EXPECT_EQ(pieces[0], "a");
917   EXPECT_EQ(pieces[1], "b");
918   EXPECT_EQ(pieces[0].start(), str);
919   EXPECT_EQ(pieces[1].start(), str + 2);
920
921   std::set<StringPiece> unique;
922   folly::splitTo<StringPiece>(":", "asd:bsd:asd:asd:bsd:csd::asd",
923     std::inserter(unique, unique.begin()), true);
924   EXPECT_EQ(unique.size(), 3);
925   if (unique.size() == 3) {
926     EXPECT_EQ(*unique.begin(), "asd");
927     EXPECT_EQ(*--unique.end(), "csd");
928   }
929
930   VectorType<fbstring,std::allocator<fbstring> > blah;
931   folly::split('-', "a-b-c-d-f-e", blah);
932   EXPECT_EQ(blah.size(), 6);
933 }
934
935 }
936
937 TEST(Split, split_vector) {
938   splitTest<std::vector>();
939 }
940 TEST(Split, split_fbvector) {
941   splitTest<folly::fbvector>();
942 }
943 TEST(Split, pieces_vector) {
944   piecesTest<std::vector>();
945 }
946 TEST(Split, pieces_fbvector) {
947   piecesTest<folly::fbvector>();
948 }
949
950 TEST(Split, fixed) {
951   StringPiece a, b, c, d;
952
953   EXPECT_TRUE(folly::split<false>('.', "a.b.c.d", a, b, c, d));
954   EXPECT_TRUE(folly::split<false>('.', "a.b.c", a, b, c));
955   EXPECT_TRUE(folly::split<false>('.', "a.b", a, b));
956   EXPECT_TRUE(folly::split<false>('.', "a", a));
957
958   EXPECT_TRUE(folly::split('.', "a.b.c.d", a, b, c, d));
959   EXPECT_TRUE(folly::split('.', "a.b.c", a, b, c));
960   EXPECT_TRUE(folly::split('.', "a.b", a, b));
961   EXPECT_TRUE(folly::split('.', "a", a));
962
963   EXPECT_TRUE(folly::split<false>('.', "a.b.c", a, b, c));
964   EXPECT_EQ("a", a);
965   EXPECT_EQ("b", b);
966   EXPECT_EQ("c", c);
967   EXPECT_FALSE(folly::split<false>('.', "a.b", a, b, c));
968   EXPECT_TRUE(folly::split<false>('.', "a.b.c", a, b));
969   EXPECT_EQ("a", a);
970   EXPECT_EQ("b.c", b);
971
972   EXPECT_TRUE(folly::split('.', "a.b.c", a, b, c));
973   EXPECT_EQ("a", a);
974   EXPECT_EQ("b", b);
975   EXPECT_EQ("c", c);
976   EXPECT_FALSE(folly::split('.', "a.b.c", a, b));
977   EXPECT_FALSE(folly::split('.', "a.b", a, b, c));
978
979   EXPECT_TRUE(folly::split<false>('.', "a.b", a, b));
980   EXPECT_EQ("a", a);
981   EXPECT_EQ("b", b);
982   EXPECT_FALSE(folly::split<false>('.', "a", a, b));
983   EXPECT_TRUE(folly::split<false>('.', "a.b", a));
984   EXPECT_EQ("a.b", a);
985
986   EXPECT_TRUE(folly::split('.', "a.b", a, b));
987   EXPECT_EQ("a", a);
988   EXPECT_EQ("b", b);
989   EXPECT_FALSE(folly::split('.', "a", a, b));
990   EXPECT_FALSE(folly::split('.', "a.b", a));
991 }
992
993 TEST(Split, std_string_fixed) {
994   std::string a, b, c, d;
995
996   EXPECT_TRUE(folly::split<false>('.', "a.b.c.d", a, b, c, d));
997   EXPECT_TRUE(folly::split<false>('.', "a.b.c", a, b, c));
998   EXPECT_TRUE(folly::split<false>('.', "a.b", a, b));
999   EXPECT_TRUE(folly::split<false>('.', "a", a));
1000
1001   EXPECT_TRUE(folly::split('.', "a.b.c.d", a, b, c, d));
1002   EXPECT_TRUE(folly::split('.', "a.b.c", a, b, c));
1003   EXPECT_TRUE(folly::split('.', "a.b", a, b));
1004   EXPECT_TRUE(folly::split('.', "a", a));
1005
1006   EXPECT_TRUE(folly::split<false>('.', "a.b.c", a, b, c));
1007   EXPECT_EQ("a", a);
1008   EXPECT_EQ("b", b);
1009   EXPECT_EQ("c", c);
1010   EXPECT_FALSE(folly::split<false>('.', "a.b", a, b, c));
1011   EXPECT_TRUE(folly::split<false>('.', "a.b.c", a, b));
1012   EXPECT_EQ("a", a);
1013   EXPECT_EQ("b.c", b);
1014
1015   EXPECT_TRUE(folly::split('.', "a.b.c", a, b, c));
1016   EXPECT_EQ("a", a);
1017   EXPECT_EQ("b", b);
1018   EXPECT_EQ("c", c);
1019   EXPECT_FALSE(folly::split('.', "a.b.c", a, b));
1020   EXPECT_FALSE(folly::split('.', "a.b", a, b, c));
1021
1022   EXPECT_TRUE(folly::split<false>('.', "a.b", a, b));
1023   EXPECT_EQ("a", a);
1024   EXPECT_EQ("b", b);
1025   EXPECT_FALSE(folly::split<false>('.', "a", a, b));
1026   EXPECT_TRUE(folly::split<false>('.', "a.b", a));
1027   EXPECT_EQ("a.b", a);
1028
1029   EXPECT_TRUE(folly::split('.', "a.b", a, b));
1030   EXPECT_EQ("a", a);
1031   EXPECT_EQ("b", b);
1032   EXPECT_FALSE(folly::split('.', "a", a, b));
1033   EXPECT_FALSE(folly::split('.', "a.b", a));
1034 }
1035
1036 TEST(Split, fixed_convert) {
1037   StringPiece a, d;
1038   int b;
1039   double c;
1040
1041   EXPECT_TRUE(folly::split(':', "a:13:14.7:b", a, b, c, d));
1042   EXPECT_EQ("a", a);
1043   EXPECT_EQ(13, b);
1044   EXPECT_NEAR(14.7, c, 1e-10);
1045   EXPECT_EQ("b", d);
1046
1047   EXPECT_TRUE(folly::split<false>(':', "b:14:15.3:c", a, b, c, d));
1048   EXPECT_EQ("b", a);
1049   EXPECT_EQ(14, b);
1050   EXPECT_NEAR(15.3, c, 1e-10);
1051   EXPECT_EQ("c", d);
1052
1053   EXPECT_FALSE(folly::split(':', "a:13:14.7:b", a, b, d));
1054
1055   EXPECT_TRUE(folly::split<false>(':', "a:13:14.7:b", a, b, d));
1056   EXPECT_EQ("a", a);
1057   EXPECT_EQ(13, b);
1058   EXPECT_EQ("14.7:b", d);
1059
1060   EXPECT_THROW(folly::split<false>(':', "a:13:14.7:b", a, b, c),
1061                std::range_error);
1062 }
1063
1064 TEST(String, join) {
1065   string output;
1066
1067   std::vector<int> empty = { };
1068   join(":", empty, output);
1069   EXPECT_TRUE(output.empty());
1070
1071   std::vector<std::string> input1 = { "1", "23", "456", "" };
1072   join(':', input1, output);
1073   EXPECT_EQ(output, "1:23:456:");
1074   output = join(':', input1);
1075   EXPECT_EQ(output, "1:23:456:");
1076
1077   auto input2 = { 1, 23, 456 };
1078   join("-*-", input2, output);
1079   EXPECT_EQ(output, "1-*-23-*-456");
1080   output = join("-*-", input2);
1081   EXPECT_EQ(output, "1-*-23-*-456");
1082
1083   auto input3 = { 'f', 'a', 'c', 'e', 'b', 'o', 'o', 'k' };
1084   join("", input3, output);
1085   EXPECT_EQ(output, "facebook");
1086
1087   join("_", { "", "f", "a", "c", "e", "b", "o", "o", "k", "" }, output);
1088   EXPECT_EQ(output, "_f_a_c_e_b_o_o_k_");
1089
1090   output = join("", input3.begin(), input3.end());
1091   EXPECT_EQ(output, "facebook");
1092 }
1093
1094 TEST(String, hexlify) {
1095   string input1 = "0123";
1096   string output1;
1097   EXPECT_TRUE(hexlify(input1, output1));
1098   EXPECT_EQ(output1, "30313233");
1099
1100   fbstring input2 = "abcdefg";
1101   input2[1] = 0;
1102   input2[3] = 0xff;
1103   input2[5] = 0xb6;
1104   fbstring output2;
1105   EXPECT_TRUE(hexlify(input2, output2));
1106   EXPECT_EQ(output2, "610063ff65b667");
1107 }
1108
1109 TEST(String, unhexlify) {
1110   string input1 = "30313233";
1111   string output1;
1112   EXPECT_TRUE(unhexlify(input1, output1));
1113   EXPECT_EQ(output1, "0123");
1114
1115   fbstring input2 = "610063ff65b667";
1116   fbstring output2;
1117   EXPECT_TRUE(unhexlify(input2, output2));
1118   EXPECT_EQ(output2.size(), 7);
1119   EXPECT_EQ(output2[0], 'a');
1120   EXPECT_EQ(output2[1], 0);
1121   EXPECT_EQ(output2[2], 'c');
1122   EXPECT_EQ(output2[3] & 0xff, 0xff);
1123   EXPECT_EQ(output2[4], 'e');
1124   EXPECT_EQ(output2[5] & 0xff, 0xb6);
1125   EXPECT_EQ(output2[6], 'g');
1126
1127   string input3 = "x";
1128   string output3;
1129   EXPECT_FALSE(unhexlify(input3, output3));
1130
1131   string input4 = "xy";
1132   string output4;
1133   EXPECT_FALSE(unhexlify(input4, output4));
1134 }
1135
1136 TEST(String, backslashify) {
1137   EXPECT_EQ("abc", string("abc"));
1138   EXPECT_EQ("abc", backslashify(string("abc")));
1139   EXPECT_EQ("abc\\r", backslashify(string("abc\r")));
1140   EXPECT_EQ("abc\\x0d", backslashify(string("abc\r"), true));
1141   EXPECT_EQ("\\0\\0", backslashify(string(2, '\0')));
1142 }
1143
1144 TEST(String, humanify) {
1145   // Simple cases; output is obvious.
1146   EXPECT_EQ("abc", humanify(string("abc")));
1147   EXPECT_EQ("abc\\\\r", humanify(string("abc\\r")));
1148   EXPECT_EQ("0xff", humanify(string("\xff")));
1149   EXPECT_EQ("abc\\xff", humanify(string("abc\xff")));
1150   EXPECT_EQ("abc\\b", humanify(string("abc\b")));
1151   EXPECT_EQ("0x00", humanify(string(1, '\0')));
1152   EXPECT_EQ("0x0000", humanify(string(2, '\0')));
1153
1154
1155   // Mostly printable, so backslash!  80, 60, and 40% printable, respectively
1156   EXPECT_EQ("aaaa\\xff", humanify(string("aaaa\xff")));
1157   EXPECT_EQ("aaa\\xff\\xff", humanify(string("aaa\xff\xff")));
1158   EXPECT_EQ("aa\\xff\\xff\\xff", humanify(string("aa\xff\xff\xff")));
1159
1160   // 20% printable, and the printable portion isn't the prefix; hexify!
1161   EXPECT_EQ("0xff61ffffff", humanify(string("\xff" "a\xff\xff\xff")));
1162
1163   // Same as previous, except swap first two chars; prefix is
1164   // printable and within the threshold, so backslashify.
1165   EXPECT_EQ("a\\xff\\xff\\xff\\xff", humanify(string("a\xff\xff\xff\xff")));
1166
1167   // Just too much unprintable; hex, despite prefix.
1168   EXPECT_EQ("0x61ffffffffff", humanify(string("a\xff\xff\xff\xff\xff")));
1169 }
1170
1171 namespace {
1172
1173 /**
1174  * Copy bytes from src to somewhere in the buffer referenced by dst. The
1175  * actual starting position of the copy will be the first address in the
1176  * destination buffer whose address mod 8 is equal to the src address mod 8.
1177  * The caller is responsible for ensuring that the destination buffer has
1178  * enough extra space to accommodate the shifted copy.
1179  */
1180 char* copyWithSameAlignment(char* dst, const char* src, size_t length) {
1181   const char* originalDst = dst;
1182   size_t dstOffset = size_t(dst) & 0x7;
1183   size_t srcOffset = size_t(src) & 0x7;
1184   while (dstOffset != srcOffset) {
1185     dst++;
1186     dstOffset++;
1187     dstOffset &= 0x7;
1188   }
1189   CHECK(dst <= originalDst + 7);
1190   CHECK((size_t(dst) & 0x7) == (size_t(src) & 0x7));
1191   memcpy(dst, src, length);
1192   return dst;
1193 }
1194
1195 void testToLowerAscii(Range<const char*> src) {
1196   // Allocate extra space so we can make copies that start at the
1197   // same alignment (byte, word, quadword, etc) as the source buffer.
1198   char controlBuf[src.size() + 7];
1199   char* control = copyWithSameAlignment(controlBuf, src.begin(), src.size());
1200
1201   char testBuf[src.size() + 7];
1202   char* test = copyWithSameAlignment(testBuf, src.begin(), src.size());
1203
1204   for (size_t i = 0; i < src.size(); i++) {
1205     control[i] = tolower(control[i]);
1206   }
1207   toLowerAscii(test, src.size());
1208   for (size_t i = 0; i < src.size(); i++) {
1209     EXPECT_EQ(control[i], test[i]);
1210   }
1211 }
1212
1213 } // anon namespace
1214
1215 TEST(String, toLowerAsciiAligned) {
1216   static const size_t kSize = 256;
1217   char input[kSize];
1218   for (size_t i = 0; i < kSize; i++) {
1219     input[i] = (char)(i & 0xff);
1220   }
1221   testToLowerAscii(Range<const char*>(input, kSize));
1222 }
1223
1224 TEST(String, toLowerAsciiUnaligned) {
1225   static const size_t kSize = 256;
1226   char input[kSize];
1227   for (size_t i = 0; i < kSize; i++) {
1228     input[i] = (char)(i & 0xff);
1229   }
1230   // Test input buffers of several lengths to exercise all the
1231   // cases: buffer at the start/middle/end of an aligned block, plus
1232   // buffers that span multiple aligned blocks.  The longest test input
1233   // is 3 unaligned bytes + 4 32-bit aligned bytes + 8 64-bit aligned
1234   // + 4 32-bit aligned + 3 unaligned = 22 bytes.
1235   for (size_t length = 1; length < 23; length++) {
1236     for (size_t offset = 0; offset + length <= kSize; offset++) {
1237       testToLowerAscii(Range<const char*>(input + offset, length));
1238     }
1239   }
1240 }
1241
1242 //////////////////////////////////////////////////////////////////////
1243
1244 BENCHMARK(splitOnSingleChar, iters) {
1245   static const std::string line = "one:two:three:four";
1246   for (size_t i = 0; i < iters << 4; ++i) {
1247     std::vector<StringPiece> pieces;
1248     folly::split(':', line, pieces);
1249   }
1250 }
1251
1252 BENCHMARK(splitOnSingleCharFixed, iters) {
1253   static const std::string line = "one:two:three:four";
1254   for (size_t i = 0; i < iters << 4; ++i) {
1255     StringPiece a, b, c, d;
1256     folly::split(':', line, a, b, c, d);
1257   }
1258 }
1259
1260 BENCHMARK(splitOnSingleCharFixedAllowExtra, iters) {
1261   static const std::string line = "one:two:three:four";
1262   for (size_t i = 0; i < iters << 4; ++i) {
1263     StringPiece a, b, c, d;
1264     folly::split<false>(':', line, a, b, c, d);
1265   }
1266 }
1267
1268 BENCHMARK(splitStr, iters) {
1269   static const std::string line = "one-*-two-*-three-*-four";
1270   for (size_t i = 0; i < iters << 4; ++i) {
1271     std::vector<StringPiece> pieces;
1272     folly::split("-*-", line, pieces);
1273   }
1274 }
1275
1276 BENCHMARK(splitStrFixed, iters) {
1277   static const std::string line = "one-*-two-*-three-*-four";
1278   for (size_t i = 0; i < iters << 4; ++i) {
1279     StringPiece a, b, c, d;
1280     folly::split("-*-", line, a, b, c, d);
1281   }
1282 }
1283
1284 BENCHMARK(boost_splitOnSingleChar, iters) {
1285   static const std::string line = "one:two:three:four";
1286   bool(*pred)(char) = [] (char c) -> bool { return c == ':'; };
1287   for (size_t i = 0; i < iters << 4; ++i) {
1288     std::vector<boost::iterator_range<std::string::const_iterator> > pieces;
1289     boost::split(pieces, line, pred);
1290   }
1291 }
1292
1293 BENCHMARK(joinCharStr, iters) {
1294   static const std::vector<std::string> input = {
1295     "one", "two", "three", "four", "five", "six", "seven" };
1296   for (size_t i = 0; i < iters << 4; ++i) {
1297     std::string output;
1298     folly::join(':', input, output);
1299   }
1300 }
1301
1302 BENCHMARK(joinStrStr, iters) {
1303   static const std::vector<std::string> input = {
1304     "one", "two", "three", "four", "five", "six", "seven" };
1305   for (size_t i = 0; i < iters << 4; ++i) {
1306     std::string output;
1307     folly::join(":", input, output);
1308   }
1309 }
1310
1311 BENCHMARK(joinInt, iters) {
1312   static const auto input = {
1313     123, 456, 78910, 1112, 1314, 151, 61718 };
1314   for (size_t i = 0; i < iters << 4; ++i) {
1315     std::string output;
1316     folly::join(":", input, output);
1317   }
1318 }
1319
1320 int main(int argc, char *argv[]) {
1321   testing::InitGoogleTest(&argc, argv);
1322   gflags::ParseCommandLineFlags(&argc, &argv, true);
1323   auto ret = RUN_ALL_TESTS();
1324   if (!ret) {
1325     initBenchmark();
1326     if (FLAGS_benchmark) {
1327       folly::runBenchmarks();
1328     }
1329   }
1330   return ret;
1331 }