2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/Format.h>
19 #include <double-conversion/double-conversion.h>
24 extern const FormatArg::Align formatAlignTable[];
25 extern const FormatArg::Sign formatSignTable[];
29 using namespace folly::detail;
31 void FormatValue<double>::formatHelper(
32 fbstring& piece, int& prefixLen, FormatArg& arg) const {
33 using ::double_conversion::DoubleToStringConverter;
34 using ::double_conversion::StringBuilder;
36 arg.validate(FormatArg::Type::FLOAT);
38 if (arg.presentation == FormatArg::kDefaultPresentation) {
39 arg.presentation = 'g';
42 const char* infinitySymbol = isupper(arg.presentation) ? "INF" : "inf";
43 const char* nanSymbol = isupper(arg.presentation) ? "NAN" : "nan";
44 char exponentSymbol = isupper(arg.presentation) ? 'E' : 'e';
46 if (arg.precision == FormatArg::kDefaultPrecision) {
50 // 2+: for null terminator and optional sign shenanigans.
51 char buf[2 + std::max(
52 2 + DoubleToStringConverter::kMaxFixedDigitsBeforePoint +
53 DoubleToStringConverter::kMaxFixedDigitsAfterPoint,
54 std::max(8 + DoubleToStringConverter::kMaxExponentialDigits,
55 7 + DoubleToStringConverter::kMaxPrecisionDigits))];
56 StringBuilder builder(buf + 1, static_cast<int> (sizeof(buf) - 1));
60 case FormatArg::Sign::PLUS_OR_MINUS:
63 case FormatArg::Sign::SPACE_OR_MINUS:
72 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN |
73 (arg.trailingDot ? DoubleToStringConverter::EMIT_TRAILING_DECIMAL_POINT
77 switch (arg.presentation) {
84 DoubleToStringConverter::kMaxFixedDigitsAfterPoint) {
85 arg.precision = DoubleToStringConverter::kMaxFixedDigitsAfterPoint;
87 DoubleToStringConverter conv(flags,
95 arg.enforce(conv.ToFixed(val, arg.precision, &builder),
96 "fixed double conversion failed");
102 if (arg.precision > DoubleToStringConverter::kMaxExponentialDigits) {
103 arg.precision = DoubleToStringConverter::kMaxExponentialDigits;
106 DoubleToStringConverter conv(flags,
114 arg.enforce(conv.ToExponential(val, arg.precision, &builder));
117 case 'n': // should be locale-aware, but isn't
121 if (arg.precision < DoubleToStringConverter::kMinPrecisionDigits) {
122 arg.precision = DoubleToStringConverter::kMinPrecisionDigits;
123 } else if (arg.precision >
124 DoubleToStringConverter::kMaxPrecisionDigits) {
125 arg.precision = DoubleToStringConverter::kMaxPrecisionDigits;
127 DoubleToStringConverter conv(flags,
135 arg.enforce(conv.ToShortest(val, &builder));
139 arg.error("invalid specifier '", arg.presentation, "'");
142 int len = builder.position();
146 // Add '+' or ' ' sign if needed
148 // anything that's neither negative nor nan
150 if (plusSign && (*p != '-' && *p != 'n' && *p != 'N')) {
154 } else if (*p == '-') {
158 piece = fbstring(p, len);
162 void FormatArg::initSlow() {
163 auto b = fullArgString.begin();
164 auto end = fullArgString.end();
167 auto p = static_cast<const char*>(memchr(b, ':', end - b));
169 key_ = StringPiece(b, end);
172 key_ = StringPiece(b, p);
176 if (++p == end) return;
178 // fill/align, or just align
181 (a = formatAlignTable[static_cast<unsigned char>(p[1])]) !=
186 if (p == end) return;
187 } else if ((a = formatAlignTable[static_cast<unsigned char>(*p)]) !=
190 if (++p == end) return;
194 unsigned char uSign = static_cast<unsigned char>(*p);
195 if ((s = formatSignTable[uSign]) != Sign::INVALID) {
197 if (++p == end) return;
202 if (++p == end) return;
206 enforce(align == Align::DEFAULT, "alignment specified twice");
208 align = Align::PAD_AFTER_SIGN;
209 if (++p == end) return;
216 } while (p != end && *p >= '0' && *p <= '9');
217 return to<int>(StringPiece(b, p));
221 width = kDynamicWidth;
224 if (p == end) return;
226 if (*p >= '0' && *p <= '9') widthIndex = readInt();
228 if (p == end) return;
229 } else if (*p >= '0' && *p <= '9') {
232 if (p == end) return;
236 thousandsSeparator = true;
237 if (++p == end) return;
242 while (p != end && *p >= '0' && *p <= '9') {
246 precision = to<int>(StringPiece(b, p));
247 if (p != end && *p == '.') {
255 if (p == end) return;
259 if (++p == end) return;
262 error("extra characters in format string");
265 void FormatArg::validate(Type type) const {
266 enforce(keyEmpty(), "index not allowed");
269 enforce(precision == kDefaultPrecision,
270 "precision not allowed on integers");
274 "base prefix ('#') specifier only allowed on integers");
275 enforce(!thousandsSeparator,
276 "thousands separator (',') only allowed on integers");
279 enforce(align != Align::PAD_AFTER_SIGN,
280 "'='alignment only allowed on numbers");
281 enforce(sign == Sign::DEFAULT,
282 "sign specifier only allowed on numbers");
284 "base prefix ('#') specifier only allowed on integers");
285 enforce(!thousandsSeparator,
286 "thousands separator (',') only allowed on integers");
292 void insertThousandsGroupingUnsafe(char* start_buffer, char** end_buffer) {
293 uint32_t remaining_digits = *end_buffer - start_buffer;
294 uint32_t separator_size = (remaining_digits - 1) / 3;
295 uint32_t result_size = remaining_digits + separator_size;
296 *end_buffer = *end_buffer + separator_size;
298 // get the end of the new string with the separators
299 uint32_t buffer_write_index = result_size - 1;
300 uint32_t buffer_read_index = remaining_digits - 1;
301 start_buffer[buffer_write_index + 1] = 0;
304 uint32_t next_group_size = 3;
307 uint32_t current_group_size = std::max<uint32_t>(1,
308 std::min<uint32_t>(remaining_digits, next_group_size));
310 // write out the current group's digits to the buffer index
311 for (uint32_t i = 0; i < current_group_size; i++) {
312 start_buffer[buffer_write_index--] = start_buffer[buffer_read_index--];
315 // if not finished, write the separator before the next group
316 if (buffer_write_index < buffer_write_index + 1) {
317 start_buffer[buffer_write_index--] = ',';
322 remaining_digits -= current_group_size;