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