1#include "string_util.h"
2
3#include <array>
4#include <cmath>
5#include <cstdarg>
6#include <cstdio>
7#include <memory>
8#include <sstream>
9
10#include "arraysize.h"
11
12namespace benchmark {
13namespace {
14
15// kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta.
16const char kBigSIUnits[] = "kMGTPEZY";
17// Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi.
18const char kBigIECUnits[] = "KMGTPEZY";
19// milli, micro, nano, pico, femto, atto, zepto, yocto.
20const char kSmallSIUnits[] = "munpfazy";
21
22// We require that all three arrays have the same size.
23static_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits),
24              "SI and IEC unit arrays must be the same size");
25static_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits),
26              "Small SI and Big SI unit arrays must be the same size");
27
28static const int64_t kUnitsSize = arraysize(kBigSIUnits);
29
30}  // end anonymous namespace
31
32void ToExponentAndMantissa(double val, double thresh, int precision,
33                           double one_k, std::string* mantissa,
34                           int64_t* exponent) {
35  std::stringstream mantissa_stream;
36
37  if (val < 0) {
38    mantissa_stream << "-";
39    val = -val;
40  }
41
42  // Adjust threshold so that it never excludes things which can't be rendered
43  // in 'precision' digits.
44  const double adjusted_threshold =
45      std::max(thresh, 1.0 / std::pow(10.0, precision));
46  const double big_threshold = adjusted_threshold * one_k;
47  const double small_threshold = adjusted_threshold;
48
49  if (val > big_threshold) {
50    // Positive powers
51    double scaled = val;
52    for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) {
53      scaled /= one_k;
54      if (scaled <= big_threshold) {
55        mantissa_stream << scaled;
56        *exponent = i + 1;
57        *mantissa = mantissa_stream.str();
58        return;
59      }
60    }
61    mantissa_stream << val;
62    *exponent = 0;
63  } else if (val < small_threshold) {
64    // Negative powers
65    double scaled = val;
66    for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) {
67      scaled *= one_k;
68      if (scaled >= small_threshold) {
69        mantissa_stream << scaled;
70        *exponent = -static_cast<int64_t>(i + 1);
71        *mantissa = mantissa_stream.str();
72        return;
73      }
74    }
75    mantissa_stream << val;
76    *exponent = 0;
77  } else {
78    mantissa_stream << val;
79    *exponent = 0;
80  }
81  *mantissa = mantissa_stream.str();
82}
83
84std::string ExponentToPrefix(int64_t exponent, bool iec) {
85  if (exponent == 0) return "";
86
87  const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1);
88  if (index >= kUnitsSize) return "";
89
90  const char* array =
91      (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits);
92  if (iec)
93    return array[index] + std::string("i");
94  else
95    return std::string(1, array[index]);
96}
97
98std::string ToBinaryStringFullySpecified(double value, double threshold,
99                                         int precision) {
100  std::string mantissa;
101  int64_t exponent;
102  ToExponentAndMantissa(value, threshold, precision, 1024.0, &mantissa,
103                        &exponent);
104  return mantissa + ExponentToPrefix(exponent, false);
105}
106
107void AppendHumanReadable(int n, std::string* str) {
108  std::stringstream ss;
109  // Round down to the nearest SI prefix.
110  ss << ToBinaryStringFullySpecified(n, 1.0, 0);
111  *str += ss.str();
112}
113
114std::string HumanReadableNumber(double n) {
115  // 1.1 means that figures up to 1.1k should be shown with the next unit down;
116  // this softens edge effects.
117  // 1 means that we should show one decimal place of precision.
118  return ToBinaryStringFullySpecified(n, 1.1, 1);
119}
120
121std::string StringPrintFImp(const char* msg, va_list args) {
122  // we might need a second shot at this, so pre-emptivly make a copy
123  va_list args_cp;
124  va_copy(args_cp, args);
125
126  // TODO(ericwf): use std::array for first attempt to avoid one memory
127  // allocation guess what the size might be
128  std::array<char, 256> local_buff;
129  std::size_t size = local_buff.size();
130  // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation
131  // in the android-ndk
132  auto ret = vsnprintf(local_buff.data(), size, msg, args_cp);
133
134  va_end(args_cp);
135
136  // handle empty expansion
137  if (ret == 0) return std::string{};
138  if (static_cast<std::size_t>(ret) < size)
139    return std::string(local_buff.data());
140
141  // we did not provide a long enough buffer on our first attempt.
142  // add 1 to size to account for null-byte in size cast to prevent overflow
143  size = static_cast<std::size_t>(ret) + 1;
144  auto buff_ptr = std::unique_ptr<char[]>(new char[size]);
145  // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation
146  // in the android-ndk
147  ret = vsnprintf(buff_ptr.get(), size, msg, args);
148  return std::string(buff_ptr.get());
149}
150
151std::string StringPrintF(const char* format, ...) {
152  va_list args;
153  va_start(args, format);
154  std::string tmp = StringPrintFImp(format, args);
155  va_end(args);
156  return tmp;
157}
158
159void ReplaceAll(std::string* str, const std::string& from,
160                const std::string& to) {
161  std::size_t start = 0;
162  while ((start = str->find(from, start)) != std::string::npos) {
163    str->replace(start, from.length(), to);
164    start += to.length();
165  }
166}
167
168}  // end namespace benchmark
169