2 * Copyright 2012 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"
18 #include "folly/Format.h"
25 #include <glog/logging.h>
28 #if defined(__GNUG__) && __GNUG__ >= 4
30 # define FOLLY_DEMANGLE 1
37 inline void stringPrintfImpl(std::string& output, const char* format,
39 // Tru to the space at the end of output for our output buffer.
40 // Find out write point then inflate its size temporarily to its
41 // capacity; we will later shrink it to the size needed to represent
42 // the formatted string. If this buffer isn't large enough, we do a
43 // resize and try again.
45 const auto write_point = output.size();
46 auto remaining = output.capacity() - write_point;
47 output.resize(output.capacity());
50 va_copy(args_copy, args);
51 int bytes_used = vsnprintf(&output[write_point], remaining, format,
55 throw std::runtime_error(
56 to<std::string>("Invalid format string; snprintf returned negative "
57 "with format string: ", format));
58 } else if (bytes_used < remaining) {
59 // There was enough room, just shrink and return.
60 output.resize(write_point + bytes_used);
62 output.resize(write_point + bytes_used + 1);
63 remaining = bytes_used + 1;
65 va_copy(args_copy, args);
66 bytes_used = vsnprintf(&output[write_point], remaining, format,
69 if (bytes_used + 1 != remaining) {
70 throw std::runtime_error(
71 to<std::string>("vsnprint retry did not manage to work "
72 "with format string: ", format));
74 output.resize(write_point + bytes_used);
80 std::string stringPrintf(const char* format, ...) {
81 // snprintf will tell us how large the output buffer should be, but
82 // we then have to call it a second time, which is costly. By
83 // guestimating the final size, we avoid the double snprintf in many
84 // cases, resulting in a performance win. We use this constructor
85 // of std::string to avoid a double allocation, though it does pad
86 // the resulting string with nul bytes. Our guestimation is twice
87 // the format string size, or 32 bytes, whichever is larger. This
88 // is a hueristic that doesn't affect correctness but attempts to be
89 // reasonably fast for the most common cases.
90 std::string ret(std::max(32UL, strlen(format) * 2), '\0');
95 stringPrintfImpl(ret, format, ap);
100 // Basic declarations; allow for parameters of strings and string
101 // pieces to be specified.
102 std::string& stringAppendf(std::string* output, const char* format, ...) {
104 va_start(ap, format);
105 stringPrintfImpl(*output, format, ap);
110 void stringPrintf(std::string* output, const char* format, ...) {
113 va_start(ap, format);
114 stringPrintfImpl(*output, format, ap);
120 struct PrettySuffix {
125 const PrettySuffix kPrettyTimeSuffixes[] = {
135 const PrettySuffix kPrettyBytesSuffixes[] = {
136 { "TB", int64_t(1) << 40 },
137 { "GB", int64_t(1) << 30 },
138 { "MB", int64_t(1) << 20 },
139 { "kB", int64_t(1) << 10 },
144 const PrettySuffix kPrettyBytesMetricSuffixes[] = {
153 const PrettySuffix kPrettyUnitsMetricSuffixes[] = {
162 const PrettySuffix kPrettyUnitsBinarySuffixes[] = {
163 { "T", int64_t(1) << 40 },
164 { "G", int64_t(1) << 30 },
165 { "M", int64_t(1) << 20 },
166 { "k", int64_t(1) << 10 },
171 const PrettySuffix* const kPrettySuffixes[PRETTY_NUM_TYPES] = {
173 kPrettyBytesSuffixes,
174 kPrettyBytesMetricSuffixes,
175 kPrettyUnitsMetricSuffixes,
176 kPrettyUnitsBinarySuffixes,
181 std::string prettyPrint(double val, PrettyType type, bool addSpace) {
184 // pick the suffixes to use
186 assert(type < PRETTY_NUM_TYPES);
187 const PrettySuffix* suffixes = kPrettySuffixes[type];
189 // find the first suffix we're bigger than -- then use it
190 double abs_val = fabs(val);
191 for (int i = 0; suffixes[i].suffix; ++i) {
192 if (abs_val >= suffixes[i].val) {
193 snprintf(buf, sizeof buf, "%.4g%s%s",
194 (suffixes[i].val ? (val / suffixes[i].val)
196 (addSpace ? " " : ""),
198 return std::string(buf);
202 // no suffix, we've got a tiny value -- just print it in sci-notation
203 snprintf(buf, sizeof buf, "%.4g", val);
204 return std::string(buf);
207 std::string hexDump(const void* ptr, size_t size) {
208 std::ostringstream os;
209 hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
213 fbstring errnoStr(int err) {
214 int savedErrno = errno;
216 // Ensure that we reset errno upon exit.
217 auto guard(makeGuard([&] { errno = savedErrno; }));
224 // http://www.kernel.org/doc/man-pages/online/pages/man3/strerror.3.html
225 #if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 || \
226 !FOLLY_HAVE_FEATURES_H) && !_GNU_SOURCE
227 // Using XSI-compatible strerror_r
228 int r = strerror_r(err, buf, sizeof(buf));
231 result = to<fbstring>(
232 "Unknown error ", err,
233 " (strerror_r failed with error ", errno, ")");
238 // Using GNU strerror_r
239 result.assign(strerror_r(err, buf, sizeof(buf)));
245 #ifdef FOLLY_DEMANGLE
247 fbstring demangle(const char* name) {
250 // malloc() memory for the demangled type name
251 char* demangled = abi::__cxa_demangle(name, nullptr, &len, &status);
255 // len is the length of the buffer (including NUL terminator and maybe
257 return fbstring(demangled, strlen(demangled), len, AcquireMallocatedString());
262 fbstring demangle(const char* name) {
267 #undef FOLLY_DEMANGLE
271 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
276 // (1+2)*16: hex bytes, each preceded by a space
277 // 1: space separating the two halves
284 const uint8_t* p = reinterpret_cast<const uint8_t*>(ptr) + offset;
285 size_t n = std::min(size - offset, size_t(16));
286 format("{:08x} ", offset).appendTo(line);
288 for (size_t i = 0; i < n; i++) {
292 format(" {:02x}", p[i]).appendTo(line);
295 // 3 spaces for each byte we're not printing, one separating the halves
297 line.append(3 * (16 - n) + (n <= 8), ' ');
300 for (size_t i = 0; i < n; i++) {
301 char c = (p[i] >= 32 && p[i] <= 126 ? static_cast<char>(p[i]) : '.');
304 line.append(16 - n, ' ');
306 DCHECK_EQ(line.size(), 78);
311 } // namespace detail