2 * Copyright 2017 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/ScopeGuard.h>
28 #include <glog/logging.h>
32 static inline bool is_oddspace(char c) {
33 return c == '\n' || c == '\t' || c == '\r';
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.
42 for (; !sp.empty() && sp.front() == ' '; sp.pop_front()) {
44 if (!sp.empty() && is_oddspace(sp.front())) {
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.
58 for (; !sp.empty() && sp.back() == ' '; sp.pop_back()) {
60 if (!sp.empty() && is_oddspace(sp.back())) {
70 int stringAppendfImplHelper(char* buf,
75 va_copy(args_copy, args);
76 int bytes_used = vsnprintf(buf, bufsize, format, args_copy);
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.
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
92 std::array<char, 128> inline_buffer;
94 int bytes_used = stringAppendfImplHelper(
95 inline_buffer.data(), inline_buffer.size(), format, args);
97 throw std::runtime_error(to<std::string>(
98 "Invalid format string; snprintf returned negative "
99 "with format string: ",
103 if (static_cast<size_t>(bytes_used) < inline_buffer.size()) {
104 output.append(inline_buffer.data(), size_t(bytes_used));
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);
117 // We don't keep the trailing '\0' in our output string
118 output.append(heap_buffer.get(), size_t(final_bytes_used));
123 std::string stringPrintf(const char* format, ...) {
125 va_start(ap, format);
129 return stringVPrintf(format, ap);
132 std::string stringVPrintf(const char* format, va_list ap) {
134 stringAppendfImpl(ret, format, ap);
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, ...) {
142 va_start(ap, format);
146 return stringVAppendf(output, format, ap);
149 std::string& stringVAppendf(std::string* output,
152 stringAppendfImpl(*output, format, ap);
156 void stringPrintf(std::string* output, const char* format, ...) {
158 va_start(ap, format);
162 return stringVPrintf(output, format, ap);
165 void stringVPrintf(std::string* output, const char* format, va_list ap) {
167 stringAppendfImpl(*output, format, ap);
172 struct PrettySuffix {
177 const PrettySuffix kPrettyTimeSuffixes[] = {
187 const PrettySuffix kPrettyBytesMetricSuffixes[] = {
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 },
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 },
214 const PrettySuffix kPrettyUnitsMetricSuffixes[] = {
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 },
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 },
241 const PrettySuffix kPrettySISuffixes[] = {
266 const PrettySuffix* const kPrettySuffixes[PRETTY_NUM_TYPES] = {
268 kPrettyBytesMetricSuffixes,
269 kPrettyBytesBinarySuffixes,
270 kPrettyBytesBinaryIECSuffixes,
271 kPrettyUnitsMetricSuffixes,
272 kPrettyUnitsBinarySuffixes,
273 kPrettyUnitsBinaryIECSuffixes,
279 std::string prettyPrint(double val, PrettyType type, bool addSpace) {
282 // pick the suffixes to use
284 assert(type < PRETTY_NUM_TYPES);
285 const PrettySuffix* suffixes = kPrettySuffixes[type];
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)
294 (addSpace ? " " : ""),
296 return std::string(buf);
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);
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
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
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;
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(), "\""));
337 prettyString->advance(size_t(longestPrefixLen));
338 return suffixes[bestPrefixId].val ? value * suffixes[bestPrefixId].val :
342 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type){
343 double result = prettyToDouble(&prettyString, type);
344 detail::enforceWhitespace(prettyString);
348 std::string hexDump(const void* ptr, size_t size) {
349 std::ostringstream os;
350 hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
354 fbstring errnoStr(int err) {
355 int savedErrno = errno;
357 // Ensure that we reset errno upon exit.
358 auto guard(makeGuard([&] { errno = savedErrno; }));
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);
373 result = to<fbstring>(
374 "Unknown error ", err,
375 " (strerror_r failed with error ", errno, ")");
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));
384 // OSX/FreeBSD use EINVAL and Linux uses -1 so just check for non-zero
386 result = to<fbstring>(
387 "Unknown error ", err,
388 " (strerror_r failed with error ", errno, ")");
393 // Using GNU strerror_r
394 result.assign(strerror_r(err, buf, sizeof(buf)));
402 void toLowerAscii8(char& c) {
403 // Branchless tolower, based on the input-rotating trick described
404 // at http://www.azillionmonkeys.com/qed/asmexample.html
406 // This algorithm depends on an observation: each uppercase
407 // ASCII character can be converted to its lowercase equivalent
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:
417 // Step 2: Add 0x25 (37)
419 // Now the value of rotated, as a function of the original c is:
422 // above 'Z': 128-164
424 // Step 3: clear the high order bit
430 // Step 4: Add 0x1a (26)
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).
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.
450 // Step 6: Apply a mask to clear everything except the 0x20 bit
454 // At this point, rotated is 0x20 if c is 'A'-'Z' and 0x00 otherwise
456 // Step 7: Add rotated to c
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);
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.
476 rotated &= uint32_t(0x20202020L);
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);
488 rotated &= uint64_t(0x2020202020202020L);
494 void toLowerAscii(char* str, size_t length) {
495 static const size_t kAlignMask64 = 7;
496 static const size_t kAlignMask32 = 3;
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;
502 n = std::min(n, length);
505 n = std::min(4 - n, length);
507 toLowerAscii8(str[offset]);
509 } while (offset < n);
512 n = (size_t)(str + offset);
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));
522 // Convert 8 characters at a time
523 while (offset + 8 <= length) {
524 toLowerAscii64(*(uint64_t*)(str + offset));
528 // Convert 4 characters at a time
529 while (offset + 4 <= length) {
530 toLowerAscii32(*(uint32_t*)(str + offset));
534 // Convert any characters remaining after the last 4-byte aligned group
535 while (offset < length) {
536 toLowerAscii8(str[offset]);
543 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
545 static char hexValues[] = "0123456789abcdef";
549 // (1+2)*16: hex bytes, each preceded by a space
550 // 1: space separating the two halves
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]);
569 for (size_t i = 0; i < n; i++) {
575 line.push_back(hexValues[(p[i] >> 4) & 0xf]);
576 line.push_back(hexValues[p[i] & 0xf]);
579 // 3 spaces for each byte we're not printing, one separating the halves
581 line.append(3 * (16 - n) + (n <= 8), ' ');
584 for (size_t i = 0; i < n; i++) {
585 char c = (p[i] >= 32 && p[i] <= 126 ? static_cast<char>(p[i]) : '.');
588 line.append(16 - n, ' ');
590 DCHECK_EQ(line.size(), 78u);
595 } // namespace detail
597 std::string stripLeftMargin(std::string s) {
598 std::vector<StringPiece> pieces;
599 split("\n", s, pieces);
600 auto piecer = range(pieces);
602 auto piece = (piecer.end() - 1);
603 auto needle = std::find_if(piece->begin(),
605 [](char c) { return c != ' ' && c != '\t'; });
606 if (needle == piece->end()) {
607 (piecer.end() - 1)->clear();
609 piece = piecer.begin();
610 needle = std::find_if(piece->begin(),
612 [](char c) { return c != ' ' && c != '\t'; });
613 if (needle == piece->end()) {
614 piecer.erase(piecer.begin(), piecer.begin() + 1);
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(),
623 [](char c) { return c != ' ' && c != '\t'; });
624 if (needle != piece->end()) {
625 indent = std::min<size_t>(indent, size_t(needle - piece->begin()));
627 max_length = std::max<size_t>(piece->size(), max_length);
630 indent = indent == sentinel ? max_length : indent;
631 for (piece = piecer.begin(); piece != piecer.end(); piece++) {
632 if (piece->size() < indent) {
635 piece->erase(piece->begin(), piece->begin() + indent);
638 return join("\n", piecer);
643 #ifdef FOLLY_DEFINED_DMGL
644 # undef FOLLY_DEFINED_DMGL
651 # undef DMGL_RET_POSTFIX