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