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