Break dependency on features.h
[folly.git] / folly / String.cpp
1 /*
2  * Copyright 2013 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "folly/String.h"
18 #include "folly/Format.h"
19
20 #include <cerrno>
21 #include <cstdarg>
22 #include <cstring>
23 #include <stdexcept>
24 #include <iterator>
25 #include <glog/logging.h>
26
27 #undef FOLLY_DEMANGLE
28 #if defined(__GNUG__) && __GNUG__ >= 4
29 # include <cxxabi.h>
30 # define FOLLY_DEMANGLE 1
31 #endif
32
33 namespace folly {
34
35 namespace {
36
37 inline void stringPrintfImpl(std::string& output, const char* format,
38                              va_list args) {
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.
44
45   const auto write_point = output.size();
46   auto remaining = output.capacity() - write_point;
47   output.resize(output.capacity());
48
49   va_list args_copy;
50   va_copy(args_copy, args);
51   int bytes_used = vsnprintf(&output[write_point], remaining, format,
52                              args_copy);
53   va_end(args_copy);
54   if (bytes_used < 0) {
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);
61   } else {
62     output.resize(write_point + bytes_used + 1);
63     remaining = bytes_used + 1;
64     va_list args_copy;
65     va_copy(args_copy, args);
66     bytes_used = vsnprintf(&output[write_point], remaining, format,
67                            args_copy);
68     va_end(args_copy);
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));
73     }
74     output.resize(write_point + bytes_used);
75   }
76 }
77
78 }  // anon namespace
79
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');
91   ret.resize(0);
92
93   va_list ap;
94   va_start(ap, format);
95   stringPrintfImpl(ret, format, ap);
96   va_end(ap);
97   return ret;
98 }
99
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, ...) {
103   va_list ap;
104   va_start(ap, format);
105   stringPrintfImpl(*output, format, ap);
106   va_end(ap);
107   return *output;
108 }
109
110 void stringPrintf(std::string* output, const char* format, ...) {
111   output->clear();
112   va_list ap;
113   va_start(ap, format);
114   stringPrintfImpl(*output, format, ap);
115   va_end(ap);
116 };
117
118 namespace {
119
120 struct PrettySuffix {
121   const char* suffix;
122   double val;
123 };
124
125 const PrettySuffix kPrettyTimeSuffixes[] = {
126   { "s ", 1e0L },
127   { "ms", 1e-3L },
128   { "us", 1e-6L },
129   { "ns", 1e-9L },
130   { "ps", 1e-12L },
131   { "s ", 0 },
132   { 0, 0 },
133 };
134
135 const PrettySuffix kPrettyBytesMetricSuffixes[] = {
136   { "TB", 1e12L },
137   { "GB", 1e9L },
138   { "MB", 1e6L },
139   { "kB", 1e3L },
140   { "B ", 0L },
141   { 0, 0 },
142 };
143
144 const PrettySuffix kPrettyBytesBinarySuffixes[] = {
145   { "TB", int64_t(1) << 40 },
146   { "GB", int64_t(1) << 30 },
147   { "MB", int64_t(1) << 20 },
148   { "kB", int64_t(1) << 10 },
149   { "B ", 0L },
150   { 0, 0 },
151 };
152
153 const PrettySuffix kPrettyBytesBinaryIECSuffixes[] = {
154   { "TiB", int64_t(1) << 40 },
155   { "GiB", int64_t(1) << 30 },
156   { "MiB", int64_t(1) << 20 },
157   { "KiB", int64_t(1) << 10 },
158   { "B  ", 0L },
159   { 0, 0 },
160 };
161
162 const PrettySuffix kPrettyUnitsMetricSuffixes[] = {
163   { "tril", 1e12L },
164   { "bil",  1e9L },
165   { "M",    1e6L },
166   { "k",    1e3L },
167   { " ",      0  },
168   { 0, 0 },
169 };
170
171 const PrettySuffix kPrettyUnitsBinarySuffixes[] = {
172   { "T", int64_t(1) << 40 },
173   { "G", int64_t(1) << 30 },
174   { "M", int64_t(1) << 20 },
175   { "k", int64_t(1) << 10 },
176   { " ", 0 },
177   { 0, 0 },
178 };
179
180 const PrettySuffix kPrettyUnitsBinaryIECSuffixes[] = {
181   { "Ti", int64_t(1) << 40 },
182   { "Gi", int64_t(1) << 30 },
183   { "Mi", int64_t(1) << 20 },
184   { "Ki", int64_t(1) << 10 },
185   { "  ", 0 },
186   { 0, 0 },
187 };
188
189 const PrettySuffix* const kPrettySuffixes[PRETTY_NUM_TYPES] = {
190   kPrettyTimeSuffixes,
191   kPrettyBytesMetricSuffixes,
192   kPrettyBytesBinarySuffixes,
193   kPrettyBytesBinaryIECSuffixes,
194   kPrettyUnitsMetricSuffixes,
195   kPrettyUnitsBinarySuffixes,
196   kPrettyUnitsBinaryIECSuffixes,
197 };
198
199 }  // namespace
200
201 std::string prettyPrint(double val, PrettyType type, bool addSpace) {
202   char buf[100];
203
204   // pick the suffixes to use
205   assert(type >= 0);
206   assert(type < PRETTY_NUM_TYPES);
207   const PrettySuffix* suffixes = kPrettySuffixes[type];
208
209   // find the first suffix we're bigger than -- then use it
210   double abs_val = fabs(val);
211   for (int i = 0; suffixes[i].suffix; ++i) {
212     if (abs_val >= suffixes[i].val) {
213       snprintf(buf, sizeof buf, "%.4g%s%s",
214                (suffixes[i].val ? (val / suffixes[i].val)
215                                 : val),
216                (addSpace ? " " : ""),
217                suffixes[i].suffix);
218       return std::string(buf);
219     }
220   }
221
222   // no suffix, we've got a tiny value -- just print it in sci-notation
223   snprintf(buf, sizeof buf, "%.4g", val);
224   return std::string(buf);
225 }
226
227 std::string hexDump(const void* ptr, size_t size) {
228   std::ostringstream os;
229   hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
230   return os.str();
231 }
232
233 fbstring errnoStr(int err) {
234   int savedErrno = errno;
235
236   // Ensure that we reset errno upon exit.
237   auto guard(makeGuard([&] { errno = savedErrno; }));
238
239   char buf[1024];
240   buf[0] = '\0';
241
242   fbstring result;
243
244   // http://www.kernel.org/doc/man-pages/online/pages/man3/strerror.3.html
245 #if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE
246   // Using XSI-compatible strerror_r
247   int r = strerror_r(err, buf, sizeof(buf));
248
249   if (r == -1) {
250     result = to<fbstring>(
251       "Unknown error ", err,
252       " (strerror_r failed with error ", errno, ")");
253   } else {
254     result.assign(buf);
255   }
256 #else
257   // Using GNU strerror_r
258   result.assign(strerror_r(err, buf, sizeof(buf)));
259 #endif
260
261   return result;
262 }
263
264 #ifdef FOLLY_DEMANGLE
265
266 fbstring demangle(const char* name) {
267   int status;
268   size_t len = 0;
269   // malloc() memory for the demangled type name
270   char* demangled = abi::__cxa_demangle(name, nullptr, &len, &status);
271   if (status != 0) {
272     return name;
273   }
274   // len is the length of the buffer (including NUL terminator and maybe
275   // other junk)
276   return fbstring(demangled, strlen(demangled), len, AcquireMallocatedString());
277 }
278
279 #else
280
281 fbstring demangle(const char* name) {
282   return name;
283 }
284
285 #endif
286 #undef FOLLY_DEMANGLE
287
288 namespace detail {
289
290 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
291                    std::string& line) {
292   // Line layout:
293   // 8: address
294   // 1: space
295   // (1+2)*16: hex bytes, each preceded by a space
296   // 1: space separating the two halves
297   // 3: "  |"
298   // 16: characters
299   // 1: "|"
300   // Total: 78
301   line.clear();
302   line.reserve(78);
303   const uint8_t* p = reinterpret_cast<const uint8_t*>(ptr) + offset;
304   size_t n = std::min(size - offset, size_t(16));
305   format("{:08x} ", offset).appendTo(line);
306
307   for (size_t i = 0; i < n; i++) {
308     if (i == 8) {
309       line.push_back(' ');
310     }
311     format(" {:02x}", p[i]).appendTo(line);
312   }
313
314   // 3 spaces for each byte we're not printing, one separating the halves
315   // if necessary
316   line.append(3 * (16 - n) + (n <= 8), ' ');
317   line.append("  |");
318
319   for (size_t i = 0; i < n; i++) {
320     char c = (p[i] >= 32 && p[i] <= 126 ? static_cast<char>(p[i]) : '.');
321     line.push_back(c);
322   }
323   line.append(16 - n, ' ');
324   line.push_back('|');
325   DCHECK_EQ(line.size(), 78);
326
327   return n;
328 }
329
330 } // namespace detail
331
332 }   // namespace folly