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"
18 #include "folly/Format.h"
25 #include <glog/logging.h>
31 inline void stringPrintfImpl(std::string& output, const char* format,
33 // Tru to the space at the end of output for our output buffer.
34 // Find out write point then inflate its size temporarily to its
35 // capacity; we will later shrink it to the size needed to represent
36 // the formatted string. If this buffer isn't large enough, we do a
37 // resize and try again.
39 const auto write_point = output.size();
40 auto remaining = output.capacity() - write_point;
41 output.resize(output.capacity());
44 va_copy(args_copy, args);
45 int bytes_used = vsnprintf(&output[write_point], remaining, format,
49 throw std::runtime_error(
50 to<std::string>("Invalid format string; snprintf returned negative "
51 "with format string: ", format));
52 } else if (bytes_used < remaining) {
53 // There was enough room, just shrink and return.
54 output.resize(write_point + bytes_used);
56 output.resize(write_point + bytes_used + 1);
57 remaining = bytes_used + 1;
59 va_copy(args_copy, args);
60 bytes_used = vsnprintf(&output[write_point], remaining, format,
63 if (bytes_used + 1 != remaining) {
64 throw std::runtime_error(
65 to<std::string>("vsnprint retry did not manage to work "
66 "with format string: ", format));
68 output.resize(write_point + bytes_used);
74 std::string stringPrintf(const char* format, ...) {
75 // snprintf will tell us how large the output buffer should be, but
76 // we then have to call it a second time, which is costly. By
77 // guestimating the final size, we avoid the double snprintf in many
78 // cases, resulting in a performance win. We use this constructor
79 // of std::string to avoid a double allocation, though it does pad
80 // the resulting string with nul bytes. Our guestimation is twice
81 // the format string size, or 32 bytes, whichever is larger. This
82 // is a hueristic that doesn't affect correctness but attempts to be
83 // reasonably fast for the most common cases.
84 std::string ret(std::max(32UL, strlen(format) * 2), '\0');
89 stringPrintfImpl(ret, format, ap);
94 // Basic declarations; allow for parameters of strings and string
95 // pieces to be specified.
96 std::string& stringAppendf(std::string* output, const char* format, ...) {
99 stringPrintfImpl(*output, format, ap);
104 void stringPrintf(std::string* output, const char* format, ...) {
107 va_start(ap, format);
108 stringPrintfImpl(*output, format, ap);
114 struct PrettySuffix {
119 const PrettySuffix kPrettyTimeSuffixes[] = {
129 const PrettySuffix kPrettyBytesMetricSuffixes[] = {
138 const PrettySuffix kPrettyBytesBinarySuffixes[] = {
139 { "TB", int64_t(1) << 40 },
140 { "GB", int64_t(1) << 30 },
141 { "MB", int64_t(1) << 20 },
142 { "kB", int64_t(1) << 10 },
147 const PrettySuffix kPrettyBytesBinaryIECSuffixes[] = {
148 { "TiB", int64_t(1) << 40 },
149 { "GiB", int64_t(1) << 30 },
150 { "MiB", int64_t(1) << 20 },
151 { "KiB", int64_t(1) << 10 },
156 const PrettySuffix kPrettyUnitsMetricSuffixes[] = {
165 const PrettySuffix kPrettyUnitsBinarySuffixes[] = {
166 { "T", int64_t(1) << 40 },
167 { "G", int64_t(1) << 30 },
168 { "M", int64_t(1) << 20 },
169 { "k", int64_t(1) << 10 },
174 const PrettySuffix kPrettyUnitsBinaryIECSuffixes[] = {
175 { "Ti", int64_t(1) << 40 },
176 { "Gi", int64_t(1) << 30 },
177 { "Mi", int64_t(1) << 20 },
178 { "Ki", int64_t(1) << 10 },
183 const PrettySuffix* const kPrettySuffixes[PRETTY_NUM_TYPES] = {
185 kPrettyBytesMetricSuffixes,
186 kPrettyBytesBinarySuffixes,
187 kPrettyBytesBinaryIECSuffixes,
188 kPrettyUnitsMetricSuffixes,
189 kPrettyUnitsBinarySuffixes,
190 kPrettyUnitsBinaryIECSuffixes,
195 std::string prettyPrint(double val, PrettyType type, bool addSpace) {
198 // pick the suffixes to use
200 assert(type < PRETTY_NUM_TYPES);
201 const PrettySuffix* suffixes = kPrettySuffixes[type];
203 // find the first suffix we're bigger than -- then use it
204 double abs_val = fabs(val);
205 for (int i = 0; suffixes[i].suffix; ++i) {
206 if (abs_val >= suffixes[i].val) {
207 snprintf(buf, sizeof buf, "%.4g%s%s",
208 (suffixes[i].val ? (val / suffixes[i].val)
210 (addSpace ? " " : ""),
212 return std::string(buf);
216 // no suffix, we've got a tiny value -- just print it in sci-notation
217 snprintf(buf, sizeof buf, "%.4g", val);
218 return std::string(buf);
221 std::string hexDump(const void* ptr, size_t size) {
222 std::ostringstream os;
223 hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
227 fbstring errnoStr(int err) {
228 int savedErrno = errno;
230 // Ensure that we reset errno upon exit.
231 auto guard(makeGuard([&] { errno = savedErrno; }));
238 // https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/strerror_r.3.html
239 // http://www.kernel.org/doc/man-pages/online/pages/man3/strerror.3.html
240 #if defined(__APPLE__) || defined(__FreeBSD__) || \
241 ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE)
242 // Using XSI-compatible strerror_r
243 int r = strerror_r(err, buf, sizeof(buf));
245 // OSX/FreeBSD use EINVAL and Linux uses -1 so just check for non-zero
247 result = to<fbstring>(
248 "Unknown error ", err,
249 " (strerror_r failed with error ", errno, ")");
254 // Using GNU strerror_r
255 result.assign(strerror_r(err, buf, sizeof(buf)));
263 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
268 // (1+2)*16: hex bytes, each preceded by a space
269 // 1: space separating the two halves
276 const uint8_t* p = reinterpret_cast<const uint8_t*>(ptr) + offset;
277 size_t n = std::min(size - offset, size_t(16));
278 format("{:08x} ", offset).appendTo(line);
280 for (size_t i = 0; i < n; i++) {
284 format(" {:02x}", p[i]).appendTo(line);
287 // 3 spaces for each byte we're not printing, one separating the halves
289 line.append(3 * (16 - n) + (n <= 8), ' ');
292 for (size_t i = 0; i < n; i++) {
293 char c = (p[i] >= 32 && p[i] <= 126 ? static_cast<char>(p[i]) : '.');
296 line.append(16 - n, ' ');
298 DCHECK_EQ(line.size(), 78);
303 } // namespace detail
307 #ifdef FOLLY_DEFINED_DMGL
308 # undef FOLLY_DEFINED_DMGL
315 # undef DMGL_RET_POSTFIX