Codemod: use #include angle brackets in folly and thrift
[folly.git] / folly / String.cpp
1 /*
2  * Copyright 2014 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 <cctype>
26 #include <glog/logging.h>
27
28 namespace folly {
29
30 namespace {
31
32 inline void stringPrintfImpl(std::string& output, const char* format,
33                              va_list args) {
34   // Tru to the space at the end of output for our output buffer.
35   // Find out write point then inflate its size temporarily to its
36   // capacity; we will later shrink it to the size needed to represent
37   // the formatted string.  If this buffer isn't large enough, we do a
38   // resize and try again.
39
40   const auto write_point = output.size();
41   auto remaining = output.capacity() - write_point;
42   output.resize(output.capacity());
43
44   va_list args_copy;
45   va_copy(args_copy, args);
46   int bytes_used = vsnprintf(&output[write_point], remaining, format,
47                              args_copy);
48   va_end(args_copy);
49   if (bytes_used < 0) {
50     throw std::runtime_error(
51       to<std::string>("Invalid format string; snprintf returned negative "
52                       "with format string: ", format));
53   } else if (bytes_used < remaining) {
54     // There was enough room, just shrink and return.
55     output.resize(write_point + bytes_used);
56   } else {
57     output.resize(write_point + bytes_used + 1);
58     remaining = bytes_used + 1;
59     va_list args_copy;
60     va_copy(args_copy, args);
61     bytes_used = vsnprintf(&output[write_point], remaining, format,
62                            args_copy);
63     va_end(args_copy);
64     if (bytes_used + 1 != remaining) {
65       throw std::runtime_error(
66         to<std::string>("vsnprint retry did not manage to work "
67                         "with format string: ", format));
68     }
69     output.resize(write_point + bytes_used);
70   }
71 }
72
73 }  // anon namespace
74
75 std::string stringPrintf(const char* format, ...) {
76   // snprintf will tell us how large the output buffer should be, but
77   // we then have to call it a second time, which is costly.  By
78   // guestimating the final size, we avoid the double snprintf in many
79   // cases, resulting in a performance win.  We use this constructor
80   // of std::string to avoid a double allocation, though it does pad
81   // the resulting string with nul bytes.  Our guestimation is twice
82   // the format string size, or 32 bytes, whichever is larger.  This
83   // is a hueristic that doesn't affect correctness but attempts to be
84   // reasonably fast for the most common cases.
85   std::string ret(std::max(32UL, strlen(format) * 2), '\0');
86   ret.resize(0);
87
88   va_list ap;
89   va_start(ap, format);
90   stringPrintfImpl(ret, format, ap);
91   va_end(ap);
92   return ret;
93 }
94
95 // Basic declarations; allow for parameters of strings and string
96 // pieces to be specified.
97 std::string& stringAppendf(std::string* output, const char* format, ...) {
98   va_list ap;
99   va_start(ap, format);
100   stringPrintfImpl(*output, format, ap);
101   va_end(ap);
102   return *output;
103 }
104
105 void stringPrintf(std::string* output, const char* format, ...) {
106   output->clear();
107   va_list ap;
108   va_start(ap, format);
109   stringPrintfImpl(*output, format, ap);
110   va_end(ap);
111 };
112
113 namespace {
114
115 struct PrettySuffix {
116   const char* suffix;
117   double val;
118 };
119
120 const PrettySuffix kPrettyTimeSuffixes[] = {
121   { "s ", 1e0L },
122   { "ms", 1e-3L },
123   { "us", 1e-6L },
124   { "ns", 1e-9L },
125   { "ps", 1e-12L },
126   { "s ", 0 },
127   { 0, 0 },
128 };
129
130 const PrettySuffix kPrettyBytesMetricSuffixes[] = {
131   { "TB", 1e12L },
132   { "GB", 1e9L },
133   { "MB", 1e6L },
134   { "kB", 1e3L },
135   { "B ", 0L },
136   { 0, 0 },
137 };
138
139 const PrettySuffix kPrettyBytesBinarySuffixes[] = {
140   { "TB", int64_t(1) << 40 },
141   { "GB", int64_t(1) << 30 },
142   { "MB", int64_t(1) << 20 },
143   { "kB", int64_t(1) << 10 },
144   { "B ", 0L },
145   { 0, 0 },
146 };
147
148 const PrettySuffix kPrettyBytesBinaryIECSuffixes[] = {
149   { "TiB", int64_t(1) << 40 },
150   { "GiB", int64_t(1) << 30 },
151   { "MiB", int64_t(1) << 20 },
152   { "KiB", int64_t(1) << 10 },
153   { "B  ", 0L },
154   { 0, 0 },
155 };
156
157 const PrettySuffix kPrettyUnitsMetricSuffixes[] = {
158   { "tril", 1e12L },
159   { "bil",  1e9L },
160   { "M",    1e6L },
161   { "k",    1e3L },
162   { " ",      0  },
163   { 0, 0 },
164 };
165
166 const PrettySuffix kPrettyUnitsBinarySuffixes[] = {
167   { "T", int64_t(1) << 40 },
168   { "G", int64_t(1) << 30 },
169   { "M", int64_t(1) << 20 },
170   { "k", int64_t(1) << 10 },
171   { " ", 0 },
172   { 0, 0 },
173 };
174
175 const PrettySuffix kPrettyUnitsBinaryIECSuffixes[] = {
176   { "Ti", int64_t(1) << 40 },
177   { "Gi", int64_t(1) << 30 },
178   { "Mi", int64_t(1) << 20 },
179   { "Ki", int64_t(1) << 10 },
180   { "  ", 0 },
181   { 0, 0 },
182 };
183
184 const PrettySuffix kPrettySISuffixes[] = {
185   { "Y", 1e24L },
186   { "Z", 1e21L },
187   { "E", 1e18L },
188   { "P", 1e15L },
189   { "T", 1e12L },
190   { "G", 1e9L },
191   { "M", 1e6L },
192   { "k", 1e3L },
193   { "h", 1e2L },
194   { "da", 1e1L },
195   { "d", 1e-1L },
196   { "c", 1e-2L },
197   { "m", 1e-3L },
198   { "u", 1e-6L },
199   { "n", 1e-9L },
200   { "p", 1e-12L },
201   { "f", 1e-15L },
202   { "a", 1e-18L },
203   { "z", 1e-21L },
204   { "y", 1e-24L },
205   { " ", 0 },
206   { 0, 0} 
207 };
208
209 const PrettySuffix* const kPrettySuffixes[PRETTY_NUM_TYPES] = {
210   kPrettyTimeSuffixes,
211   kPrettyBytesMetricSuffixes,
212   kPrettyBytesBinarySuffixes,
213   kPrettyBytesBinaryIECSuffixes,
214   kPrettyUnitsMetricSuffixes,
215   kPrettyUnitsBinarySuffixes,
216   kPrettyUnitsBinaryIECSuffixes,
217   kPrettySISuffixes,
218 };
219
220 }  // namespace
221
222 std::string prettyPrint(double val, PrettyType type, bool addSpace) {
223   char buf[100];
224
225   // pick the suffixes to use
226   assert(type >= 0);
227   assert(type < PRETTY_NUM_TYPES);
228   const PrettySuffix* suffixes = kPrettySuffixes[type];
229
230   // find the first suffix we're bigger than -- then use it
231   double abs_val = fabs(val);
232   for (int i = 0; suffixes[i].suffix; ++i) {
233     if (abs_val >= suffixes[i].val) {
234       snprintf(buf, sizeof buf, "%.4g%s%s",
235                (suffixes[i].val ? (val / suffixes[i].val)
236                                 : val),
237                (addSpace ? " " : ""),
238                suffixes[i].suffix);
239       return std::string(buf);
240     }
241   }
242
243   // no suffix, we've got a tiny value -- just print it in sci-notation
244   snprintf(buf, sizeof buf, "%.4g", val);
245   return std::string(buf);
246 }
247
248 //TODO:
249 //1) Benchmark & optimize
250 double prettyToDouble(folly::StringPiece *const prettyString, 
251                       const PrettyType type) {
252   double value = folly::to<double>(prettyString);
253   while (prettyString->size() > 0 && std::isspace(prettyString->front())) {
254     prettyString->advance(1); //Skipping spaces between number and suffix
255   }
256   const PrettySuffix* suffixes = kPrettySuffixes[type];
257   int longestPrefixLen = -1;
258   int bestPrefixId = -1;
259   for (int j = 0 ; suffixes[j].suffix; ++j) {
260     if (suffixes[j].suffix[0] == ' '){//Checking for " " -> number rule.
261       if (longestPrefixLen == -1) {
262         longestPrefixLen = 0; //No characters to skip
263         bestPrefixId = j;
264       }
265     } else if (prettyString->startsWith(suffixes[j].suffix)) {
266       int suffixLen = strlen(suffixes[j].suffix);
267       //We are looking for a longest suffix matching prefix of the string
268       //after numeric value. We need this in case suffixes have common prefix.
269       if (suffixLen > longestPrefixLen) {
270         longestPrefixLen = suffixLen;
271         bestPrefixId = j;
272       }
273     }
274   }
275   if (bestPrefixId == -1) { //No valid suffix rule found
276     throw std::invalid_argument(folly::to<std::string>(
277             "Unable to parse suffix \"",
278             prettyString->toString(), "\""));
279   }
280   prettyString->advance(longestPrefixLen);
281   return suffixes[bestPrefixId].val ? value * suffixes[bestPrefixId].val : 
282                                       value;
283 }
284
285 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type){
286   double result = prettyToDouble(&prettyString, type);
287   detail::enforceWhitespace(prettyString.data(), 
288                             prettyString.data() + prettyString.size());
289   return result;
290 }
291
292 std::string hexDump(const void* ptr, size_t size) {
293   std::ostringstream os;
294   hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
295   return os.str();
296 }
297
298 fbstring errnoStr(int err) {
299   int savedErrno = errno;
300
301   // Ensure that we reset errno upon exit.
302   auto guard(makeGuard([&] { errno = savedErrno; }));
303
304   char buf[1024];
305   buf[0] = '\0';
306
307   fbstring result;
308
309   // https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/strerror_r.3.html
310   // http://www.kernel.org/doc/man-pages/online/pages/man3/strerror.3.html
311 #if defined(__APPLE__) || defined(__FreeBSD__) || \
312     ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE)
313   // Using XSI-compatible strerror_r
314   int r = strerror_r(err, buf, sizeof(buf));
315
316   // OSX/FreeBSD use EINVAL and Linux uses -1 so just check for non-zero
317   if (r != 0) {
318     result = to<fbstring>(
319       "Unknown error ", err,
320       " (strerror_r failed with error ", errno, ")");
321   } else {
322     result.assign(buf);
323   }
324 #else
325   // Using GNU strerror_r
326   result.assign(strerror_r(err, buf, sizeof(buf)));
327 #endif
328
329   return result;
330 }
331
332 namespace detail {
333
334 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
335                    std::string& line) {
336   // Line layout:
337   // 8: address
338   // 1: space
339   // (1+2)*16: hex bytes, each preceded by a space
340   // 1: space separating the two halves
341   // 3: "  |"
342   // 16: characters
343   // 1: "|"
344   // Total: 78
345   line.clear();
346   line.reserve(78);
347   const uint8_t* p = reinterpret_cast<const uint8_t*>(ptr) + offset;
348   size_t n = std::min(size - offset, size_t(16));
349   format("{:08x} ", offset).appendTo(line);
350
351   for (size_t i = 0; i < n; i++) {
352     if (i == 8) {
353       line.push_back(' ');
354     }
355     format(" {:02x}", p[i]).appendTo(line);
356   }
357
358   // 3 spaces for each byte we're not printing, one separating the halves
359   // if necessary
360   line.append(3 * (16 - n) + (n <= 8), ' ');
361   line.append("  |");
362
363   for (size_t i = 0; i < n; i++) {
364     char c = (p[i] >= 32 && p[i] <= 126 ? static_cast<char>(p[i]) : '.');
365     line.push_back(c);
366   }
367   line.append(16 - n, ' ');
368   line.push_back('|');
369   DCHECK_EQ(line.size(), 78);
370
371   return n;
372 }
373
374 } // namespace detail
375
376 }   // namespace folly
377
378 #ifdef FOLLY_DEFINED_DMGL
379 # undef FOLLY_DEFINED_DMGL
380 # undef DMGL_NO_OPTS
381 # undef DMGL_PARAMS
382 # undef DMGL_ANSI
383 # undef DMGL_JAVA
384 # undef DMGL_VERBOSE
385 # undef DMGL_TYPES
386 # undef DMGL_RET_POSTFIX
387 #endif
388