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