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