forked from facebook/folly
/
String.cpp
313 lines (266 loc) · 8.17 KB
/
String.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "folly/String.h"
#include "folly/Format.h"
#include <cerrno>
#include <cstdarg>
#include <cstring>
#include <stdexcept>
#include <iterator>
#include <glog/logging.h>
#undef FOLLY_DEMANGLE
#if defined(__GNUG__) && __GNUG__ >= 4
# include <cxxabi.h>
# define FOLLY_DEMANGLE 1
#endif
namespace folly {
namespace {
inline void stringPrintfImpl(std::string& output, const char* format,
va_list args) {
// Tru to the space at the end of output for our output buffer.
// Find out write point then inflate its size temporarily to its
// capacity; we will later shrink it to the size needed to represent
// the formatted string. If this buffer isn't large enough, we do a
// resize and try again.
const auto write_point = output.size();
auto remaining = output.capacity() - write_point;
output.resize(output.capacity());
va_list args_copy;
va_copy(args_copy, args);
int bytes_used = vsnprintf(&output[write_point], remaining, format,
args_copy);
va_end(args_copy);
if (bytes_used < 0) {
throw std::runtime_error(
to<std::string>("Invalid format string; snprintf returned negative "
"with format string: ", format));
} else if (bytes_used < remaining) {
// There was enough room, just shrink and return.
output.resize(write_point + bytes_used);
} else {
output.resize(write_point + bytes_used + 1);
remaining = bytes_used + 1;
va_list args_copy;
va_copy(args_copy, args);
bytes_used = vsnprintf(&output[write_point], remaining, format,
args_copy);
va_end(args_copy);
if (bytes_used + 1 != remaining) {
throw std::runtime_error(
to<std::string>("vsnprint retry did not manage to work "
"with format string: ", format));
}
output.resize(write_point + bytes_used);
}
}
} // anon namespace
std::string stringPrintf(const char* format, ...) {
// snprintf will tell us how large the output buffer should be, but
// we then have to call it a second time, which is costly. By
// guestimating the final size, we avoid the double snprintf in many
// cases, resulting in a performance win. We use this constructor
// of std::string to avoid a double allocation, though it does pad
// the resulting string with nul bytes. Our guestimation is twice
// the format string size, or 32 bytes, whichever is larger. This
// is a hueristic that doesn't affect correctness but attempts to be
// reasonably fast for the most common cases.
std::string ret(std::max(32UL, strlen(format) * 2), '\0');
ret.resize(0);
va_list ap;
va_start(ap, format);
stringPrintfImpl(ret, format, ap);
va_end(ap);
return ret;
}
// Basic declarations; allow for parameters of strings and string
// pieces to be specified.
std::string& stringAppendf(std::string* output, const char* format, ...) {
va_list ap;
va_start(ap, format);
stringPrintfImpl(*output, format, ap);
va_end(ap);
return *output;
}
void stringPrintf(std::string* output, const char* format, ...) {
output->clear();
va_list ap;
va_start(ap, format);
stringPrintfImpl(*output, format, ap);
va_end(ap);
};
namespace {
struct PrettySuffix {
const char* suffix;
double val;
};
const PrettySuffix kPrettyTimeSuffixes[] = {
{ "s ", 1e0L },
{ "ms", 1e-3L },
{ "us", 1e-6L },
{ "ns", 1e-9L },
{ "ps", 1e-12L },
{ "s ", 0 },
{ 0, 0 },
};
const PrettySuffix kPrettyBytesSuffixes[] = {
{ "TB", int64_t(1) << 40 },
{ "GB", int64_t(1) << 30 },
{ "MB", int64_t(1) << 20 },
{ "kB", int64_t(1) << 10 },
{ "B ", 0L },
{ 0, 0 },
};
const PrettySuffix kPrettyBytesMetricSuffixes[] = {
{ "TB", 1e12L },
{ "GB", 1e9L },
{ "MB", 1e6L },
{ "kB", 1e3L },
{ "B ", 0L },
{ 0, 0 },
};
const PrettySuffix kPrettyUnitsMetricSuffixes[] = {
{ "tril", 1e12L },
{ "bil", 1e9L },
{ "M", 1e6L },
{ "k", 1e3L },
{ " ", 0 },
{ 0, 0 },
};
const PrettySuffix kPrettyUnitsBinarySuffixes[] = {
{ "T", int64_t(1) << 40 },
{ "G", int64_t(1) << 30 },
{ "M", int64_t(1) << 20 },
{ "k", int64_t(1) << 10 },
{ " ", 0 },
{ 0, 0 },
};
const PrettySuffix* const kPrettySuffixes[PRETTY_NUM_TYPES] = {
kPrettyTimeSuffixes,
kPrettyBytesSuffixes,
kPrettyBytesMetricSuffixes,
kPrettyUnitsMetricSuffixes,
kPrettyUnitsBinarySuffixes,
};
} // namespace
std::string prettyPrint(double val, PrettyType type, bool addSpace) {
char buf[100];
// pick the suffixes to use
assert(type >= 0);
assert(type < PRETTY_NUM_TYPES);
const PrettySuffix* suffixes = kPrettySuffixes[type];
// find the first suffix we're bigger than -- then use it
double abs_val = fabs(val);
for (int i = 0; suffixes[i].suffix; ++i) {
if (abs_val >= suffixes[i].val) {
snprintf(buf, sizeof buf, "%.4g%s%s",
(suffixes[i].val ? (val / suffixes[i].val)
: val),
(addSpace ? " " : ""),
suffixes[i].suffix);
return std::string(buf);
}
}
// no suffix, we've got a tiny value -- just print it in sci-notation
snprintf(buf, sizeof buf, "%.4g", val);
return std::string(buf);
}
std::string hexDump(const void* ptr, size_t size) {
std::ostringstream os;
hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
return os.str();
}
fbstring errnoStr(int err) {
int savedErrno = errno;
// Ensure that we reset errno upon exit.
auto guard(makeGuard([&] { errno = savedErrno; }));
char buf[1024];
buf[0] = '\0';
fbstring result;
// http://www.kernel.org/doc/man-pages/online/pages/man3/strerror.3.html
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 || \
!FOLLY_HAVE_FEATURES_H) && !_GNU_SOURCE
// Using XSI-compatible strerror_r
int r = strerror_r(err, buf, sizeof(buf));
if (r == -1) {
result = to<fbstring>(
"Unknown error ", err,
" (strerror_r failed with error ", errno, ")");
} else {
result.assign(buf);
}
#else
// Using GNU strerror_r
result.assign(strerror_r(err, buf, sizeof(buf)));
#endif
return result;
}
#ifdef FOLLY_DEMANGLE
fbstring demangle(const char* name) {
int status;
size_t len = 0;
// malloc() memory for the demangled type name
char* demangled = abi::__cxa_demangle(name, nullptr, &len, &status);
if (status != 0) {
return name;
}
// len is the length of the buffer (including NUL terminator and maybe
// other junk)
return fbstring(demangled, strlen(demangled), len, AcquireMallocatedString());
}
#else
fbstring demangle(const char* name) {
return name;
}
#endif
#undef FOLLY_DEMANGLE
namespace detail {
size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
std::string& line) {
// Line layout:
// 8: address
// 1: space
// (1+2)*16: hex bytes, each preceded by a space
// 1: space separating the two halves
// 3: " |"
// 16: characters
// 1: "|"
// Total: 78
line.clear();
line.reserve(78);
const uint8_t* p = reinterpret_cast<const uint8_t*>(ptr) + offset;
size_t n = std::min(size - offset, size_t(16));
format("{:08x} ", offset).appendTo(line);
for (size_t i = 0; i < n; i++) {
if (i == 8) {
line.push_back(' ');
}
format(" {:02x}", p[i]).appendTo(line);
}
// 3 spaces for each byte we're not printing, one separating the halves
// if necessary
line.append(3 * (16 - n) + (n <= 8), ' ');
line.append(" |");
for (size_t i = 0; i < n; i++) {
char c = (p[i] >= 32 && p[i] <= 126 ? static_cast<char>(p[i]) : '.');
line.push_back(c);
}
line.append(16 - n, ' ');
line.push_back('|');
DCHECK_EQ(line.size(), 78);
return n;
}
} // namespace detail
} // namespace folly