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