2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/String.h>
19 #include <folly/Format.h>
20 #include <folly/ScopeGuard.h>
28 #include <glog/logging.h>
34 int stringAppendfImplHelper(char* buf,
39 va_copy(args_copy, args);
40 int bytes_used = vsnprintf(buf, bufsize, format, args_copy);
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.
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
56 std::array<char, 128> inline_buffer;
58 int bytes_used = stringAppendfImplHelper(
59 inline_buffer.data(), inline_buffer.size(), format, args);
61 throw std::runtime_error(to<std::string>(
62 "Invalid format string; snprintf returned negative "
63 "with format string: ",
67 if (static_cast<size_t>(bytes_used) < inline_buffer.size()) {
68 output.append(inline_buffer.data(), bytes_used);
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);
81 // We don't keep the trailing '\0' in our output string
82 output.append(heap_buffer.get(), final_bytes_used);
87 std::string stringPrintf(const char* format, ...) {
93 return stringVPrintf(format, ap);
96 std::string stringVPrintf(const char* format, va_list ap) {
98 stringAppendfImpl(ret, format, ap);
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, ...) {
106 va_start(ap, format);
110 return stringVAppendf(output, format, ap);
113 std::string& stringVAppendf(std::string* output,
116 stringAppendfImpl(*output, format, ap);
120 void stringPrintf(std::string* output, const char* format, ...) {
122 va_start(ap, format);
126 return stringVPrintf(output, format, ap);
129 void stringVPrintf(std::string* output, const char* format, va_list ap) {
131 stringAppendfImpl(*output, format, ap);
136 struct PrettySuffix {
141 const PrettySuffix kPrettyTimeSuffixes[] = {
151 const PrettySuffix kPrettyBytesMetricSuffixes[] = {
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 },
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 },
178 const PrettySuffix kPrettyUnitsMetricSuffixes[] = {
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 },
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 },
205 const PrettySuffix kPrettySISuffixes[] = {
230 const PrettySuffix* const kPrettySuffixes[PRETTY_NUM_TYPES] = {
232 kPrettyBytesMetricSuffixes,
233 kPrettyBytesBinarySuffixes,
234 kPrettyBytesBinaryIECSuffixes,
235 kPrettyUnitsMetricSuffixes,
236 kPrettyUnitsBinarySuffixes,
237 kPrettyUnitsBinaryIECSuffixes,
243 std::string prettyPrint(double val, PrettyType type, bool addSpace) {
246 // pick the suffixes to use
248 assert(type < PRETTY_NUM_TYPES);
249 const PrettySuffix* suffixes = kPrettySuffixes[type];
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)
258 (addSpace ? " " : ""),
260 return std::string(buf);
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);
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
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
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;
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(), "\""));
301 prettyString->advance(longestPrefixLen);
302 return suffixes[bestPrefixId].val ? value * suffixes[bestPrefixId].val :
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());
313 std::string hexDump(const void* ptr, size_t size) {
314 std::ostringstream os;
315 hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
319 fbstring errnoStr(int err) {
320 int savedErrno = errno;
322 // Ensure that we reset errno upon exit.
323 auto guard(makeGuard([&] { errno = savedErrno; }));
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));
338 // OSX/FreeBSD use EINVAL and Linux uses -1 so just check for non-zero
340 result = to<fbstring>(
341 "Unknown error ", err,
342 " (strerror_r failed with error ", errno, ")");
347 // Using GNU strerror_r
348 result.assign(strerror_r(err, buf, sizeof(buf)));
354 StringPiece skipWhitespace(StringPiece sp) {
355 // Spaces other than ' ' characters are less common but should be
356 // checked. This configuration where we loop on the ' '
357 // separately from oddspaces was empirically fastest.
358 auto oddspace = [] (char c) {
359 return c == '\n' || c == '\t' || c == '\r';
363 for (; !sp.empty() && sp.front() == ' '; sp.pop_front()) {
365 if (!sp.empty() && oddspace(sp.front())) {
375 void toLowerAscii8(char& c) {
376 // Branchless tolower, based on the input-rotating trick described
377 // at http://www.azillionmonkeys.com/qed/asmexample.html
379 // This algorithm depends on an observation: each uppercase
380 // ASCII character can be converted to its lowercase equivalent
383 // Step 1: Clear the high order bit. We'll deal with it in Step 5.
384 unsigned char rotated = c & 0x7f;
385 // Currently, the value of rotated, as a function of the original c is:
390 // Step 2: Add 0x25 (37)
392 // Now the value of rotated, as a function of the original c is:
395 // above 'Z': 128-164
397 // Step 3: clear the high order bit
403 // Step 4: Add 0x1a (26)
409 // At this point, note that only the uppercase letters have been
410 // transformed into values with the high order bit set (128 and above).
412 // Step 5: Shift the high order bit 2 spaces to the right: the spot
413 // where the only 1 bit in 0x20 is. But first, how we ignored the
414 // high order bit of the original c in step 1? If that bit was set,
415 // we may have just gotten a false match on a value in the range
416 // 128+'A' to 128+'Z'. To correct this, need to clear the high order
417 // bit of rotated if the high order bit of c is set. Since we don't
418 // care about the other bits in rotated, the easiest thing to do
419 // is invert all the bits in c and bitwise-and them with rotated.
423 // Step 6: Apply a mask to clear everything except the 0x20 bit
427 // At this point, rotated is 0x20 if c is 'A'-'Z' and 0x00 otherwise
429 // Step 7: Add rotated to c
433 void toLowerAscii32(uint32_t& c) {
434 // Besides being branchless, the algorithm in toLowerAscii8() has another
435 // interesting property: None of the addition operations will cause
436 // an overflow in the 8-bit value. So we can pack four 8-bit values
437 // into a uint32_t and run each operation on all four values in parallel
438 // without having to use any CPU-specific SIMD instructions.
439 uint32_t rotated = c & uint32_t(0x7f7f7f7fL);
440 rotated += uint32_t(0x25252525L);
441 rotated &= uint32_t(0x7f7f7f7fL);
442 rotated += uint32_t(0x1a1a1a1aL);
444 // Step 5 involves a shift, so some bits will spill over from each
445 // 8-bit value into the next. But that's okay, because they're bits
446 // that will be cleared by the mask in step 6 anyway.
449 rotated &= uint32_t(0x20202020L);
453 void toLowerAscii64(uint64_t& c) {
454 // 64-bit version of toLower32
455 uint64_t rotated = c & uint64_t(0x7f7f7f7f7f7f7f7fL);
456 rotated += uint64_t(0x2525252525252525L);
457 rotated &= uint64_t(0x7f7f7f7f7f7f7f7fL);
458 rotated += uint64_t(0x1a1a1a1a1a1a1a1aL);
461 rotated &= uint64_t(0x2020202020202020L);
467 void toLowerAscii(char* str, size_t length) {
468 static const size_t kAlignMask64 = 7;
469 static const size_t kAlignMask32 = 3;
471 // Convert a character at a time until we reach an address that
472 // is at least 32-bit aligned
473 size_t n = (size_t)str;
475 n = std::min(n, length);
478 n = std::min(4 - n, length);
480 toLowerAscii8(str[offset]);
482 } while (offset < n);
485 n = (size_t)(str + offset);
487 if ((n != 0) && (offset + 4 <= length)) {
488 // The next address is 32-bit aligned but not 64-bit aligned.
489 // Convert the next 4 bytes in order to get to the 64-bit aligned
490 // part of the input.
491 toLowerAscii32(*(uint32_t*)(str + offset));
495 // Convert 8 characters at a time
496 while (offset + 8 <= length) {
497 toLowerAscii64(*(uint64_t*)(str + offset));
501 // Convert 4 characters at a time
502 while (offset + 4 <= length) {
503 toLowerAscii32(*(uint32_t*)(str + offset));
507 // Convert any characters remaining after the last 4-byte aligned group
508 while (offset < length) {
509 toLowerAscii8(str[offset]);
516 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
521 // (1+2)*16: hex bytes, each preceded by a space
522 // 1: space separating the two halves
529 const uint8_t* p = reinterpret_cast<const uint8_t*>(ptr) + offset;
530 size_t n = std::min(size - offset, size_t(16));
531 format("{:08x} ", offset).appendTo(line);
533 for (size_t i = 0; i < n; i++) {
537 format(" {:02x}", p[i]).appendTo(line);
540 // 3 spaces for each byte we're not printing, one separating the halves
542 line.append(3 * (16 - n) + (n <= 8), ' ');
545 for (size_t i = 0; i < n; i++) {
546 char c = (p[i] >= 32 && p[i] <= 126 ? static_cast<char>(p[i]) : '.');
549 line.append(16 - n, ' ');
551 DCHECK_EQ(line.size(), 78);
556 } // namespace detail
560 #ifdef FOLLY_DEFINED_DMGL
561 # undef FOLLY_DEFINED_DMGL
568 # undef DMGL_RET_POSTFIX