2 * Copyright 2014 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 inline void stringPrintfImpl(std::string& output, const char* format,
36 // Tru to the space at the end of output for our output buffer.
37 // Find out write point then inflate its size temporarily to its
38 // capacity; we will later shrink it to the size needed to represent
39 // the formatted string. If this buffer isn't large enough, we do a
40 // resize and try again.
42 const auto write_point = output.size();
43 auto remaining = output.capacity() - write_point;
44 output.resize(output.capacity());
47 va_copy(args_copy, args);
48 int bytes_used = vsnprintf(&output[write_point], remaining, format,
52 throw std::runtime_error(
53 to<std::string>("Invalid format string; snprintf returned negative "
54 "with format string: ", format));
55 } else if (bytes_used < remaining) {
56 // There was enough room, just shrink and return.
57 output.resize(write_point + bytes_used);
59 output.resize(write_point + bytes_used + 1);
60 remaining = bytes_used + 1;
62 va_copy(args_copy, args);
63 bytes_used = vsnprintf(&output[write_point], remaining, format,
66 if (bytes_used + 1 != remaining) {
67 throw std::runtime_error(
68 to<std::string>("vsnprint retry did not manage to work "
69 "with format string: ", format));
71 output.resize(write_point + bytes_used);
77 std::string stringPrintf(const char* format, ...) {
83 return stringVPrintf(format, ap);
86 std::string stringVPrintf(const char* format, va_list ap) {
87 // snprintf will tell us how large the output buffer should be, but
88 // we then have to call it a second time, which is costly. By
89 // guestimating the final size, we avoid the double snprintf in many
90 // cases, resulting in a performance win. We use this constructor
91 // of std::string to avoid a double allocation, though it does pad
92 // the resulting string with nul bytes. Our guestimation is twice
93 // the format string size, or 32 bytes, whichever is larger. This
94 // is a hueristic that doesn't affect correctness but attempts to be
95 // reasonably fast for the most common cases.
96 std::string ret(std::max(size_t(32), strlen(format) * 2), '\0');
99 stringPrintfImpl(ret, format, ap);
103 // Basic declarations; allow for parameters of strings and string
104 // pieces to be specified.
105 std::string& stringAppendf(std::string* output, const char* format, ...) {
107 va_start(ap, format);
111 return stringVAppendf(output, format, ap);
114 std::string& stringVAppendf(std::string* output,
117 stringPrintfImpl(*output, format, ap);
121 void stringPrintf(std::string* output, const char* format, ...) {
123 va_start(ap, format);
127 return stringVPrintf(output, format, ap);
130 void stringVPrintf(std::string* output, const char* format, va_list ap) {
132 stringPrintfImpl(*output, format, ap);
137 struct PrettySuffix {
142 const PrettySuffix kPrettyTimeSuffixes[] = {
152 const PrettySuffix kPrettyBytesMetricSuffixes[] = {
161 const PrettySuffix kPrettyBytesBinarySuffixes[] = {
162 { "TB", int64_t(1) << 40 },
163 { "GB", int64_t(1) << 30 },
164 { "MB", int64_t(1) << 20 },
165 { "kB", int64_t(1) << 10 },
170 const PrettySuffix kPrettyBytesBinaryIECSuffixes[] = {
171 { "TiB", int64_t(1) << 40 },
172 { "GiB", int64_t(1) << 30 },
173 { "MiB", int64_t(1) << 20 },
174 { "KiB", int64_t(1) << 10 },
179 const PrettySuffix kPrettyUnitsMetricSuffixes[] = {
188 const PrettySuffix kPrettyUnitsBinarySuffixes[] = {
189 { "T", int64_t(1) << 40 },
190 { "G", int64_t(1) << 30 },
191 { "M", int64_t(1) << 20 },
192 { "k", int64_t(1) << 10 },
197 const PrettySuffix kPrettyUnitsBinaryIECSuffixes[] = {
198 { "Ti", int64_t(1) << 40 },
199 { "Gi", int64_t(1) << 30 },
200 { "Mi", int64_t(1) << 20 },
201 { "Ki", int64_t(1) << 10 },
206 const PrettySuffix kPrettySISuffixes[] = {
231 const PrettySuffix* const kPrettySuffixes[PRETTY_NUM_TYPES] = {
233 kPrettyBytesMetricSuffixes,
234 kPrettyBytesBinarySuffixes,
235 kPrettyBytesBinaryIECSuffixes,
236 kPrettyUnitsMetricSuffixes,
237 kPrettyUnitsBinarySuffixes,
238 kPrettyUnitsBinaryIECSuffixes,
244 std::string prettyPrint(double val, PrettyType type, bool addSpace) {
247 // pick the suffixes to use
249 assert(type < PRETTY_NUM_TYPES);
250 const PrettySuffix* suffixes = kPrettySuffixes[type];
252 // find the first suffix we're bigger than -- then use it
253 double abs_val = fabs(val);
254 for (int i = 0; suffixes[i].suffix; ++i) {
255 if (abs_val >= suffixes[i].val) {
256 snprintf(buf, sizeof buf, "%.4g%s%s",
257 (suffixes[i].val ? (val / suffixes[i].val)
259 (addSpace ? " " : ""),
261 return std::string(buf);
265 // no suffix, we've got a tiny value -- just print it in sci-notation
266 snprintf(buf, sizeof buf, "%.4g", val);
267 return std::string(buf);
271 //1) Benchmark & optimize
272 double prettyToDouble(folly::StringPiece *const prettyString,
273 const PrettyType type) {
274 double value = folly::to<double>(prettyString);
275 while (prettyString->size() > 0 && std::isspace(prettyString->front())) {
276 prettyString->advance(1); //Skipping spaces between number and suffix
278 const PrettySuffix* suffixes = kPrettySuffixes[type];
279 int longestPrefixLen = -1;
280 int bestPrefixId = -1;
281 for (int j = 0 ; suffixes[j].suffix; ++j) {
282 if (suffixes[j].suffix[0] == ' '){//Checking for " " -> number rule.
283 if (longestPrefixLen == -1) {
284 longestPrefixLen = 0; //No characters to skip
287 } else if (prettyString->startsWith(suffixes[j].suffix)) {
288 int suffixLen = strlen(suffixes[j].suffix);
289 //We are looking for a longest suffix matching prefix of the string
290 //after numeric value. We need this in case suffixes have common prefix.
291 if (suffixLen > longestPrefixLen) {
292 longestPrefixLen = suffixLen;
297 if (bestPrefixId == -1) { //No valid suffix rule found
298 throw std::invalid_argument(folly::to<std::string>(
299 "Unable to parse suffix \"",
300 prettyString->toString(), "\""));
302 prettyString->advance(longestPrefixLen);
303 return suffixes[bestPrefixId].val ? value * suffixes[bestPrefixId].val :
307 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type){
308 double result = prettyToDouble(&prettyString, type);
309 detail::enforceWhitespace(prettyString.data(),
310 prettyString.data() + prettyString.size());
314 std::string hexDump(const void* ptr, size_t size) {
315 std::ostringstream os;
316 hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
320 fbstring errnoStr(int err) {
321 int savedErrno = errno;
323 // Ensure that we reset errno upon exit.
324 auto guard(makeGuard([&] { errno = savedErrno; }));
331 // https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/strerror_r.3.html
332 // http://www.kernel.org/doc/man-pages/online/pages/man3/strerror.3.html
333 #if defined(__APPLE__) || defined(__FreeBSD__) ||\
334 defined(__CYGWIN__) || defined(__ANDROID__) ||\
335 ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE)
336 // Using XSI-compatible strerror_r
337 int r = strerror_r(err, buf, sizeof(buf));
339 // OSX/FreeBSD use EINVAL and Linux uses -1 so just check for non-zero
341 result = to<fbstring>(
342 "Unknown error ", err,
343 " (strerror_r failed with error ", errno, ")");
348 // Using GNU strerror_r
349 result.assign(strerror_r(err, buf, sizeof(buf)));
355 StringPiece skipWhitespace(StringPiece sp) {
356 // Spaces other than ' ' characters are less common but should be
357 // checked. This configuration where we loop on the ' '
358 // separately from oddspaces was empirically fastest.
359 auto oddspace = [] (char c) {
360 return c == '\n' || c == '\t' || c == '\r';
364 for (; !sp.empty() && sp.front() == ' '; sp.pop_front()) {
366 if (!sp.empty() && oddspace(sp.front())) {
376 void toLowerAscii8(char& c) {
377 // Branchless tolower, based on the input-rotating trick described
378 // at http://www.azillionmonkeys.com/qed/asmexample.html
380 // This algorithm depends on an observation: each uppercase
381 // ASCII character can be converted to its lowercase equivalent
384 // Step 1: Clear the high order bit. We'll deal with it in Step 5.
385 unsigned char rotated = c & 0x7f;
386 // Currently, the value of rotated, as a function of the original c is:
391 // Step 2: Add 0x25 (37)
393 // Now the value of rotated, as a function of the original c is:
396 // above 'Z': 128-164
398 // Step 3: clear the high order bit
404 // Step 4: Add 0x1a (26)
410 // At this point, note that only the uppercase letters have been
411 // transformed into values with the high order bit set (128 and above).
413 // Step 5: Shift the high order bit 2 spaces to the right: the spot
414 // where the only 1 bit in 0x20 is. But first, how we ignored the
415 // high order bit of the original c in step 1? If that bit was set,
416 // we may have just gotten a false match on a value in the range
417 // 128+'A' to 128+'Z'. To correct this, need to clear the high order
418 // bit of rotated if the high order bit of c is set. Since we don't
419 // care about the other bits in rotated, the easiest thing to do
420 // is invert all the bits in c and bitwise-and them with rotated.
424 // Step 6: Apply a mask to clear everything except the 0x20 bit
428 // At this point, rotated is 0x20 if c is 'A'-'Z' and 0x00 otherwise
430 // Step 7: Add rotated to c
434 void toLowerAscii32(uint32_t& c) {
435 // Besides being branchless, the algorithm in toLowerAscii8() has another
436 // interesting property: None of the addition operations will cause
437 // an overflow in the 8-bit value. So we can pack four 8-bit values
438 // into a uint32_t and run each operation on all four values in parallel
439 // without having to use any CPU-specific SIMD instructions.
440 uint32_t rotated = c & uint32_t(0x7f7f7f7fL);
441 rotated += uint32_t(0x25252525L);
442 rotated &= uint32_t(0x7f7f7f7fL);
443 rotated += uint32_t(0x1a1a1a1aL);
445 // Step 5 involves a shift, so some bits will spill over from each
446 // 8-bit value into the next. But that's okay, because they're bits
447 // that will be cleared by the mask in step 6 anyway.
450 rotated &= uint32_t(0x20202020L);
454 void toLowerAscii64(uint64_t& c) {
455 // 64-bit version of toLower32
456 uint64_t rotated = c & uint64_t(0x7f7f7f7f7f7f7f7fL);
457 rotated += uint64_t(0x2525252525252525L);
458 rotated &= uint64_t(0x7f7f7f7f7f7f7f7fL);
459 rotated += uint64_t(0x1a1a1a1a1a1a1a1aL);
462 rotated &= uint64_t(0x2020202020202020L);
468 void toLowerAscii(char* str, size_t length) {
469 static const size_t kAlignMask64 = 7;
470 static const size_t kAlignMask32 = 3;
472 // Convert a character at a time until we reach an address that
473 // is at least 32-bit aligned
474 size_t n = (size_t)str;
476 n = std::min(n, length);
479 n = std::min(4 - n, length);
481 toLowerAscii8(str[offset]);
483 } while (offset < n);
486 n = (size_t)(str + offset);
488 if ((n != 0) && (offset + 4 <= length)) {
489 // The next address is 32-bit aligned but not 64-bit aligned.
490 // Convert the next 4 bytes in order to get to the 64-bit aligned
491 // part of the input.
492 toLowerAscii32(*(uint32_t*)(str + offset));
496 // Convert 8 characters at a time
497 while (offset + 8 <= length) {
498 toLowerAscii64(*(uint64_t*)(str + offset));
502 // Convert 4 characters at a time
503 while (offset + 4 <= length) {
504 toLowerAscii32(*(uint32_t*)(str + offset));
508 // Convert any characters remaining after the last 4-byte aligned group
509 while (offset < length) {
510 toLowerAscii8(str[offset]);
517 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
522 // (1+2)*16: hex bytes, each preceded by a space
523 // 1: space separating the two halves
530 const uint8_t* p = reinterpret_cast<const uint8_t*>(ptr) + offset;
531 size_t n = std::min(size - offset, size_t(16));
532 format("{:08x} ", offset).appendTo(line);
534 for (size_t i = 0; i < n; i++) {
538 format(" {:02x}", p[i]).appendTo(line);
541 // 3 spaces for each byte we're not printing, one separating the halves
543 line.append(3 * (16 - n) + (n <= 8), ' ');
546 for (size_t i = 0; i < n; i++) {
547 char c = (p[i] >= 32 && p[i] <= 126 ? static_cast<char>(p[i]) : '.');
550 line.append(16 - n, ' ');
552 DCHECK_EQ(line.size(), 78);
557 } // namespace detail
561 #ifdef FOLLY_DEFINED_DMGL
562 # undef FOLLY_DEFINED_DMGL
569 # undef DMGL_RET_POSTFIX