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
145 template <bool containerMode, class... Args>
146 Formatter<containerMode, Args...>::Formatter(StringPiece str, Args&&... args)
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 <bool containerMode, class... Args>
155 void Formatter<containerMode, Args...>::handleFormatStrError() const {
157 LOG(FATAL) << "folly::format: bad format string \"" << str_ << "\": " <<
158 folly::exceptionStr(std::current_exception());
163 template <bool containerMode, class... Args>
164 template <class Output>
165 void Formatter<containerMode, Args...>::operator()(Output& out) const {
166 // Catch BadFormatArg and range_error exceptions, and call
167 // handleFormatStrError().
169 // These exception types indicate a problem with the format string. Most
170 // format strings are string literals specified by the programmer. If they
171 // have a problem, this is usually a programmer bug. We want to crash to
172 // ensure that these are found early on during development.
174 // BadFormatArg is thrown by the Format.h code, while range_error is thrown
175 // by Conv.h, which is used in several places in our format string
178 // (Note: This behavior is slightly dangerous. If the Output object throws a
179 // BadFormatArg or a range_error, we will also crash the program, even if it
180 // wasn't an issue with the format string. This seems highly unlikely
181 // though, and none of our current Output objects can throw these errors.)
183 // We also throw out_of_range errors if the format string references an
184 // argument that isn't present (or a key that isn't present in one of the
185 // argument containers). However, at the moment we don't crash on these
186 // errors, as it is likely that the container is dynamic at runtime.
189 } catch (const BadFormatArg& ex) {
190 handleFormatStrError();
191 } catch (const std::range_error& ex) {
192 handleFormatStrError();
196 template <bool containerMode, class... Args>
197 template <class Output>
198 void Formatter<containerMode, Args...>::appendOutput(Output& out) const {
199 auto p = str_.begin();
200 auto end = str_.end();
202 // Copy raw string (without format specifiers) to output;
203 // not as simple as we'd like, as we still need to translate "}}" to "}"
204 // and throw if we see any lone "}"
205 auto outputString = [&out] (StringPiece s) {
209 auto q = static_cast<const char*>(memchr(p, '}', end - p));
211 out(StringPiece(p, end));
215 out(StringPiece(p, q));
218 if (p == end || *p != '}') {
219 throw BadFormatArg("folly::format: single '}' in format string");
226 bool hasDefaultArgIndex = false;
227 bool hasExplicitArgIndex = false;
229 auto q = static_cast<const char*>(memchr(p, '{', end - p));
231 outputString(StringPiece(p, end));
234 outputString(StringPiece(p, q));
238 throw BadFormatArg("folly::format: '}' at end of format string");
243 out(StringPiece(p, 1));
249 q = static_cast<const char*>(memchr(p, '}', end - p));
251 throw BadFormatArg("folly::format: missing ending '}'");
253 FormatArg arg(StringPiece(p, q));
257 auto piece = arg.splitKey<true>(); // empty key component is okay
258 if (containerMode) { // static
260 arg.setNextIntKey(nextArg++);
261 hasDefaultArgIndex = true;
263 arg.setNextKey(piece);
264 hasExplicitArgIndex = true;
268 argIndex = nextArg++;
269 hasDefaultArgIndex = true;
272 argIndex = to<int>(piece);
273 } catch (const std::out_of_range& e) {
274 arg.error("argument index must be integer");
276 arg.enforce(argIndex >= 0, "argument index must be non-negative");
277 hasExplicitArgIndex = true;
281 if (hasDefaultArgIndex && hasExplicitArgIndex) {
283 "folly::format: may not have both default and explicit arg indexes");
286 doFormat(argIndex, arg, out);
290 template <bool containerMode, class... Args>
291 void writeTo(FILE* fp, const Formatter<containerMode, Args...>& formatter) {
292 auto writer = [fp] (StringPiece sp) {
293 ssize_t n = fwrite(sp.data(), 1, sp.size(), fp);
295 throwSystemError("Formatter writeTo", "fwrite failed");
301 namespace format_value {
303 template <class FormatCallback>
304 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb) {
305 if (arg.precision != FormatArg::kDefaultPrecision &&
306 val.size() > arg.precision) {
307 val.reset(val.data(), arg.precision);
310 constexpr int padBufSize = 128;
311 char padBuf[padBufSize];
313 // Output padding, no more than padBufSize at once
314 auto pad = [&padBuf, &cb, padBufSize] (int chars) {
316 int n = std::min(chars, padBufSize);
317 cb(StringPiece(padBuf, n));
322 int padRemaining = 0;
323 if (arg.width != FormatArg::kDefaultWidth && val.size() < arg.width) {
324 char fill = arg.fill == FormatArg::kDefaultFill ? ' ' : arg.fill;
325 int padChars = arg.width - val.size();
326 memset(padBuf, fill, std::min(padBufSize, padChars));
329 case FormatArg::Align::DEFAULT:
330 case FormatArg::Align::LEFT:
331 padRemaining = padChars;
333 case FormatArg::Align::CENTER:
335 padRemaining = padChars - padChars / 2;
337 case FormatArg::Align::RIGHT:
338 case FormatArg::Align::PAD_AFTER_SIGN:
354 template <class FormatCallback>
355 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
356 FormatCallback& cb) {
357 // precision means something different for numbers
358 arg.precision = FormatArg::kDefaultPrecision;
359 if (arg.align == FormatArg::Align::DEFAULT) {
360 arg.align = FormatArg::Align::RIGHT;
361 } else if (prefixLen && arg.align == FormatArg::Align::PAD_AFTER_SIGN) {
362 // Split off the prefix, then do any padding if necessary
363 cb(val.subpiece(0, prefixLen));
364 val.advance(prefixLen);
365 arg.width = std::max(arg.width - prefixLen, 0);
367 format_value::formatString(val, arg, cb);
370 template <class FormatCallback, bool containerMode, class... Args>
371 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
373 FormatCallback& cb) {
374 if (arg.width == FormatArg::kDefaultWidth &&
375 arg.precision == FormatArg::kDefaultPrecision) {
378 } else if (arg.align != FormatArg::Align::LEFT &&
379 arg.align != FormatArg::Align::DEFAULT) {
380 // We can only avoid creating a temporary string if we align left,
381 // as we'd need to know the size beforehand otherwise
382 format_value::formatString(formatter.fbstr(), arg, cb);
384 auto fn = [&arg, &cb] (StringPiece sp) mutable {
385 int sz = static_cast<int>(sp.size());
386 if (arg.precision != FormatArg::kDefaultPrecision) {
387 sz = std::min(arg.precision, sz);
388 sp.reset(sp.data(), sz);
393 if (arg.width != FormatArg::kDefaultWidth) {
394 arg.width = std::max(arg.width - sz, 0);
399 if (arg.width != FormatArg::kDefaultWidth && arg.width != 0) {
400 // Rely on formatString to do appropriate padding
401 format_value::formatString(StringPiece(), arg, cb);
406 } // namespace format_value
408 // Definitions for default FormatValue classes
410 // Integral types (except bool)
413 T, typename std::enable_if<
414 std::is_integral<T>::value &&
415 !std::is_same<T, bool>::value>::type>
418 explicit FormatValue(T val) : val_(val) { }
419 template <class FormatCallback>
420 void format(FormatArg& arg, FormatCallback& cb) const {
421 arg.validate(FormatArg::Type::INTEGER);
425 template <class FormatCallback>
426 void doFormat(FormatArg& arg, FormatCallback& cb) const {
427 char presentation = arg.presentation;
428 if (presentation == FormatArg::kDefaultPresentation) {
429 presentation = std::is_same<T, char>::value ? 'c' : 'd';
432 // Do all work as unsigned, we'll add the prefix ('0' or '0x' if necessary)
433 // and sign ourselves.
434 typedef typename std::make_unsigned<T>::type UT;
437 if (std::is_signed<T>::value) {
438 if (folly::is_negative(val_)) {
439 uval = static_cast<UT>(-val_);
442 uval = static_cast<UT>(val_);
444 case FormatArg::Sign::PLUS_OR_MINUS:
447 case FormatArg::Sign::SPACE_OR_MINUS:
459 arg.enforce(arg.sign == FormatArg::Sign::DEFAULT,
460 "sign specifications not allowed for unsigned values");
464 // #x: 0x prefix + 16 bytes = 18 bytes
465 // #o: 0 prefix + 22 bytes = 23 bytes
466 // #b: 0b prefix + 64 bytes = 65 bytes
467 // ,d: 26 bytes (including thousands separators!)
469 // + 3 for sign and prefix shenanigans (see below)
470 constexpr size_t valBufSize = 69;
471 char valBuf[valBufSize];
472 char* valBufBegin = nullptr;
473 char* valBufEnd = nullptr;
476 auto useSprintf = [&] (const char* format) mutable {
477 valBufBegin = valBuf + 3; // room for sign and base prefix
478 valBufEnd = valBufBegin + sprintf(valBufBegin, format,
479 static_cast<uintmax_t>(uval));
484 switch (presentation) {
485 case 'n': // TODO(tudorb): locale awareness?
487 arg.enforce(!arg.basePrefix,
488 "base prefix not allowed with '", presentation,
490 if (arg.thousandsSeparator) {
493 // Use uintToBuffer, faster than sprintf
494 valBufBegin = valBuf + 3;
495 valBufEnd = valBufBegin + uint64ToBufferUnsafe(uval, valBufBegin);
499 arg.enforce(!arg.basePrefix,
500 "base prefix not allowed with '", presentation,
502 arg.enforce(!arg.thousandsSeparator,
503 "thousands separator (',') not allowed with '",
504 presentation, "' specifier");
505 valBufBegin = valBuf + 3;
506 *valBufBegin = static_cast<char>(uval);
507 valBufEnd = valBufBegin + 1;
511 arg.enforce(!arg.thousandsSeparator,
512 "thousands separator (',') not allowed with '",
513 presentation, "' specifier");
514 valBufEnd = valBuf + valBufSize - 1;
515 valBufBegin = valBuf + detail::uintToOctal(valBuf, valBufSize - 1, uval);
516 if (arg.basePrefix) {
517 *--valBufBegin = '0';
522 arg.enforce(!arg.thousandsSeparator,
523 "thousands separator (',') not allowed with '",
524 presentation, "' specifier");
525 valBufEnd = valBuf + valBufSize - 1;
526 valBufBegin = valBuf + detail::uintToHexLower(valBuf, valBufSize - 1,
528 if (arg.basePrefix) {
529 *--valBufBegin = 'x';
530 *--valBufBegin = '0';
535 arg.enforce(!arg.thousandsSeparator,
536 "thousands separator (',') not allowed with '",
537 presentation, "' specifier");
538 valBufEnd = valBuf + valBufSize - 1;
539 valBufBegin = valBuf + detail::uintToHexUpper(valBuf, valBufSize - 1,
541 if (arg.basePrefix) {
542 *--valBufBegin = 'X';
543 *--valBufBegin = '0';
549 arg.enforce(!arg.thousandsSeparator,
550 "thousands separator (',') not allowed with '",
551 presentation, "' specifier");
552 valBufEnd = valBuf + valBufSize - 1;
553 valBufBegin = valBuf + detail::uintToBinary(valBuf, valBufSize - 1,
555 if (arg.basePrefix) {
556 *--valBufBegin = presentation; // 0b or 0B
557 *--valBufBegin = '0';
562 arg.error("invalid specifier '", presentation, "'");
566 *--valBufBegin = sign;
570 format_value::formatNumber(StringPiece(valBufBegin, valBufEnd), prefixLen,
580 class FormatValue<bool> {
582 explicit FormatValue(bool val) : val_(val) { }
584 template <class FormatCallback>
585 void format(FormatArg& arg, FormatCallback& cb) const {
586 if (arg.presentation == FormatArg::kDefaultPresentation) {
587 arg.validate(FormatArg::Type::OTHER);
588 format_value::formatString(val_ ? "true" : "false", arg, cb);
590 FormatValue<int>(val_).format(arg, cb);
600 class FormatValue<double> {
602 explicit FormatValue(double val) : val_(val) { }
604 template <class FormatCallback>
605 void format(FormatArg& arg, FormatCallback& cb) const {
606 using ::double_conversion::DoubleToStringConverter;
607 using ::double_conversion::StringBuilder;
609 arg.validate(FormatArg::Type::FLOAT);
611 if (arg.presentation == FormatArg::kDefaultPresentation) {
612 arg.presentation = 'g';
615 const char* infinitySymbol = isupper(arg.presentation) ? "INF" : "inf";
616 const char* nanSymbol = isupper(arg.presentation) ? "NAN" : "nan";
617 char exponentSymbol = isupper(arg.presentation) ? 'E' : 'e';
619 if (arg.precision == FormatArg::kDefaultPrecision) {
623 // 2+: for null terminator and optional sign shenanigans.
624 char buf[2 + std::max({
625 (2 + DoubleToStringConverter::kMaxFixedDigitsBeforePoint +
626 DoubleToStringConverter::kMaxFixedDigitsAfterPoint),
627 (8 + DoubleToStringConverter::kMaxExponentialDigits),
628 (7 + DoubleToStringConverter::kMaxPrecisionDigits)})];
629 StringBuilder builder(buf + 1, sizeof(buf) - 1);
633 case FormatArg::Sign::PLUS_OR_MINUS:
636 case FormatArg::Sign::SPACE_OR_MINUS:
645 switch (arg.presentation) {
652 DoubleToStringConverter::kMaxFixedDigitsAfterPoint) {
653 arg.precision = DoubleToStringConverter::kMaxFixedDigitsAfterPoint;
655 DoubleToStringConverter conv(
656 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,
662 arg.enforce(conv.ToFixed(val, arg.precision, &builder),
663 "fixed double conversion failed");
669 if (arg.precision > DoubleToStringConverter::kMaxExponentialDigits) {
670 arg.precision = DoubleToStringConverter::kMaxExponentialDigits;
673 DoubleToStringConverter conv(
674 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,
680 arg.enforce(conv.ToExponential(val, arg.precision, &builder));
683 case 'n': // should be locale-aware, but isn't
687 if (arg.precision < DoubleToStringConverter::kMinPrecisionDigits) {
688 arg.precision = DoubleToStringConverter::kMinPrecisionDigits;
689 } else if (arg.precision >
690 DoubleToStringConverter::kMaxPrecisionDigits) {
691 arg.precision = DoubleToStringConverter::kMaxPrecisionDigits;
693 DoubleToStringConverter conv(
694 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,
700 arg.enforce(conv.ToShortest(val, &builder));
704 arg.error("invalid specifier '", arg.presentation, "'");
707 int len = builder.position();
711 // Add '+' or ' ' sign if needed
713 // anything that's neither negative nor nan
715 if (plusSign && (*p != '-' && *p != 'n' && *p != 'N')) {
719 } else if (*p == '-') {
723 format_value::formatNumber(StringPiece(p, len), prefixLen, arg, cb);
730 // float (defer to double)
732 class FormatValue<float> {
734 explicit FormatValue(float val) : val_(val) { }
736 template <class FormatCallback>
737 void format(FormatArg& arg, FormatCallback& cb) const {
738 FormatValue<double>(val_).format(arg, cb);
745 // Sring-y types (implicitly convertible to StringPiece, except char*)
748 T, typename std::enable_if<
749 (!std::is_pointer<T>::value ||
750 !std::is_same<char, typename std::decay<
751 typename std::remove_pointer<T>::type>::type>::value) &&
752 std::is_convertible<T, StringPiece>::value>::type>
755 explicit FormatValue(StringPiece val) : val_(val) { }
757 template <class FormatCallback>
758 void format(FormatArg& arg, FormatCallback& cb) const {
759 if (arg.keyEmpty()) {
760 arg.validate(FormatArg::Type::OTHER);
761 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation ||
762 arg.presentation == 's',
763 "invalid specifier '", arg.presentation, "'");
764 format_value::formatString(val_, arg, cb);
766 FormatValue<char>(val_.at(arg.splitIntKey())).format(arg, cb);
776 class FormatValue<std::nullptr_t> {
778 explicit FormatValue(std::nullptr_t) { }
780 template <class FormatCallback>
781 void format(FormatArg& arg, FormatCallback& cb) const {
782 arg.validate(FormatArg::Type::OTHER);
783 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
784 "invalid specifier '", arg.presentation, "'");
785 format_value::formatString("(null)", arg, cb);
789 // Partial specialization of FormatValue for char*
793 typename std::enable_if<
794 std::is_same<char, typename std::decay<T>::type>::value>::type>
797 explicit FormatValue(T* val) : val_(val) { }
799 template <class FormatCallback>
800 void format(FormatArg& arg, FormatCallback& cb) const {
801 if (arg.keyEmpty()) {
803 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
805 FormatValue<StringPiece>(val_).format(arg, cb);
808 FormatValue<typename std::decay<T>::type>(
809 val_[arg.splitIntKey()]).format(arg, cb);
817 // Partial specialization of FormatValue for void*
821 typename std::enable_if<
822 std::is_same<void, typename std::decay<T>::type>::value>::type>
825 explicit FormatValue(T* val) : val_(val) { }
827 template <class FormatCallback>
828 void format(FormatArg& arg, FormatCallback& cb) const {
830 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
832 // Print as a pointer, in hex.
833 arg.validate(FormatArg::Type::OTHER);
834 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
835 "invalid specifier '", arg.presentation, "'");
836 arg.basePrefix = true;
837 arg.presentation = 'x';
838 if (arg.align == FormatArg::Align::DEFAULT) {
839 arg.align = FormatArg::Align::LEFT;
841 FormatValue<uintptr_t>(
842 reinterpret_cast<uintptr_t>(val_)).doFormat(arg, cb);
850 template <class T, class = void>
851 class TryFormatValue {
853 template <class FormatCallback>
854 static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
855 arg.error("No formatter available for this type");
860 class TryFormatValue<
862 typename std::enable_if<
863 0 < sizeof(FormatValue<typename std::decay<T>::type>)>::type>
866 template <class FormatCallback>
867 static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
868 FormatValue<typename std::decay<T>::type>(value).format(arg, cb);
872 // Partial specialization of FormatValue for other pointers
876 typename std::enable_if<
877 !std::is_same<char, typename std::decay<T>::type>::value &&
878 !std::is_same<void, typename std::decay<T>::type>::value>::type>
881 explicit FormatValue(T* val) : val_(val) { }
883 template <class FormatCallback>
884 void format(FormatArg& arg, FormatCallback& cb) const {
885 if (arg.keyEmpty()) {
886 FormatValue<void*>((void*)val_).format(arg, cb);
888 TryFormatValue<T>::formatOrFail(val_[arg.splitIntKey()], arg, cb);
897 // Shortcut, so we don't have to use enable_if everywhere
898 struct FormatTraitsBase {
899 typedef void enabled;
902 // Traits that define enabled, value_type, and at() for anything
903 // indexable with integral keys: pointers, arrays, vectors, and maps
904 // with integral keys
905 template <class T, class Enable=void> struct IndexableTraits;
907 // Base class for sequences (vectors, deques)
909 struct IndexableTraitsSeq : public FormatTraitsBase {
910 typedef C container_type;
911 typedef typename C::value_type value_type;
912 static const value_type& at(const C& c, int idx) {
916 static const value_type& at(const C& c, int idx,
917 const value_type& dflt) {
918 return (idx >= 0 && idx < c.size()) ? c.at(idx) : dflt;
922 // Base class for associative types (maps)
924 struct IndexableTraitsAssoc : public FormatTraitsBase {
925 typedef typename C::value_type::second_type value_type;
926 static const value_type& at(const C& c, int idx) {
927 return c.at(static_cast<typename C::key_type>(idx));
929 static const value_type& at(const C& c, int idx,
930 const value_type& dflt) {
931 auto pos = c.find(static_cast<typename C::key_type>(idx));
932 return pos != c.end() ? pos->second : dflt;
937 template <class T, size_t N>
938 struct IndexableTraits<std::array<T, N>>
939 : public IndexableTraitsSeq<std::array<T, N>> {
943 template <class T, class A>
944 struct IndexableTraits<std::vector<T, A>>
945 : public IndexableTraitsSeq<std::vector<T, A>> {
949 template <class T, class A>
950 struct IndexableTraits<std::deque<T, A>>
951 : public IndexableTraitsSeq<std::deque<T, A>> {
955 template <class T, class A>
956 struct IndexableTraits<fbvector<T, A>>
957 : public IndexableTraitsSeq<fbvector<T, A>> {
961 template <class T, size_t M, class A, class B, class C>
962 struct IndexableTraits<small_vector<T, M, A, B, C>>
963 : public IndexableTraitsSeq<small_vector<T, M, A, B, C>> {
966 // std::map with integral keys
967 template <class K, class T, class C, class A>
968 struct IndexableTraits<
969 std::map<K, T, C, A>,
970 typename std::enable_if<std::is_integral<K>::value>::type>
971 : public IndexableTraitsAssoc<std::map<K, T, C, A>> {
974 // std::unordered_map with integral keys
975 template <class K, class T, class H, class E, class A>
976 struct IndexableTraits<
977 std::unordered_map<K, T, H, E, A>,
978 typename std::enable_if<std::is_integral<K>::value>::type>
979 : public IndexableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
982 } // namespace detail
984 // Partial specialization of FormatValue for integer-indexable containers
988 typename detail::IndexableTraits<T>::enabled> {
990 explicit FormatValue(const T& val) : val_(val) { }
992 template <class FormatCallback>
993 void format(FormatArg& arg, FormatCallback& cb) const {
994 FormatValue<typename std::decay<
995 typename detail::IndexableTraits<T>::value_type>::type>(
996 detail::IndexableTraits<T>::at(
997 val_, arg.splitIntKey())).format(arg, cb);
1004 template <class Container, class Value>
1006 detail::DefaultValueWrapper<Container, Value>,
1007 typename detail::IndexableTraits<Container>::enabled> {
1009 explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
1012 template <class FormatCallback>
1013 void format(FormatArg& arg, FormatCallback& cb) const {
1014 FormatValue<typename std::decay<
1015 typename detail::IndexableTraits<Container>::value_type>::type>(
1016 detail::IndexableTraits<Container>::at(
1019 val_.defaultValue)).format(arg, cb);
1023 const detail::DefaultValueWrapper<Container, Value>& val_;
1028 // Define enabled, key_type, convert from StringPiece to the key types
1030 template <class T> struct KeyFromStringPiece;
1034 struct KeyFromStringPiece<std::string> : public FormatTraitsBase {
1035 typedef std::string key_type;
1036 static std::string convert(StringPiece s) {
1037 return s.toString();
1039 typedef void enabled;
1044 struct KeyFromStringPiece<fbstring> : public FormatTraitsBase {
1045 typedef fbstring key_type;
1046 static fbstring convert(StringPiece s) {
1047 return s.toFbstring();
1053 struct KeyFromStringPiece<StringPiece> : public FormatTraitsBase {
1054 typedef StringPiece key_type;
1055 static StringPiece convert(StringPiece s) {
1060 // Base class for associative types keyed by strings
1061 template <class T> struct KeyableTraitsAssoc : public FormatTraitsBase {
1062 typedef typename T::key_type key_type;
1063 typedef typename T::value_type::second_type value_type;
1064 static const value_type& at(const T& map, StringPiece key) {
1065 return map.at(KeyFromStringPiece<key_type>::convert(key));
1067 static const value_type& at(const T& map, StringPiece key,
1068 const value_type& dflt) {
1069 auto pos = map.find(KeyFromStringPiece<key_type>::convert(key));
1070 return pos != map.end() ? pos->second : dflt;
1074 // Define enabled, key_type, value_type, at() for supported string-keyed
1076 template <class T, class Enabled=void> struct KeyableTraits;
1078 // std::map with string key
1079 template <class K, class T, class C, class A>
1080 struct KeyableTraits<
1081 std::map<K, T, C, A>,
1082 typename KeyFromStringPiece<K>::enabled>
1083 : public KeyableTraitsAssoc<std::map<K, T, C, A>> {
1086 // std::unordered_map with string key
1087 template <class K, class T, class H, class E, class A>
1088 struct KeyableTraits<
1089 std::unordered_map<K, T, H, E, A>,
1090 typename KeyFromStringPiece<K>::enabled>
1091 : public KeyableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
1094 } // namespace detail
1096 // Partial specialization of FormatValue for string-keyed containers
1100 typename detail::KeyableTraits<T>::enabled> {
1102 explicit FormatValue(const T& val) : val_(val) { }
1104 template <class FormatCallback>
1105 void format(FormatArg& arg, FormatCallback& cb) const {
1106 FormatValue<typename std::decay<
1107 typename detail::KeyableTraits<T>::value_type>::type>(
1108 detail::KeyableTraits<T>::at(
1109 val_, arg.splitKey())).format(arg, cb);
1116 template <class Container, class Value>
1118 detail::DefaultValueWrapper<Container, Value>,
1119 typename detail::KeyableTraits<Container>::enabled> {
1121 explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
1124 template <class FormatCallback>
1125 void format(FormatArg& arg, FormatCallback& cb) const {
1126 FormatValue<typename std::decay<
1127 typename detail::KeyableTraits<Container>::value_type>::type>(
1128 detail::KeyableTraits<Container>::at(
1131 val_.defaultValue)).format(arg, cb);
1135 const detail::DefaultValueWrapper<Container, Value>& val_;
1138 // Partial specialization of FormatValue for pairs
1139 template <class A, class B>
1140 class FormatValue<std::pair<A, B>> {
1142 explicit FormatValue(const std::pair<A, B>& val) : val_(val) { }
1144 template <class FormatCallback>
1145 void format(FormatArg& arg, FormatCallback& cb) const {
1146 int key = arg.splitIntKey();
1149 FormatValue<typename std::decay<A>::type>(val_.first).format(arg, cb);
1152 FormatValue<typename std::decay<B>::type>(val_.second).format(arg, cb);
1155 arg.error("invalid index for pair");
1160 const std::pair<A, B>& val_;
1163 // Partial specialization of FormatValue for tuples
1164 template <class... Args>
1165 class FormatValue<std::tuple<Args...>> {
1166 typedef std::tuple<Args...> Tuple;
1168 explicit FormatValue(const Tuple& val) : val_(val) { }
1170 template <class FormatCallback>
1171 void format(FormatArg& arg, FormatCallback& cb) const {
1172 int key = arg.splitIntKey();
1173 arg.enforce(key >= 0, "tuple index must be non-negative");
1174 doFormat(key, arg, cb);
1178 static constexpr size_t valueCount = std::tuple_size<Tuple>::value;
1180 template <size_t K, class Callback>
1181 typename std::enable_if<K == valueCount>::type
1182 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1183 arg.enforce("tuple index out of range, max=", i);
1186 template <size_t K, class Callback>
1187 typename std::enable_if<(K < valueCount)>::type
1188 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1190 FormatValue<typename std::decay<
1191 typename std::tuple_element<K, Tuple>::type>::type>(
1192 std::get<K>(val_)).format(arg, cb);
1194 doFormatFrom<K+1>(i, arg, cb);
1198 template <class Callback>
1199 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
1200 return doFormatFrom<0>(i, arg, cb);
1206 // Partial specialization of FormatValue for nested Formatters
1207 template <bool containerMode, class... Args>
1208 class FormatValue<Formatter<containerMode, Args...>, void> {
1209 typedef Formatter<containerMode, Args...> FormatterValue;
1211 explicit FormatValue(const FormatterValue& f) : f_(f) { }
1213 template <class FormatCallback>
1214 void format(FormatArg& arg, FormatCallback& cb) const {
1215 format_value::formatFormatter(f_, arg, cb);
1218 const FormatterValue& f_;
1222 * Formatter objects can be appended to strings, and therefore they're
1223 * compatible with folly::toAppend and folly::to.
1225 template <class Tgt, bool containerMode, class... Args>
1226 typename std::enable_if<
1227 IsSomeString<Tgt>::value>::type
1228 toAppend(const Formatter<containerMode, Args...>& value, Tgt * result) {
1229 value.appendTo(*result);
1232 } // namespace folly
1234 #pragma GCC diagnostic pop