2 * Copyright 2014 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 #ifndef FOLLY_FORMAT_H_
18 #error This file may only be included from Format.h.
21 #include <folly/Exception.h>
22 #include <folly/Traits.h>
24 // Ignore -Wformat-nonliteral warnings within this file
25 #pragma GCC diagnostic push
26 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
32 extern const char formatHexUpper[256][2];
33 extern const char formatHexLower[256][2];
34 extern const char formatOctal[512][3];
35 extern const char formatBinary[256][8];
37 const size_t kMaxHexLength = 2 * sizeof(uintmax_t);
38 const size_t kMaxOctalLength = 3 * sizeof(uintmax_t);
39 const size_t kMaxBinaryLength = 8 * sizeof(uintmax_t);
42 * Convert an unsigned to hex, using repr (which maps from each possible
43 * 2-hex-bytes value to the 2-character representation).
45 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
46 * the supplied buffer and returns the offset of the beginning of the string
47 * from the start of the buffer. The formatted string will be in range
48 * [buf+begin, buf+bufLen).
51 size_t uintToHex(char* buffer, size_t bufLen, Uint v,
52 const char (&repr)[256][2]) {
53 // 'v >>= 7, v >>= 1' is no more than a work around to get rid of shift size
54 // warning when Uint = uint8_t (it's false as v >= 256 implies sizeof(v) > 1).
55 for (; !less_than<unsigned, 256>(v); v >>= 7, v >>= 1) {
58 buffer[bufLen] = repr[b][0];
59 buffer[bufLen + 1] = repr[b][1];
61 buffer[--bufLen] = repr[v][1];
63 buffer[--bufLen] = repr[v][0];
69 * Convert an unsigned to hex, using lower-case letters for the digits
70 * above 9. See the comments for uintToHex.
73 inline size_t uintToHexLower(char* buffer, size_t bufLen, Uint v) {
74 return uintToHex(buffer, bufLen, v, formatHexLower);
78 * Convert an unsigned to hex, using upper-case letters for the digits
79 * above 9. See the comments for uintToHex.
82 inline size_t uintToHexUpper(char* buffer, size_t bufLen, Uint v) {
83 return uintToHex(buffer, bufLen, v, formatHexUpper);
87 * Convert an unsigned to octal.
89 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
90 * the supplied buffer and returns the offset of the beginning of the string
91 * from the start of the buffer. The formatted string will be in range
92 * [buf+begin, buf+bufLen).
95 size_t uintToOctal(char* buffer, size_t bufLen, Uint v) {
96 auto& repr = formatOctal;
97 // 'v >>= 7, v >>= 2' is no more than a work around to get rid of shift size
98 // warning when Uint = uint8_t (it's false as v >= 512 implies sizeof(v) > 1).
99 for (; !less_than<unsigned, 512>(v); v >>= 7, v >>= 2) {
102 buffer[bufLen] = repr[b][0];
103 buffer[bufLen + 1] = repr[b][1];
104 buffer[bufLen + 2] = repr[b][2];
106 buffer[--bufLen] = repr[v][2];
108 buffer[--bufLen] = repr[v][1];
111 buffer[--bufLen] = repr[v][0];
117 * Convert an unsigned to binary.
119 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
120 * the supplied buffer and returns the offset of the beginning of the string
121 * from the start of the buffer. The formatted string will be in range
122 * [buf+begin, buf+bufLen).
124 template <class Uint>
125 size_t uintToBinary(char* buffer, size_t bufLen, Uint v) {
126 auto& repr = formatBinary;
128 buffer[--bufLen] = '0';
131 for (; v; v >>= 7, v >>= 1) {
134 memcpy(buffer + bufLen, &(repr[b][0]), 8);
136 while (buffer[bufLen] == '0') {
142 } // namespace detail
144 template <class Derived, bool containerMode, class... Args>
145 BaseFormatter<Derived, containerMode, Args...>::BaseFormatter(StringPiece str,
148 values_(FormatValue<typename std::decay<Args>::type>(
149 std::forward<Args>(args))...) {
150 static_assert(!containerMode || sizeof...(Args) == 1,
151 "Exactly one argument required in container mode");
154 template <class Derived, bool containerMode, class... Args>
155 void BaseFormatter<Derived, containerMode, Args...>::handleFormatStrError()
158 LOG(FATAL) << "folly::format: bad format string \"" << str_ << "\": " <<
159 folly::exceptionStr(std::current_exception());
164 template <class Derived, bool containerMode, class... Args>
165 template <class Output>
166 void BaseFormatter<Derived, containerMode, Args...>::operator()(Output& out)
168 // Catch BadFormatArg and range_error exceptions, and call
169 // handleFormatStrError().
171 // These exception types indicate a problem with the format string. Most
172 // format strings are string literals specified by the programmer. If they
173 // have a problem, this is usually a programmer bug. We want to crash to
174 // ensure that these are found early on during development.
176 // BadFormatArg is thrown by the Format.h code, while range_error is thrown
177 // by Conv.h, which is used in several places in our format string
180 // (Note: This behavior is slightly dangerous. If the Output object throws a
181 // BadFormatArg or a range_error, we will also crash the program, even if it
182 // wasn't an issue with the format string. This seems highly unlikely
183 // though, and none of our current Output objects can throw these errors.)
185 // We also throw out_of_range errors if the format string references an
186 // argument that isn't present (or a key that isn't present in one of the
187 // argument containers). However, at the moment we don't crash on these
188 // errors, as it is likely that the container is dynamic at runtime.
191 } catch (const BadFormatArg& ex) {
192 handleFormatStrError();
193 } catch (const std::range_error& ex) {
194 handleFormatStrError();
198 template <class Derived, bool containerMode, class... Args>
199 template <class Output>
200 void BaseFormatter<Derived, containerMode, Args...>::appendOutput(Output& out)
202 auto p = str_.begin();
203 auto end = str_.end();
205 // Copy raw string (without format specifiers) to output;
206 // not as simple as we'd like, as we still need to translate "}}" to "}"
207 // and throw if we see any lone "}"
208 auto outputString = [&out] (StringPiece s) {
212 auto q = static_cast<const char*>(memchr(p, '}', end - p));
214 out(StringPiece(p, end));
218 out(StringPiece(p, q));
221 if (p == end || *p != '}') {
222 throw BadFormatArg("folly::format: single '}' in format string");
229 bool hasDefaultArgIndex = false;
230 bool hasExplicitArgIndex = false;
232 auto q = static_cast<const char*>(memchr(p, '{', end - p));
234 outputString(StringPiece(p, end));
237 outputString(StringPiece(p, q));
241 throw BadFormatArg("folly::format: '}' at end of format string");
246 out(StringPiece(p, 1));
252 q = static_cast<const char*>(memchr(p, '}', end - p));
254 throw BadFormatArg("folly::format: missing ending '}'");
256 FormatArg arg(StringPiece(p, q));
260 auto piece = arg.splitKey<true>(); // empty key component is okay
261 if (containerMode) { // static
263 arg.setNextIntKey(nextArg++);
264 hasDefaultArgIndex = true;
266 arg.setNextKey(piece);
267 hasExplicitArgIndex = true;
271 argIndex = nextArg++;
272 hasDefaultArgIndex = true;
275 argIndex = to<int>(piece);
276 } catch (const std::out_of_range& e) {
277 arg.error("argument index must be integer");
279 arg.enforce(argIndex >= 0, "argument index must be non-negative");
280 hasExplicitArgIndex = true;
284 if (hasDefaultArgIndex && hasExplicitArgIndex) {
286 "folly::format: may not have both default and explicit arg indexes");
289 doFormat(argIndex, arg, out);
293 template <class Derived, bool containerMode, class... Args>
294 void writeTo(FILE* fp,
295 const BaseFormatter<Derived, containerMode, Args...>& formatter) {
296 auto writer = [fp] (StringPiece sp) {
297 ssize_t n = fwrite(sp.data(), 1, sp.size(), fp);
299 throwSystemError("Formatter writeTo", "fwrite failed");
305 namespace format_value {
307 template <class FormatCallback>
308 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb) {
309 if (arg.width != FormatArg::kDefaultWidth && arg.width < 0) {
310 throw BadFormatArg("folly::format: invalid width");
312 if (arg.precision != FormatArg::kDefaultPrecision && arg.precision < 0) {
313 throw BadFormatArg("folly::format: invalid precision");
316 if (arg.precision != FormatArg::kDefaultPrecision &&
317 val.size() > arg.precision) {
318 val.reset(val.data(), arg.precision);
321 constexpr int padBufSize = 128;
322 char padBuf[padBufSize];
324 // Output padding, no more than padBufSize at once
325 auto pad = [&padBuf, &cb, padBufSize] (int chars) {
327 int n = std::min(chars, padBufSize);
328 cb(StringPiece(padBuf, n));
333 int padRemaining = 0;
334 if (arg.width != FormatArg::kDefaultWidth && val.size() < arg.width) {
335 char fill = arg.fill == FormatArg::kDefaultFill ? ' ' : arg.fill;
336 int padChars = static_cast<int> (arg.width - val.size());
337 memset(padBuf, fill, std::min(padBufSize, padChars));
340 case FormatArg::Align::DEFAULT:
341 case FormatArg::Align::LEFT:
342 padRemaining = padChars;
344 case FormatArg::Align::CENTER:
346 padRemaining = padChars - padChars / 2;
348 case FormatArg::Align::RIGHT:
349 case FormatArg::Align::PAD_AFTER_SIGN:
365 template <class FormatCallback>
366 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
367 FormatCallback& cb) {
368 // precision means something different for numbers
369 arg.precision = FormatArg::kDefaultPrecision;
370 if (arg.align == FormatArg::Align::DEFAULT) {
371 arg.align = FormatArg::Align::RIGHT;
372 } else if (prefixLen && arg.align == FormatArg::Align::PAD_AFTER_SIGN) {
373 // Split off the prefix, then do any padding if necessary
374 cb(val.subpiece(0, prefixLen));
375 val.advance(prefixLen);
376 arg.width = std::max(arg.width - prefixLen, 0);
378 format_value::formatString(val, arg, cb);
381 template <class FormatCallback,
385 void formatFormatter(
386 const BaseFormatter<Derived, containerMode, Args...>& formatter,
388 FormatCallback& cb) {
389 if (arg.width == FormatArg::kDefaultWidth &&
390 arg.precision == FormatArg::kDefaultPrecision) {
393 } else if (arg.align != FormatArg::Align::LEFT &&
394 arg.align != FormatArg::Align::DEFAULT) {
395 // We can only avoid creating a temporary string if we align left,
396 // as we'd need to know the size beforehand otherwise
397 format_value::formatString(formatter.fbstr(), arg, cb);
399 auto fn = [&arg, &cb] (StringPiece sp) mutable {
400 int sz = static_cast<int>(sp.size());
401 if (arg.precision != FormatArg::kDefaultPrecision) {
402 sz = std::min(arg.precision, sz);
403 sp.reset(sp.data(), sz);
408 if (arg.width != FormatArg::kDefaultWidth) {
409 arg.width = std::max(arg.width - sz, 0);
414 if (arg.width != FormatArg::kDefaultWidth && arg.width != 0) {
415 // Rely on formatString to do appropriate padding
416 format_value::formatString(StringPiece(), arg, cb);
421 } // namespace format_value
423 // Definitions for default FormatValue classes
425 // Integral types (except bool)
428 T, typename std::enable_if<
429 std::is_integral<T>::value &&
430 !std::is_same<T, bool>::value>::type>
433 explicit FormatValue(T val) : val_(val) { }
434 template <class FormatCallback>
435 void format(FormatArg& arg, FormatCallback& cb) const {
436 arg.validate(FormatArg::Type::INTEGER);
440 template <class FormatCallback>
441 void doFormat(FormatArg& arg, FormatCallback& cb) const {
442 char presentation = arg.presentation;
443 if (presentation == FormatArg::kDefaultPresentation) {
444 presentation = std::is_same<T, char>::value ? 'c' : 'd';
447 // Do all work as unsigned, we'll add the prefix ('0' or '0x' if necessary)
448 // and sign ourselves.
449 typedef typename std::make_unsigned<T>::type UT;
452 if (std::is_signed<T>::value) {
453 if (folly::is_negative(val_)) {
454 uval = static_cast<UT>(-val_);
457 uval = static_cast<UT>(val_);
459 case FormatArg::Sign::PLUS_OR_MINUS:
462 case FormatArg::Sign::SPACE_OR_MINUS:
474 arg.enforce(arg.sign == FormatArg::Sign::DEFAULT,
475 "sign specifications not allowed for unsigned values");
479 // #x: 0x prefix + 16 bytes = 18 bytes
480 // #o: 0 prefix + 22 bytes = 23 bytes
481 // #b: 0b prefix + 64 bytes = 65 bytes
482 // ,d: 26 bytes (including thousands separators!)
484 // + 3 for sign and prefix shenanigans (see below)
485 constexpr size_t valBufSize = 69;
486 char valBuf[valBufSize];
487 char* valBufBegin = nullptr;
488 char* valBufEnd = nullptr;
491 auto useSprintf = [&] (const char* format) mutable {
492 valBufBegin = valBuf + 3; // room for sign and base prefix
493 valBufEnd = valBufBegin + sprintf(valBufBegin, format,
494 static_cast<uintmax_t>(uval));
499 switch (presentation) {
500 case 'n': // TODO(tudorb): locale awareness?
502 arg.enforce(!arg.basePrefix,
503 "base prefix not allowed with '", presentation,
505 if (arg.thousandsSeparator) {
508 // Use uintToBuffer, faster than sprintf
509 valBufBegin = valBuf + 3;
510 valBufEnd = valBufBegin + uint64ToBufferUnsafe(uval, valBufBegin);
514 arg.enforce(!arg.basePrefix,
515 "base prefix not allowed with '", presentation,
517 arg.enforce(!arg.thousandsSeparator,
518 "thousands separator (',') not allowed with '",
519 presentation, "' specifier");
520 valBufBegin = valBuf + 3;
521 *valBufBegin = static_cast<char>(uval);
522 valBufEnd = valBufBegin + 1;
526 arg.enforce(!arg.thousandsSeparator,
527 "thousands separator (',') not allowed with '",
528 presentation, "' specifier");
529 valBufEnd = valBuf + valBufSize - 1;
530 valBufBegin = valBuf + detail::uintToOctal(valBuf, valBufSize - 1, uval);
531 if (arg.basePrefix) {
532 *--valBufBegin = '0';
537 arg.enforce(!arg.thousandsSeparator,
538 "thousands separator (',') not allowed with '",
539 presentation, "' specifier");
540 valBufEnd = valBuf + valBufSize - 1;
541 valBufBegin = valBuf + detail::uintToHexLower(valBuf, valBufSize - 1,
543 if (arg.basePrefix) {
544 *--valBufBegin = 'x';
545 *--valBufBegin = '0';
550 arg.enforce(!arg.thousandsSeparator,
551 "thousands separator (',') not allowed with '",
552 presentation, "' specifier");
553 valBufEnd = valBuf + valBufSize - 1;
554 valBufBegin = valBuf + detail::uintToHexUpper(valBuf, valBufSize - 1,
556 if (arg.basePrefix) {
557 *--valBufBegin = 'X';
558 *--valBufBegin = '0';
564 arg.enforce(!arg.thousandsSeparator,
565 "thousands separator (',') not allowed with '",
566 presentation, "' specifier");
567 valBufEnd = valBuf + valBufSize - 1;
568 valBufBegin = valBuf + detail::uintToBinary(valBuf, valBufSize - 1,
570 if (arg.basePrefix) {
571 *--valBufBegin = presentation; // 0b or 0B
572 *--valBufBegin = '0';
577 arg.error("invalid specifier '", presentation, "'");
581 *--valBufBegin = sign;
585 format_value::formatNumber(StringPiece(valBufBegin, valBufEnd), prefixLen,
595 class FormatValue<bool> {
597 explicit FormatValue(bool val) : val_(val) { }
599 template <class FormatCallback>
600 void format(FormatArg& arg, FormatCallback& cb) const {
601 if (arg.presentation == FormatArg::kDefaultPresentation) {
602 arg.validate(FormatArg::Type::OTHER);
603 format_value::formatString(val_ ? "true" : "false", arg, cb);
605 FormatValue<int>(val_).format(arg, cb);
615 class FormatValue<double> {
617 explicit FormatValue(double val) : val_(val) { }
619 template <class FormatCallback>
620 void format(FormatArg& arg, FormatCallback& cb) const {
621 using ::double_conversion::DoubleToStringConverter;
622 using ::double_conversion::StringBuilder;
624 arg.validate(FormatArg::Type::FLOAT);
626 if (arg.presentation == FormatArg::kDefaultPresentation) {
627 arg.presentation = 'g';
630 const char* infinitySymbol = isupper(arg.presentation) ? "INF" : "inf";
631 const char* nanSymbol = isupper(arg.presentation) ? "NAN" : "nan";
632 char exponentSymbol = isupper(arg.presentation) ? 'E' : 'e';
634 if (arg.precision == FormatArg::kDefaultPrecision) {
638 // 2+: for null terminator and optional sign shenanigans.
639 char buf[2 + std::max({
640 (2 + DoubleToStringConverter::kMaxFixedDigitsBeforePoint +
641 DoubleToStringConverter::kMaxFixedDigitsAfterPoint),
642 (8 + DoubleToStringConverter::kMaxExponentialDigits),
643 (7 + DoubleToStringConverter::kMaxPrecisionDigits)})];
644 StringBuilder builder(buf + 1, static_cast<int> (sizeof(buf) - 1));
648 case FormatArg::Sign::PLUS_OR_MINUS:
651 case FormatArg::Sign::SPACE_OR_MINUS:
660 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN |
661 (arg.trailingDot ? DoubleToStringConverter::EMIT_TRAILING_DECIMAL_POINT
665 switch (arg.presentation) {
672 DoubleToStringConverter::kMaxFixedDigitsAfterPoint) {
673 arg.precision = DoubleToStringConverter::kMaxFixedDigitsAfterPoint;
675 DoubleToStringConverter conv(flags,
683 arg.enforce(conv.ToFixed(val, arg.precision, &builder),
684 "fixed double conversion failed");
690 if (arg.precision > DoubleToStringConverter::kMaxExponentialDigits) {
691 arg.precision = DoubleToStringConverter::kMaxExponentialDigits;
694 DoubleToStringConverter conv(flags,
702 arg.enforce(conv.ToExponential(val, arg.precision, &builder));
705 case 'n': // should be locale-aware, but isn't
709 if (arg.precision < DoubleToStringConverter::kMinPrecisionDigits) {
710 arg.precision = DoubleToStringConverter::kMinPrecisionDigits;
711 } else if (arg.precision >
712 DoubleToStringConverter::kMaxPrecisionDigits) {
713 arg.precision = DoubleToStringConverter::kMaxPrecisionDigits;
715 DoubleToStringConverter conv(flags,
723 arg.enforce(conv.ToShortest(val, &builder));
727 arg.error("invalid specifier '", arg.presentation, "'");
730 int len = builder.position();
734 // Add '+' or ' ' sign if needed
736 // anything that's neither negative nor nan
738 if (plusSign && (*p != '-' && *p != 'n' && *p != 'N')) {
742 } else if (*p == '-') {
746 format_value::formatNumber(StringPiece(p, len), prefixLen, arg, cb);
753 // float (defer to double)
755 class FormatValue<float> {
757 explicit FormatValue(float val) : val_(val) { }
759 template <class FormatCallback>
760 void format(FormatArg& arg, FormatCallback& cb) const {
761 FormatValue<double>(val_).format(arg, cb);
768 // Sring-y types (implicitly convertible to StringPiece, except char*)
771 T, typename std::enable_if<
772 (!std::is_pointer<T>::value ||
773 !std::is_same<char, typename std::decay<
774 typename std::remove_pointer<T>::type>::type>::value) &&
775 std::is_convertible<T, StringPiece>::value>::type>
778 explicit FormatValue(StringPiece val) : val_(val) { }
780 template <class FormatCallback>
781 void format(FormatArg& arg, FormatCallback& cb) const {
782 if (arg.keyEmpty()) {
783 arg.validate(FormatArg::Type::OTHER);
784 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation ||
785 arg.presentation == 's',
786 "invalid specifier '", arg.presentation, "'");
787 format_value::formatString(val_, arg, cb);
789 FormatValue<char>(val_.at(arg.splitIntKey())).format(arg, cb);
799 class FormatValue<std::nullptr_t> {
801 explicit FormatValue(std::nullptr_t) { }
803 template <class FormatCallback>
804 void format(FormatArg& arg, FormatCallback& cb) const {
805 arg.validate(FormatArg::Type::OTHER);
806 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
807 "invalid specifier '", arg.presentation, "'");
808 format_value::formatString("(null)", arg, cb);
812 // Partial specialization of FormatValue for char*
816 typename std::enable_if<
817 std::is_same<char, typename std::decay<T>::type>::value>::type>
820 explicit FormatValue(T* val) : val_(val) { }
822 template <class FormatCallback>
823 void format(FormatArg& arg, FormatCallback& cb) const {
824 if (arg.keyEmpty()) {
826 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
828 FormatValue<StringPiece>(val_).format(arg, cb);
831 FormatValue<typename std::decay<T>::type>(
832 val_[arg.splitIntKey()]).format(arg, cb);
840 // Partial specialization of FormatValue for void*
844 typename std::enable_if<
845 std::is_same<void, typename std::decay<T>::type>::value>::type>
848 explicit FormatValue(T* val) : val_(val) { }
850 template <class FormatCallback>
851 void format(FormatArg& arg, FormatCallback& cb) const {
853 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
855 // Print as a pointer, in hex.
856 arg.validate(FormatArg::Type::OTHER);
857 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
858 "invalid specifier '", arg.presentation, "'");
859 arg.basePrefix = true;
860 arg.presentation = 'x';
861 if (arg.align == FormatArg::Align::DEFAULT) {
862 arg.align = FormatArg::Align::LEFT;
864 FormatValue<uintptr_t>(
865 reinterpret_cast<uintptr_t>(val_)).doFormat(arg, cb);
873 template <class T, class = void>
874 class TryFormatValue {
876 template <class FormatCallback>
877 static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
878 arg.error("No formatter available for this type");
883 class TryFormatValue<
885 typename std::enable_if<
886 0 < sizeof(FormatValue<typename std::decay<T>::type>)>::type>
889 template <class FormatCallback>
890 static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
891 FormatValue<typename std::decay<T>::type>(value).format(arg, cb);
895 // Partial specialization of FormatValue for other pointers
899 typename std::enable_if<
900 !std::is_same<char, typename std::decay<T>::type>::value &&
901 !std::is_same<void, typename std::decay<T>::type>::value>::type>
904 explicit FormatValue(T* val) : val_(val) { }
906 template <class FormatCallback>
907 void format(FormatArg& arg, FormatCallback& cb) const {
908 if (arg.keyEmpty()) {
909 FormatValue<void*>((void*)val_).format(arg, cb);
911 TryFormatValue<T>::formatOrFail(val_[arg.splitIntKey()], arg, cb);
920 // Shortcut, so we don't have to use enable_if everywhere
921 struct FormatTraitsBase {
922 typedef void enabled;
925 // Traits that define enabled, value_type, and at() for anything
926 // indexable with integral keys: pointers, arrays, vectors, and maps
927 // with integral keys
928 template <class T, class Enable=void> struct IndexableTraits;
930 // Base class for sequences (vectors, deques)
932 struct IndexableTraitsSeq : public FormatTraitsBase {
933 typedef C container_type;
934 typedef typename C::value_type value_type;
935 static const value_type& at(const C& c, int idx) {
939 static const value_type& at(const C& c, int idx,
940 const value_type& dflt) {
941 return (idx >= 0 && idx < c.size()) ? c.at(idx) : dflt;
945 // Base class for associative types (maps)
947 struct IndexableTraitsAssoc : public FormatTraitsBase {
948 typedef typename C::value_type::second_type value_type;
949 static const value_type& at(const C& c, int idx) {
950 return c.at(static_cast<typename C::key_type>(idx));
952 static const value_type& at(const C& c, int idx,
953 const value_type& dflt) {
954 auto pos = c.find(static_cast<typename C::key_type>(idx));
955 return pos != c.end() ? pos->second : dflt;
960 template <class T, size_t N>
961 struct IndexableTraits<std::array<T, N>>
962 : public IndexableTraitsSeq<std::array<T, N>> {
966 template <class T, class A>
967 struct IndexableTraits<std::vector<T, A>>
968 : public IndexableTraitsSeq<std::vector<T, A>> {
972 template <class T, class A>
973 struct IndexableTraits<std::deque<T, A>>
974 : public IndexableTraitsSeq<std::deque<T, A>> {
978 template <class T, class A>
979 struct IndexableTraits<fbvector<T, A>>
980 : public IndexableTraitsSeq<fbvector<T, A>> {
984 template <class T, size_t M, class A, class B, class C>
985 struct IndexableTraits<small_vector<T, M, A, B, C>>
986 : public IndexableTraitsSeq<small_vector<T, M, A, B, C>> {
989 // std::map with integral keys
990 template <class K, class T, class C, class A>
991 struct IndexableTraits<
992 std::map<K, T, C, A>,
993 typename std::enable_if<std::is_integral<K>::value>::type>
994 : public IndexableTraitsAssoc<std::map<K, T, C, A>> {
997 // std::unordered_map with integral keys
998 template <class K, class T, class H, class E, class A>
999 struct IndexableTraits<
1000 std::unordered_map<K, T, H, E, A>,
1001 typename std::enable_if<std::is_integral<K>::value>::type>
1002 : public IndexableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
1005 } // namespace detail
1007 // Partial specialization of FormatValue for integer-indexable containers
1011 typename detail::IndexableTraits<T>::enabled> {
1013 explicit FormatValue(const T& val) : val_(val) { }
1015 template <class FormatCallback>
1016 void format(FormatArg& arg, FormatCallback& cb) const {
1017 FormatValue<typename std::decay<
1018 typename detail::IndexableTraits<T>::value_type>::type>(
1019 detail::IndexableTraits<T>::at(
1020 val_, arg.splitIntKey())).format(arg, cb);
1027 template <class Container, class Value>
1029 detail::DefaultValueWrapper<Container, Value>,
1030 typename detail::IndexableTraits<Container>::enabled> {
1032 explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
1035 template <class FormatCallback>
1036 void format(FormatArg& arg, FormatCallback& cb) const {
1037 FormatValue<typename std::decay<
1038 typename detail::IndexableTraits<Container>::value_type>::type>(
1039 detail::IndexableTraits<Container>::at(
1042 val_.defaultValue)).format(arg, cb);
1046 const detail::DefaultValueWrapper<Container, Value>& val_;
1051 // Define enabled, key_type, convert from StringPiece to the key types
1053 template <class T> struct KeyFromStringPiece;
1057 struct KeyFromStringPiece<std::string> : public FormatTraitsBase {
1058 typedef std::string key_type;
1059 static std::string convert(StringPiece s) {
1060 return s.toString();
1062 typedef void enabled;
1067 struct KeyFromStringPiece<fbstring> : public FormatTraitsBase {
1068 typedef fbstring key_type;
1069 static fbstring convert(StringPiece s) {
1070 return s.toFbstring();
1076 struct KeyFromStringPiece<StringPiece> : public FormatTraitsBase {
1077 typedef StringPiece key_type;
1078 static StringPiece convert(StringPiece s) {
1083 // Base class for associative types keyed by strings
1084 template <class T> struct KeyableTraitsAssoc : public FormatTraitsBase {
1085 typedef typename T::key_type key_type;
1086 typedef typename T::value_type::second_type value_type;
1087 static const value_type& at(const T& map, StringPiece key) {
1088 return map.at(KeyFromStringPiece<key_type>::convert(key));
1090 static const value_type& at(const T& map, StringPiece key,
1091 const value_type& dflt) {
1092 auto pos = map.find(KeyFromStringPiece<key_type>::convert(key));
1093 return pos != map.end() ? pos->second : dflt;
1097 // Define enabled, key_type, value_type, at() for supported string-keyed
1099 template <class T, class Enabled=void> struct KeyableTraits;
1101 // std::map with string key
1102 template <class K, class T, class C, class A>
1103 struct KeyableTraits<
1104 std::map<K, T, C, A>,
1105 typename KeyFromStringPiece<K>::enabled>
1106 : public KeyableTraitsAssoc<std::map<K, T, C, A>> {
1109 // std::unordered_map with string key
1110 template <class K, class T, class H, class E, class A>
1111 struct KeyableTraits<
1112 std::unordered_map<K, T, H, E, A>,
1113 typename KeyFromStringPiece<K>::enabled>
1114 : public KeyableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
1117 } // namespace detail
1119 // Partial specialization of FormatValue for string-keyed containers
1123 typename detail::KeyableTraits<T>::enabled> {
1125 explicit FormatValue(const T& val) : val_(val) { }
1127 template <class FormatCallback>
1128 void format(FormatArg& arg, FormatCallback& cb) const {
1129 FormatValue<typename std::decay<
1130 typename detail::KeyableTraits<T>::value_type>::type>(
1131 detail::KeyableTraits<T>::at(
1132 val_, arg.splitKey())).format(arg, cb);
1139 template <class Container, class Value>
1141 detail::DefaultValueWrapper<Container, Value>,
1142 typename detail::KeyableTraits<Container>::enabled> {
1144 explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
1147 template <class FormatCallback>
1148 void format(FormatArg& arg, FormatCallback& cb) const {
1149 FormatValue<typename std::decay<
1150 typename detail::KeyableTraits<Container>::value_type>::type>(
1151 detail::KeyableTraits<Container>::at(
1154 val_.defaultValue)).format(arg, cb);
1158 const detail::DefaultValueWrapper<Container, Value>& val_;
1161 // Partial specialization of FormatValue for pairs
1162 template <class A, class B>
1163 class FormatValue<std::pair<A, B>> {
1165 explicit FormatValue(const std::pair<A, B>& val) : val_(val) { }
1167 template <class FormatCallback>
1168 void format(FormatArg& arg, FormatCallback& cb) const {
1169 int key = arg.splitIntKey();
1172 FormatValue<typename std::decay<A>::type>(val_.first).format(arg, cb);
1175 FormatValue<typename std::decay<B>::type>(val_.second).format(arg, cb);
1178 arg.error("invalid index for pair");
1183 const std::pair<A, B>& val_;
1186 // Partial specialization of FormatValue for tuples
1187 template <class... Args>
1188 class FormatValue<std::tuple<Args...>> {
1189 typedef std::tuple<Args...> Tuple;
1191 explicit FormatValue(const Tuple& val) : val_(val) { }
1193 template <class FormatCallback>
1194 void format(FormatArg& arg, FormatCallback& cb) const {
1195 int key = arg.splitIntKey();
1196 arg.enforce(key >= 0, "tuple index must be non-negative");
1197 doFormat(key, arg, cb);
1201 static constexpr size_t valueCount = std::tuple_size<Tuple>::value;
1203 template <size_t K, class Callback>
1204 typename std::enable_if<K == valueCount>::type
1205 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1206 arg.enforce("tuple index out of range, max=", i);
1209 template <size_t K, class Callback>
1210 typename std::enable_if<(K < valueCount)>::type
1211 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1213 FormatValue<typename std::decay<
1214 typename std::tuple_element<K, Tuple>::type>::type>(
1215 std::get<K>(val_)).format(arg, cb);
1217 doFormatFrom<K+1>(i, arg, cb);
1221 template <class Callback>
1222 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
1223 return doFormatFrom<0>(i, arg, cb);
1229 // Partial specialization of FormatValue for nested Formatters
1230 template <bool containerMode, class... Args,
1231 template <bool, class...> class F>
1232 class FormatValue<F<containerMode, Args...>,
1233 typename std::enable_if<detail::IsFormatter<
1234 F<containerMode, Args...>>::value>::type> {
1235 typedef typename F<containerMode, Args...>::BaseType FormatterValue;
1238 explicit FormatValue(const FormatterValue& f) : f_(f) { }
1240 template <class FormatCallback>
1241 void format(FormatArg& arg, FormatCallback& cb) const {
1242 format_value::formatFormatter(f_, arg, cb);
1245 const FormatterValue& f_;
1249 * Formatter objects can be appended to strings, and therefore they're
1250 * compatible with folly::toAppend and folly::to.
1252 template <class Tgt, class Derived, bool containerMode, class... Args>
1253 typename std::enable_if<IsSomeString<Tgt>::value>::type toAppend(
1254 const BaseFormatter<Derived, containerMode, Args...>& value, Tgt* result) {
1255 value.appendTo(*result);
1258 } // namespace folly
1260 #pragma GCC diagnostic pop