2 * Copyright 2016 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 <folly/portability/Constexpr.h>
21 #include <double-conversion/double-conversion.h>
26 extern const FormatArg::Align formatAlignTable[];
27 extern const FormatArg::Sign formatSignTable[];
31 using namespace folly::detail;
33 void FormatValue<double>::formatHelper(
34 fbstring& piece, int& prefixLen, FormatArg& arg) const {
35 using ::double_conversion::DoubleToStringConverter;
36 using ::double_conversion::StringBuilder;
38 arg.validate(FormatArg::Type::FLOAT);
40 if (arg.presentation == FormatArg::kDefaultPresentation) {
41 arg.presentation = 'g';
44 const char* infinitySymbol = isupper(arg.presentation) ? "INF" : "inf";
45 const char* nanSymbol = isupper(arg.presentation) ? "NAN" : "nan";
46 char exponentSymbol = isupper(arg.presentation) ? 'E' : 'e';
48 if (arg.precision == FormatArg::kDefaultPrecision) {
52 // 2+: for null terminator and optional sign shenanigans.
53 constexpr size_t bufLen =
55 2 + DoubleToStringConverter::kMaxFixedDigitsBeforePoint +
56 DoubleToStringConverter::kMaxFixedDigitsAfterPoint,
57 constexpr_max(8 + DoubleToStringConverter::kMaxExponentialDigits,
58 7 + DoubleToStringConverter::kMaxPrecisionDigits));
60 StringBuilder builder(buf + 1, static_cast<int> (sizeof(buf) - 1));
64 case FormatArg::Sign::PLUS_OR_MINUS:
67 case FormatArg::Sign::SPACE_OR_MINUS:
76 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN |
77 (arg.trailingDot ? DoubleToStringConverter::EMIT_TRAILING_DECIMAL_POINT
81 switch (arg.presentation) {
88 DoubleToStringConverter::kMaxFixedDigitsAfterPoint) {
89 arg.precision = DoubleToStringConverter::kMaxFixedDigitsAfterPoint;
91 DoubleToStringConverter conv(flags,
99 arg.enforce(conv.ToFixed(val, arg.precision, &builder),
100 "fixed double conversion failed");
106 if (arg.precision > DoubleToStringConverter::kMaxExponentialDigits) {
107 arg.precision = DoubleToStringConverter::kMaxExponentialDigits;
110 DoubleToStringConverter conv(flags,
118 arg.enforce(conv.ToExponential(val, arg.precision, &builder));
121 case 'n': // should be locale-aware, but isn't
125 if (arg.precision < DoubleToStringConverter::kMinPrecisionDigits) {
126 arg.precision = DoubleToStringConverter::kMinPrecisionDigits;
127 } else if (arg.precision >
128 DoubleToStringConverter::kMaxPrecisionDigits) {
129 arg.precision = DoubleToStringConverter::kMaxPrecisionDigits;
131 DoubleToStringConverter conv(flags,
139 arg.enforce(conv.ToShortest(val, &builder));
143 arg.error("invalid specifier '", arg.presentation, "'");
146 int len = builder.position();
150 // Add '+' or ' ' sign if needed
152 // anything that's neither negative nor nan
154 if (plusSign && (*p != '-' && *p != 'n' && *p != 'N')) {
158 } else if (*p == '-') {
162 piece = fbstring(p, len);
166 void FormatArg::initSlow() {
167 auto b = fullArgString.begin();
168 auto end = fullArgString.end();
171 auto p = static_cast<const char*>(memchr(b, ':', end - b));
173 key_ = StringPiece(b, end);
176 key_ = StringPiece(b, p);
180 if (++p == end) return;
182 // fill/align, or just align
185 (a = formatAlignTable[static_cast<unsigned char>(p[1])]) !=
190 if (p == end) return;
191 } else if ((a = formatAlignTable[static_cast<unsigned char>(*p)]) !=
194 if (++p == end) return;
198 unsigned char uSign = static_cast<unsigned char>(*p);
199 if ((s = formatSignTable[uSign]) != Sign::INVALID) {
201 if (++p == end) return;
206 if (++p == end) return;
210 enforce(align == Align::DEFAULT, "alignment specified twice");
212 align = Align::PAD_AFTER_SIGN;
213 if (++p == end) return;
220 } while (p != end && *p >= '0' && *p <= '9');
221 return to<int>(StringPiece(c, p));
225 width = kDynamicWidth;
228 if (p == end) return;
230 if (*p >= '0' && *p <= '9') widthIndex = readInt();
232 if (p == end) return;
233 } else if (*p >= '0' && *p <= '9') {
236 if (p == end) return;
240 thousandsSeparator = true;
241 if (++p == end) return;
246 while (p != end && *p >= '0' && *p <= '9') {
250 precision = to<int>(StringPiece(d, p));
251 if (p != end && *p == '.') {
259 if (p == end) return;
263 if (++p == end) return;
266 error("extra characters in format string");
269 void FormatArg::validate(Type type) const {
270 enforce(keyEmpty(), "index not allowed");
273 enforce(precision == kDefaultPrecision,
274 "precision not allowed on integers");
278 "base prefix ('#') specifier only allowed on integers");
279 enforce(!thousandsSeparator,
280 "thousands separator (',') only allowed on integers");
283 enforce(align != Align::PAD_AFTER_SIGN,
284 "'='alignment only allowed on numbers");
285 enforce(sign == Sign::DEFAULT,
286 "sign specifier only allowed on numbers");
288 "base prefix ('#') specifier only allowed on integers");
289 enforce(!thousandsSeparator,
290 "thousands separator (',') only allowed on integers");
296 void insertThousandsGroupingUnsafe(char* start_buffer, char** end_buffer) {
297 uint32_t remaining_digits = *end_buffer - start_buffer;
298 uint32_t separator_size = (remaining_digits - 1) / 3;
299 uint32_t result_size = remaining_digits + separator_size;
300 *end_buffer = *end_buffer + separator_size;
302 // get the end of the new string with the separators
303 uint32_t buffer_write_index = result_size - 1;
304 uint32_t buffer_read_index = remaining_digits - 1;
305 start_buffer[buffer_write_index + 1] = 0;
308 uint32_t next_group_size = 3;
311 uint32_t current_group_size = std::max<uint32_t>(1,
312 std::min<uint32_t>(remaining_digits, next_group_size));
314 // write out the current group's digits to the buffer index
315 for (uint32_t i = 0; i < current_group_size; i++) {
316 start_buffer[buffer_write_index--] = start_buffer[buffer_read_index--];
319 // if not finished, write the separator before the next group
320 if (buffer_write_index < buffer_write_index + 1) {
321 start_buffer[buffer_write_index--] = ',';
326 remaining_digits -= current_group_size;