Make some AsyncTest methods virtual to allow mocking them using gtest/gmock
[folly.git] / folly / String.cpp
1 /*
2  * Copyright 2017 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 <folly/Format.h>
20 #include <folly/ScopeGuard.h>
21
22 #include <cerrno>
23 #include <cstdarg>
24 #include <cstring>
25 #include <stdexcept>
26 #include <iterator>
27 #include <cctype>
28 #include <string.h>
29 #include <glog/logging.h>
30
31 namespace folly {
32
33 namespace {
34
35 int stringAppendfImplHelper(char* buf,
36                             size_t bufsize,
37                             const char* format,
38                             va_list args) {
39   va_list args_copy;
40   va_copy(args_copy, args);
41   int bytes_used = vsnprintf(buf, bufsize, format, args_copy);
42   va_end(args_copy);
43   return bytes_used;
44 }
45
46 void stringAppendfImpl(std::string& output, const char* format, va_list args) {
47   // Very simple; first, try to avoid an allocation by using an inline
48   // buffer.  If that fails to hold the output string, allocate one on
49   // the heap, use it instead.
50   //
51   // It is hard to guess the proper size of this buffer; some
52   // heuristics could be based on the number of format characters, or
53   // static analysis of a codebase.  Or, we can just pick a number
54   // that seems big enough for simple cases (say, one line of text on
55   // a terminal) without being large enough to be concerning as a
56   // stack variable.
57   std::array<char, 128> inline_buffer;
58
59   int bytes_used = stringAppendfImplHelper(
60       inline_buffer.data(), inline_buffer.size(), format, args);
61   if (bytes_used < 0) {
62     throw std::runtime_error(to<std::string>(
63         "Invalid format string; snprintf returned negative "
64         "with format string: ",
65         format));
66   }
67
68   if (static_cast<size_t>(bytes_used) < inline_buffer.size()) {
69     output.append(inline_buffer.data(), size_t(bytes_used));
70     return;
71   }
72
73   // Couldn't fit.  Heap allocate a buffer, oh well.
74   std::unique_ptr<char[]> heap_buffer(new char[size_t(bytes_used + 1)]);
75   int final_bytes_used = stringAppendfImplHelper(
76       heap_buffer.get(), size_t(bytes_used + 1), format, args);
77   // The second call can take fewer bytes if, for example, we were printing a
78   // string buffer with null-terminating char using a width specifier -
79   // vsnprintf("%.*s", buf.size(), buf)
80   CHECK(bytes_used >= final_bytes_used);
81
82   // We don't keep the trailing '\0' in our output string
83   output.append(heap_buffer.get(), size_t(final_bytes_used));
84 }
85
86 } // anon namespace
87
88 std::string stringPrintf(const char* format, ...) {
89   va_list ap;
90   va_start(ap, format);
91   SCOPE_EXIT {
92     va_end(ap);
93   };
94   return stringVPrintf(format, ap);
95 }
96
97 std::string stringVPrintf(const char* format, va_list ap) {
98   std::string ret;
99   stringAppendfImpl(ret, format, ap);
100   return ret;
101 }
102
103 // Basic declarations; allow for parameters of strings and string
104 // pieces to be specified.
105 std::string& stringAppendf(std::string* output, const char* format, ...) {
106   va_list ap;
107   va_start(ap, format);
108   SCOPE_EXIT {
109     va_end(ap);
110   };
111   return stringVAppendf(output, format, ap);
112 }
113
114 std::string& stringVAppendf(std::string* output,
115                             const char* format,
116                             va_list ap) {
117   stringAppendfImpl(*output, format, ap);
118   return *output;
119 }
120
121 void stringPrintf(std::string* output, const char* format, ...) {
122   va_list ap;
123   va_start(ap, format);
124   SCOPE_EXIT {
125     va_end(ap);
126   };
127   return stringVPrintf(output, format, ap);
128 }
129
130 void stringVPrintf(std::string* output, const char* format, va_list ap) {
131   output->clear();
132   stringAppendfImpl(*output, format, ap);
133 };
134
135 namespace {
136
137 struct PrettySuffix {
138   const char* suffix;
139   double val;
140 };
141
142 const PrettySuffix kPrettyTimeSuffixes[] = {
143   { "s ", 1e0L },
144   { "ms", 1e-3L },
145   { "us", 1e-6L },
146   { "ns", 1e-9L },
147   { "ps", 1e-12L },
148   { "s ", 0 },
149   { 0, 0 },
150 };
151
152 const PrettySuffix kPrettyBytesMetricSuffixes[] = {
153   { "TB", 1e12L },
154   { "GB", 1e9L },
155   { "MB", 1e6L },
156   { "kB", 1e3L },
157   { "B ", 0L },
158   { 0, 0 },
159 };
160
161 const PrettySuffix kPrettyBytesBinarySuffixes[] = {
162   { "TB", int64_t(1) << 40 },
163   { "GB", int64_t(1) << 30 },
164   { "MB", int64_t(1) << 20 },
165   { "kB", int64_t(1) << 10 },
166   { "B ", 0L },
167   { 0, 0 },
168 };
169
170 const PrettySuffix kPrettyBytesBinaryIECSuffixes[] = {
171   { "TiB", int64_t(1) << 40 },
172   { "GiB", int64_t(1) << 30 },
173   { "MiB", int64_t(1) << 20 },
174   { "KiB", int64_t(1) << 10 },
175   { "B  ", 0L },
176   { 0, 0 },
177 };
178
179 const PrettySuffix kPrettyUnitsMetricSuffixes[] = {
180   { "tril", 1e12L },
181   { "bil",  1e9L },
182   { "M",    1e6L },
183   { "k",    1e3L },
184   { " ",      0  },
185   { 0, 0 },
186 };
187
188 const PrettySuffix kPrettyUnitsBinarySuffixes[] = {
189   { "T", int64_t(1) << 40 },
190   { "G", int64_t(1) << 30 },
191   { "M", int64_t(1) << 20 },
192   { "k", int64_t(1) << 10 },
193   { " ", 0 },
194   { 0, 0 },
195 };
196
197 const PrettySuffix kPrettyUnitsBinaryIECSuffixes[] = {
198   { "Ti", int64_t(1) << 40 },
199   { "Gi", int64_t(1) << 30 },
200   { "Mi", int64_t(1) << 20 },
201   { "Ki", int64_t(1) << 10 },
202   { "  ", 0 },
203   { 0, 0 },
204 };
205
206 const PrettySuffix kPrettySISuffixes[] = {
207   { "Y", 1e24L },
208   { "Z", 1e21L },
209   { "E", 1e18L },
210   { "P", 1e15L },
211   { "T", 1e12L },
212   { "G", 1e9L },
213   { "M", 1e6L },
214   { "k", 1e3L },
215   { "h", 1e2L },
216   { "da", 1e1L },
217   { "d", 1e-1L },
218   { "c", 1e-2L },
219   { "m", 1e-3L },
220   { "u", 1e-6L },
221   { "n", 1e-9L },
222   { "p", 1e-12L },
223   { "f", 1e-15L },
224   { "a", 1e-18L },
225   { "z", 1e-21L },
226   { "y", 1e-24L },
227   { " ", 0 },
228   { 0, 0}
229 };
230
231 const PrettySuffix* const kPrettySuffixes[PRETTY_NUM_TYPES] = {
232   kPrettyTimeSuffixes,
233   kPrettyBytesMetricSuffixes,
234   kPrettyBytesBinarySuffixes,
235   kPrettyBytesBinaryIECSuffixes,
236   kPrettyUnitsMetricSuffixes,
237   kPrettyUnitsBinarySuffixes,
238   kPrettyUnitsBinaryIECSuffixes,
239   kPrettySISuffixes,
240 };
241
242 }  // namespace
243
244 std::string prettyPrint(double val, PrettyType type, bool addSpace) {
245   char buf[100];
246
247   // pick the suffixes to use
248   assert(type >= 0);
249   assert(type < PRETTY_NUM_TYPES);
250   const PrettySuffix* suffixes = kPrettySuffixes[type];
251
252   // find the first suffix we're bigger than -- then use it
253   double abs_val = fabs(val);
254   for (int i = 0; suffixes[i].suffix; ++i) {
255     if (abs_val >= suffixes[i].val) {
256       snprintf(buf, sizeof buf, "%.4g%s%s",
257                (suffixes[i].val ? (val / suffixes[i].val)
258                                 : val),
259                (addSpace ? " " : ""),
260                suffixes[i].suffix);
261       return std::string(buf);
262     }
263   }
264
265   // no suffix, we've got a tiny value -- just print it in sci-notation
266   snprintf(buf, sizeof buf, "%.4g", val);
267   return std::string(buf);
268 }
269
270 //TODO:
271 //1) Benchmark & optimize
272 double prettyToDouble(folly::StringPiece *const prettyString,
273                       const PrettyType type) {
274   double value = folly::to<double>(prettyString);
275   while (prettyString->size() > 0 && std::isspace(prettyString->front())) {
276     prettyString->advance(1); //Skipping spaces between number and suffix
277   }
278   const PrettySuffix* suffixes = kPrettySuffixes[type];
279   int longestPrefixLen = -1;
280   int bestPrefixId = -1;
281   for (int j = 0 ; suffixes[j].suffix; ++j) {
282     if (suffixes[j].suffix[0] == ' '){//Checking for " " -> number rule.
283       if (longestPrefixLen == -1) {
284         longestPrefixLen = 0; //No characters to skip
285         bestPrefixId = j;
286       }
287     } else if (prettyString->startsWith(suffixes[j].suffix)) {
288       int suffixLen = int(strlen(suffixes[j].suffix));
289       //We are looking for a longest suffix matching prefix of the string
290       //after numeric value. We need this in case suffixes have common prefix.
291       if (suffixLen > longestPrefixLen) {
292         longestPrefixLen = suffixLen;
293         bestPrefixId = j;
294       }
295     }
296   }
297   if (bestPrefixId == -1) { //No valid suffix rule found
298     throw std::invalid_argument(folly::to<std::string>(
299             "Unable to parse suffix \"",
300             prettyString->toString(), "\""));
301   }
302   prettyString->advance(size_t(longestPrefixLen));
303   return suffixes[bestPrefixId].val ? value * suffixes[bestPrefixId].val :
304                                       value;
305 }
306
307 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type){
308   double result = prettyToDouble(&prettyString, type);
309   detail::enforceWhitespace(prettyString);
310   return result;
311 }
312
313 std::string hexDump(const void* ptr, size_t size) {
314   std::ostringstream os;
315   hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
316   return os.str();
317 }
318
319 fbstring errnoStr(int err) {
320   int savedErrno = errno;
321
322   // Ensure that we reset errno upon exit.
323   auto guard(makeGuard([&] { errno = savedErrno; }));
324
325   char buf[1024];
326   buf[0] = '\0';
327
328   fbstring result;
329
330   // https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/strerror_r.3.html
331   // http://www.kernel.org/doc/man-pages/online/pages/man3/strerror.3.html
332 #if defined(_WIN32) && (defined(__MINGW32__) || defined(_MSC_VER))
333   // mingw64 has no strerror_r, but Windows has strerror_s, which C11 added
334   // as well. So maybe we should use this across all platforms (together
335   // with strerrorlen_s). Note strerror_r and _s have swapped args.
336   int r = strerror_s(buf, sizeof(buf), err);
337   if (r != 0) {
338     result = to<fbstring>(
339       "Unknown error ", err,
340       " (strerror_r failed with error ", errno, ")");
341   } else {
342     result.assign(buf);
343   }
344 #elif defined(FOLLY_HAVE_XSI_STRERROR_R) || \
345   defined(__APPLE__) || defined(__ANDROID__)
346   // Using XSI-compatible strerror_r
347   int r = strerror_r(err, buf, sizeof(buf));
348
349   // OSX/FreeBSD use EINVAL and Linux uses -1 so just check for non-zero
350   if (r != 0) {
351     result = to<fbstring>(
352       "Unknown error ", err,
353       " (strerror_r failed with error ", errno, ")");
354   } else {
355     result.assign(buf);
356   }
357 #else
358   // Using GNU strerror_r
359   result.assign(strerror_r(err, buf, sizeof(buf)));
360 #endif
361
362   return result;
363 }
364
365 namespace {
366
367 void toLowerAscii8(char& c) {
368   // Branchless tolower, based on the input-rotating trick described
369   // at http://www.azillionmonkeys.com/qed/asmexample.html
370   //
371   // This algorithm depends on an observation: each uppercase
372   // ASCII character can be converted to its lowercase equivalent
373   // by adding 0x20.
374
375   // Step 1: Clear the high order bit. We'll deal with it in Step 5.
376   uint8_t rotated = uint8_t(c & 0x7f);
377   // Currently, the value of rotated, as a function of the original c is:
378   //   below 'A':   0- 64
379   //   'A'-'Z':    65- 90
380   //   above 'Z':  91-127
381
382   // Step 2: Add 0x25 (37)
383   rotated += 0x25;
384   // Now the value of rotated, as a function of the original c is:
385   //   below 'A':   37-101
386   //   'A'-'Z':    102-127
387   //   above 'Z':  128-164
388
389   // Step 3: clear the high order bit
390   rotated &= 0x7f;
391   //   below 'A':   37-101
392   //   'A'-'Z':    102-127
393   //   above 'Z':    0- 36
394
395   // Step 4: Add 0x1a (26)
396   rotated += 0x1a;
397   //   below 'A':   63-127
398   //   'A'-'Z':    128-153
399   //   above 'Z':   25- 62
400
401   // At this point, note that only the uppercase letters have been
402   // transformed into values with the high order bit set (128 and above).
403
404   // Step 5: Shift the high order bit 2 spaces to the right: the spot
405   // where the only 1 bit in 0x20 is.  But first, how we ignored the
406   // high order bit of the original c in step 1?  If that bit was set,
407   // we may have just gotten a false match on a value in the range
408   // 128+'A' to 128+'Z'.  To correct this, need to clear the high order
409   // bit of rotated if the high order bit of c is set.  Since we don't
410   // care about the other bits in rotated, the easiest thing to do
411   // is invert all the bits in c and bitwise-and them with rotated.
412   rotated &= ~c;
413   rotated >>= 2;
414
415   // Step 6: Apply a mask to clear everything except the 0x20 bit
416   // in rotated.
417   rotated &= 0x20;
418
419   // At this point, rotated is 0x20 if c is 'A'-'Z' and 0x00 otherwise
420
421   // Step 7: Add rotated to c
422   c += char(rotated);
423 }
424
425 void toLowerAscii32(uint32_t& c) {
426   // Besides being branchless, the algorithm in toLowerAscii8() has another
427   // interesting property: None of the addition operations will cause
428   // an overflow in the 8-bit value.  So we can pack four 8-bit values
429   // into a uint32_t and run each operation on all four values in parallel
430   // without having to use any CPU-specific SIMD instructions.
431   uint32_t rotated = c & uint32_t(0x7f7f7f7fL);
432   rotated += uint32_t(0x25252525L);
433   rotated &= uint32_t(0x7f7f7f7fL);
434   rotated += uint32_t(0x1a1a1a1aL);
435
436   // Step 5 involves a shift, so some bits will spill over from each
437   // 8-bit value into the next.  But that's okay, because they're bits
438   // that will be cleared by the mask in step 6 anyway.
439   rotated &= ~c;
440   rotated >>= 2;
441   rotated &= uint32_t(0x20202020L);
442   c += rotated;
443 }
444
445 void toLowerAscii64(uint64_t& c) {
446   // 64-bit version of toLower32
447   uint64_t rotated = c & uint64_t(0x7f7f7f7f7f7f7f7fL);
448   rotated += uint64_t(0x2525252525252525L);
449   rotated &= uint64_t(0x7f7f7f7f7f7f7f7fL);
450   rotated += uint64_t(0x1a1a1a1a1a1a1a1aL);
451   rotated &= ~c;
452   rotated >>= 2;
453   rotated &= uint64_t(0x2020202020202020L);
454   c += rotated;
455 }
456
457 } // anon namespace
458
459 void toLowerAscii(char* str, size_t length) {
460   static const size_t kAlignMask64 = 7;
461   static const size_t kAlignMask32 = 3;
462
463   // Convert a character at a time until we reach an address that
464   // is at least 32-bit aligned
465   size_t n = (size_t)str;
466   n &= kAlignMask32;
467   n = std::min(n, length);
468   size_t offset = 0;
469   if (n != 0) {
470     n = std::min(4 - n, length);
471     do {
472       toLowerAscii8(str[offset]);
473       offset++;
474     } while (offset < n);
475   }
476
477   n = (size_t)(str + offset);
478   n &= kAlignMask64;
479   if ((n != 0) && (offset + 4 <= length)) {
480     // The next address is 32-bit aligned but not 64-bit aligned.
481     // Convert the next 4 bytes in order to get to the 64-bit aligned
482     // part of the input.
483     toLowerAscii32(*(uint32_t*)(str + offset));
484     offset += 4;
485   }
486
487   // Convert 8 characters at a time
488   while (offset + 8 <= length) {
489     toLowerAscii64(*(uint64_t*)(str + offset));
490     offset += 8;
491   }
492
493   // Convert 4 characters at a time
494   while (offset + 4 <= length) {
495     toLowerAscii32(*(uint32_t*)(str + offset));
496     offset += 4;
497   }
498
499   // Convert any characters remaining after the last 4-byte aligned group
500   while (offset < length) {
501     toLowerAscii8(str[offset]);
502     offset++;
503   }
504 }
505
506 namespace detail {
507
508 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
509                    std::string& line) {
510   // Line layout:
511   // 8: address
512   // 1: space
513   // (1+2)*16: hex bytes, each preceded by a space
514   // 1: space separating the two halves
515   // 3: "  |"
516   // 16: characters
517   // 1: "|"
518   // Total: 78
519   line.clear();
520   line.reserve(78);
521   const uint8_t* p = reinterpret_cast<const uint8_t*>(ptr) + offset;
522   size_t n = std::min(size - offset, size_t(16));
523   format("{:08x} ", offset).appendTo(line);
524
525   for (size_t i = 0; i < n; i++) {
526     if (i == 8) {
527       line.push_back(' ');
528     }
529     format(" {:02x}", p[i]).appendTo(line);
530   }
531
532   // 3 spaces for each byte we're not printing, one separating the halves
533   // if necessary
534   line.append(3 * (16 - n) + (n <= 8), ' ');
535   line.append("  |");
536
537   for (size_t i = 0; i < n; i++) {
538     char c = (p[i] >= 32 && p[i] <= 126 ? static_cast<char>(p[i]) : '.');
539     line.push_back(c);
540   }
541   line.append(16 - n, ' ');
542   line.push_back('|');
543   DCHECK_EQ(line.size(), 78u);
544
545   return n;
546 }
547
548 } // namespace detail
549
550 std::string stripLeftMargin(std::string s) {
551   std::vector<StringPiece> pieces;
552   split("\n", s, pieces);
553   auto piecer = range(pieces);
554
555   auto piece = (piecer.end() - 1);
556   auto needle = std::find_if(piece->begin(),
557                              piece->end(),
558                              [](char c) { return c != ' ' && c != '\t'; });
559   if (needle == piece->end()) {
560     (piecer.end() - 1)->clear();
561   }
562   piece = piecer.begin();
563   needle = std::find_if(piece->begin(),
564                         piece->end(),
565                         [](char c) { return c != ' ' && c != '\t'; });
566   if (needle == piece->end()) {
567     piecer.erase(piecer.begin(), piecer.begin() + 1);
568   }
569
570   const auto sentinel = std::numeric_limits<size_t>::max();
571   auto indent = sentinel;
572   size_t max_length = 0;
573   for (piece = piecer.begin(); piece != piecer.end(); piece++) {
574     needle = std::find_if(piece->begin(),
575                           piece->end(),
576                           [](char c) { return c != ' ' && c != '\t'; });
577     if (needle != piece->end()) {
578       indent = std::min<size_t>(indent, size_t(needle - piece->begin()));
579     } else {
580       max_length = std::max<size_t>(piece->size(), max_length);
581     }
582   }
583   indent = indent == sentinel ? max_length : indent;
584   for (piece = piecer.begin(); piece != piecer.end(); piece++) {
585     if (piece->size() < indent) {
586       piece->clear();
587     } else {
588       piece->erase(piece->begin(), piece->begin() + indent);
589     }
590   }
591   return join("\n", piecer);
592 }
593
594 }   // namespace folly
595
596 #ifdef FOLLY_DEFINED_DMGL
597 # undef FOLLY_DEFINED_DMGL
598 # undef DMGL_NO_OPTS
599 # undef DMGL_PARAMS
600 # undef DMGL_ANSI
601 # undef DMGL_JAVA
602 # undef DMGL_VERBOSE
603 # undef DMGL_TYPES
604 # undef DMGL_RET_POSTFIX
605 #endif