2 * Copyright 2012 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.
25 extern const char formatHexUpper[256][2];
26 extern const char formatHexLower[256][2];
27 extern const char formatOctal[512][3];
28 extern const char formatBinary[256][8];
30 const size_t kMaxHexLength = 2 * sizeof(uintmax_t);
31 const size_t kMaxOctalLength = 3 * sizeof(uintmax_t);
32 const size_t kMaxBinaryLength = 8 * sizeof(uintmax_t);
35 * Convert an unsigned to hex, using repr (which maps from each possible
36 * 2-hex-bytes value to the 2-character representation).
38 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
39 * the supplied buffer and returns the offset of the beginning of the string
40 * from the start of the buffer. The formatted string will be in range
41 * [buf+begin, buf+bufLen).
44 size_t uintToHex(char* buffer, size_t bufLen, Uint v,
45 const char (&repr)[256][2]) {
46 for (; v >= 256; v >>= 8) {
49 buffer[bufLen] = repr[b][0];
50 buffer[bufLen + 1] = repr[b][1];
52 buffer[--bufLen] = repr[v][1];
54 buffer[--bufLen] = repr[v][0];
60 * Convert an unsigned to hex, using lower-case letters for the digits
61 * above 9. See the comments for uintToHex.
64 inline size_t uintToHexLower(char* buffer, size_t bufLen, Uint v) {
65 return uintToHex(buffer, bufLen, v, formatHexLower);
69 * Convert an unsigned to hex, using upper-case letters for the digits
70 * above 9. See the comments for uintToHex.
73 inline size_t uintToHexUpper(char* buffer, size_t bufLen, Uint v) {
74 return uintToHex(buffer, bufLen, v, formatHexUpper);
78 * Convert an unsigned to octal.
80 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
81 * the supplied buffer and returns the offset of the beginning of the string
82 * from the start of the buffer. The formatted string will be in range
83 * [buf+begin, buf+bufLen).
86 size_t uintToOctal(char* buffer, size_t bufLen, Uint v) {
87 auto& repr = formatOctal;
88 for (; v >= 512; v >>= 9) {
91 buffer[bufLen] = repr[b][0];
92 buffer[bufLen + 1] = repr[b][1];
93 buffer[bufLen + 2] = repr[b][2];
95 buffer[--bufLen] = repr[v][2];
97 buffer[--bufLen] = repr[v][1];
100 buffer[--bufLen] = repr[v][0];
106 * Convert an unsigned to binary.
108 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
109 * the supplied buffer and returns the offset of the beginning of the string
110 * from the start of the buffer. The formatted string will be in range
111 * [buf+begin, buf+bufLen).
113 template <class Uint>
114 size_t uintToBinary(char* buffer, size_t bufLen, Uint v) {
115 auto& repr = formatBinary;
117 buffer[--bufLen] = '0';
123 memcpy(buffer + bufLen, &(repr[b][0]), 8);
125 while (buffer[bufLen] == '0') {
131 } // namespace detail
134 template <bool containerMode, class... Args>
135 Formatter<containerMode, Args...>::Formatter(StringPiece str, Args&&... args)
137 values_(FormatValue<typename std::decay<Args>::type>(
138 std::forward<Args>(args))...) {
139 static_assert(!containerMode || sizeof...(Args) == 1,
140 "Exactly one argument required in container mode");
143 template <bool containerMode, class... Args>
144 template <class Output>
145 void Formatter<containerMode, Args...>::operator()(Output& out) const {
146 auto p = str_.begin();
147 auto end = str_.end();
149 // Copy raw string (without format specifiers) to output;
150 // not as simple as we'd like, as we still need to translate "}}" to "}"
151 // and throw if we see any lone "}"
152 auto outputString = [&out] (StringPiece s) {
156 auto q = static_cast<const char*>(memchr(p, '}', end - p));
158 out(StringPiece(p, end));
162 out(StringPiece(p, q));
165 if (p == end || *p != '}') {
166 throw std::invalid_argument(
167 "folly::format: single '}' in format string");
174 bool hasDefaultArgIndex = false;
175 bool hasExplicitArgIndex = false;
177 auto q = static_cast<const char*>(memchr(p, '{', end - p));
179 outputString(StringPiece(p, end));
182 outputString(StringPiece(p, q));
186 throw std::invalid_argument(
187 "folly::format: '}' at end of format string");
192 out(StringPiece(p, 1));
198 q = static_cast<const char*>(memchr(p, '}', end - p));
200 throw std::invalid_argument("folly::format: missing ending '}'");
202 FormatArg arg(StringPiece(p, q));
206 auto piece = arg.splitKey<true>(); // empty key component is okay
207 if (containerMode) { // static
209 arg.setNextIntKey(nextArg++);
210 hasDefaultArgIndex = true;
212 arg.setNextKey(piece);
213 hasExplicitArgIndex = true;
217 argIndex = nextArg++;
218 hasDefaultArgIndex = true;
221 argIndex = to<int>(piece);
222 } catch (const std::out_of_range& e) {
223 arg.error("argument index must be integer");
225 arg.enforce(argIndex >= 0, "argument index must be non-negative");
226 hasExplicitArgIndex = true;
230 if (hasDefaultArgIndex && hasExplicitArgIndex) {
231 throw std::invalid_argument(
232 "folly::format: may not have both default and explicit arg indexes");
235 doFormat(argIndex, arg, out);
239 namespace format_value {
241 template <class FormatCallback>
242 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb) {
243 if (arg.precision != FormatArg::kDefaultPrecision &&
244 val.size() > arg.precision) {
245 val.reset(val.data(), arg.precision);
248 constexpr int padBufSize = 128;
249 char padBuf[padBufSize];
251 // Output padding, no more than padBufSize at once
252 auto pad = [&padBuf, &cb, padBufSize] (int chars) {
254 int n = std::min(chars, padBufSize);
255 cb(StringPiece(padBuf, n));
260 int padRemaining = 0;
261 if (arg.width != FormatArg::kDefaultWidth && val.size() < arg.width) {
262 char fill = arg.fill == FormatArg::kDefaultFill ? ' ' : arg.fill;
263 int padChars = arg.width - val.size();
264 memset(padBuf, fill, std::min(padBufSize, padChars));
267 case FormatArg::Align::DEFAULT:
268 case FormatArg::Align::LEFT:
269 padRemaining = padChars;
271 case FormatArg::Align::CENTER:
273 padRemaining = padChars - padChars / 2;
275 case FormatArg::Align::RIGHT:
276 case FormatArg::Align::PAD_AFTER_SIGN:
292 template <class FormatCallback>
293 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
294 FormatCallback& cb) {
295 // precision means something different for numbers
296 arg.precision = FormatArg::kDefaultPrecision;
297 if (arg.align == FormatArg::Align::DEFAULT) {
298 arg.align = FormatArg::Align::RIGHT;
299 } else if (prefixLen && arg.align == FormatArg::Align::PAD_AFTER_SIGN) {
300 // Split off the prefix, then do any padding if necessary
301 cb(val.subpiece(0, prefixLen));
302 val.advance(prefixLen);
303 arg.width = std::max(arg.width - prefixLen, 0);
305 format_value::formatString(val, arg, cb);
308 template <class FormatCallback, bool containerMode, class... Args>
309 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
311 FormatCallback& cb) {
312 if (arg.width == FormatArg::kDefaultWidth &&
313 arg.precision == FormatArg::kDefaultPrecision) {
316 } else if (arg.align != FormatArg::Align::LEFT &&
317 arg.align != FormatArg::Align::DEFAULT) {
318 // We can only avoid creating a temporary string if we align left,
319 // as we'd need to know the size beforehand otherwise
320 format_value::formatString(formatter.fbstr(), arg, cb);
322 auto fn = [&arg, &cb] (StringPiece sp) mutable {
323 int sz = static_cast<int>(sp.size());
324 if (arg.precision != FormatArg::kDefaultPrecision) {
325 sz = std::min(arg.precision, sz);
326 sp.reset(sp.data(), sz);
331 if (arg.width != FormatArg::kDefaultWidth) {
332 arg.width = std::max(arg.width - sz, 0);
337 if (arg.width != FormatArg::kDefaultWidth && arg.width != 0) {
338 // Rely on formatString to do appropriate padding
339 format_value::formatString(StringPiece(), arg, cb);
344 } // namespace format_value
346 // Definitions for default FormatValue classes
348 // Integral types (except bool)
351 T, typename std::enable_if<
352 std::is_integral<T>::value &&
353 !std::is_same<T, bool>::value>::type>
356 explicit FormatValue(T val) : val_(val) { }
357 template <class FormatCallback>
358 void format(FormatArg& arg, FormatCallback& cb) const {
359 arg.validate(FormatArg::Type::INTEGER);
363 template <class FormatCallback>
364 void doFormat(FormatArg& arg, FormatCallback& cb) const {
365 char presentation = arg.presentation;
366 if (presentation == FormatArg::kDefaultPresentation) {
367 presentation = std::is_same<T, char>::value ? 'c' : 'd';
370 // Do all work as unsigned, we'll add the prefix ('0' or '0x' if necessary)
371 // and sign ourselves.
372 typedef typename std::make_unsigned<T>::type UT;
375 if (std::is_signed<T>::value) {
377 uval = static_cast<UT>(-val_);
380 uval = static_cast<UT>(val_);
382 case FormatArg::Sign::PLUS_OR_MINUS:
385 case FormatArg::Sign::SPACE_OR_MINUS:
397 arg.enforce(arg.sign == FormatArg::Sign::DEFAULT,
398 "sign specifications not allowed for unsigned values");
402 // #x: 0x prefix + 16 bytes = 18 bytes
403 // #o: 0 prefix + 22 bytes = 23 bytes
404 // #b: 0b prefix + 64 bytes = 65 bytes
405 // ,d: 26 bytes (including thousands separators!)
407 // + 3 for sign and prefix shenanigans (see below)
408 constexpr size_t valBufSize = 69;
409 char valBuf[valBufSize];
410 char* valBufBegin = nullptr;
411 char* valBufEnd = nullptr;
414 auto useSprintf = [&] (const char* format) mutable {
415 valBufBegin = valBuf + 3; // room for sign and base prefix
416 valBufEnd = valBufBegin + sprintf(valBufBegin, format,
417 static_cast<uintmax_t>(uval));
422 switch (presentation) {
423 case 'n': // TODO(tudorb): locale awareness?
425 arg.enforce(!arg.basePrefix,
426 "base prefix not allowed with '", presentation,
428 if (arg.thousandsSeparator) {
431 // Use uintToBuffer, faster than sprintf
432 valBufEnd = valBuf + valBufSize - 1;
433 valBufBegin = valBuf + detail::uintToBuffer(valBuf, valBufSize - 1,
438 arg.enforce(!arg.basePrefix,
439 "base prefix not allowed with '", presentation,
441 arg.enforce(!arg.thousandsSeparator,
442 "thousands separator (',') not allowed with '",
443 presentation, "' specifier");
444 valBufBegin = valBuf + 3;
445 *valBufBegin = static_cast<char>(uval);
446 valBufEnd = valBufBegin + 1;
450 arg.enforce(!arg.thousandsSeparator,
451 "thousands separator (',') not allowed with '",
452 presentation, "' specifier");
453 valBufEnd = valBuf + valBufSize - 1;
454 valBufBegin = valBuf + detail::uintToOctal(valBuf, valBufSize - 1, uval);
455 if (arg.basePrefix) {
456 *--valBufBegin = '0';
461 arg.enforce(!arg.thousandsSeparator,
462 "thousands separator (',') not allowed with '",
463 presentation, "' specifier");
464 valBufEnd = valBuf + valBufSize - 1;
465 valBufBegin = valBuf + detail::uintToHexLower(valBuf, valBufSize - 1,
467 if (arg.basePrefix) {
468 *--valBufBegin = 'x';
469 *--valBufBegin = '0';
474 arg.enforce(!arg.thousandsSeparator,
475 "thousands separator (',') not allowed with '",
476 presentation, "' specifier");
477 valBufEnd = valBuf + valBufSize - 1;
478 valBufBegin = valBuf + detail::uintToHexUpper(valBuf, valBufSize - 1,
480 if (arg.basePrefix) {
481 *--valBufBegin = 'X';
482 *--valBufBegin = '0';
488 arg.enforce(!arg.thousandsSeparator,
489 "thousands separator (',') not allowed with '",
490 presentation, "' specifier");
491 valBufEnd = valBuf + valBufSize - 1;
492 valBufBegin = valBuf + detail::uintToBinary(valBuf, valBufSize - 1,
494 if (arg.basePrefix) {
495 *--valBufBegin = presentation; // 0b or 0B
496 *--valBufBegin = '0';
501 arg.error("invalid specifier '", presentation, "'");
505 *--valBufBegin = sign;
509 format_value::formatNumber(StringPiece(valBufBegin, valBufEnd), prefixLen,
519 class FormatValue<bool> {
521 explicit FormatValue(bool val) : val_(val) { }
523 template <class FormatCallback>
524 void format(FormatArg& arg, FormatCallback& cb) const {
525 if (arg.presentation == FormatArg::kDefaultPresentation) {
526 arg.validate(FormatArg::Type::OTHER);
527 format_value::formatString(val_ ? "true" : "false", arg, cb);
529 FormatValue<int>(val_).format(arg, cb);
539 class FormatValue<double> {
541 explicit FormatValue(double val) : val_(val) { }
543 template <class FormatCallback>
544 void format(FormatArg& arg, FormatCallback& cb) const {
545 using ::double_conversion::DoubleToStringConverter;
546 using ::double_conversion::StringBuilder;
548 arg.validate(FormatArg::Type::FLOAT);
550 if (arg.presentation == FormatArg::kDefaultPresentation) {
551 arg.presentation = 'g';
554 const char* infinitySymbol = isupper(arg.presentation) ? "INF" : "inf";
555 const char* nanSymbol = isupper(arg.presentation) ? "NAN" : "nan";
556 char exponentSymbol = isupper(arg.presentation) ? 'E' : 'e';
558 if (arg.precision == FormatArg::kDefaultPrecision) {
564 // 2+: for null terminator and optional sign shenanigans.
565 char buf[2 + std::max({
566 (2 + DoubleToStringConverter::kMaxFixedDigitsBeforePoint +
567 DoubleToStringConverter::kMaxFixedDigitsAfterPoint),
568 (8 + DoubleToStringConverter::kMaxExponentialDigits),
569 (7 + DoubleToStringConverter::kMaxPrecisionDigits)})];
570 StringBuilder builder(buf + 1, sizeof(buf) - 1);
574 case FormatArg::Sign::PLUS_OR_MINUS:
577 case FormatArg::Sign::SPACE_OR_MINUS:
586 switch (arg.presentation) {
593 DoubleToStringConverter::kMaxFixedDigitsAfterPoint) {
594 arg.precision = DoubleToStringConverter::kMaxFixedDigitsAfterPoint;
596 DoubleToStringConverter conv(
597 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,
603 arg.enforce(conv.ToFixed(val, arg.precision, &builder),
604 "fixed double conversion failed");
610 if (arg.precision > DoubleToStringConverter::kMaxExponentialDigits) {
611 arg.precision = DoubleToStringConverter::kMaxExponentialDigits;
614 DoubleToStringConverter conv(
615 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,
621 CHECK(conv.ToExponential(val, arg.precision, &builder));
624 case 'n': // should be locale-aware, but isn't
628 if (arg.precision < DoubleToStringConverter::kMinPrecisionDigits) {
629 arg.precision = DoubleToStringConverter::kMinPrecisionDigits;
630 } else if (arg.precision >
631 DoubleToStringConverter::kMaxPrecisionDigits) {
632 arg.precision = DoubleToStringConverter::kMaxPrecisionDigits;
634 DoubleToStringConverter conv(
635 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,
641 CHECK(conv.ToShortest(val, &builder));
645 arg.error("invalid specifier '", arg.presentation, "'");
648 int len = builder.position();
652 // Add '+' or ' ' sign if needed
654 // anything that's neither negative nor nan
656 if (plusSign && (*p != '-' && *p != 'n' && *p != 'N')) {
660 } else if (*p == '-') {
664 format_value::formatNumber(StringPiece(p, len), prefixLen, arg, cb);
671 // float (defer to double)
673 class FormatValue<float> {
675 explicit FormatValue(float val) : val_(val) { }
677 template <class FormatCallback>
678 void format(FormatArg& arg, FormatCallback& cb) const {
679 FormatValue<double>(val_).format(arg, cb);
686 // Sring-y types (implicitly convertible to StringPiece, except char*)
689 T, typename std::enable_if<
690 (!std::is_pointer<T>::value ||
691 !std::is_same<char, typename std::decay<
692 typename std::remove_pointer<T>::type>::type>::value) &&
693 std::is_convertible<T, StringPiece>::value>::type>
696 explicit FormatValue(StringPiece val) : val_(val) { }
698 template <class FormatCallback>
699 void format(FormatArg& arg, FormatCallback& cb) const {
700 if (arg.keyEmpty()) {
701 arg.validate(FormatArg::Type::OTHER);
702 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation ||
703 arg.presentation == 's',
704 "invalid specifier '", arg.presentation, "'");
705 format_value::formatString(val_, arg, cb);
707 FormatValue<char>(val_.at(arg.splitIntKey())).format(arg, cb);
717 class FormatValue<std::nullptr_t> {
719 explicit FormatValue(std::nullptr_t) { }
721 template <class FormatCallback>
722 void format(FormatArg& arg, FormatCallback& cb) const {
723 arg.validate(FormatArg::Type::OTHER);
724 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
725 "invalid specifier '", arg.presentation, "'");
726 format_value::formatString("(null)", arg, cb);
730 // Partial specialization of FormatValue for char*
734 typename std::enable_if<
735 std::is_same<char, typename std::decay<T>::type>::value>::type>
738 explicit FormatValue(T* val) : val_(val) { }
740 template <class FormatCallback>
741 void format(FormatArg& arg, FormatCallback& cb) const {
742 if (arg.keyEmpty()) {
744 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
746 FormatValue<StringPiece>(val_).format(arg, cb);
749 FormatValue<typename std::decay<T>::type>(
750 val_[arg.splitIntKey()]).format(arg, cb);
758 // Partial specialization of FormatValue for void*
762 typename std::enable_if<
763 std::is_same<void, typename std::decay<T>::type>::value>::type>
766 explicit FormatValue(T* val) : val_(val) { }
768 template <class FormatCallback>
769 void format(FormatArg& arg, FormatCallback& cb) const {
771 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
773 // Print as a pointer, in hex.
774 arg.validate(FormatArg::Type::OTHER);
775 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
776 "invalid specifier '", arg.presentation, "'");
777 arg.basePrefix = true;
778 arg.presentation = 'x';
779 if (arg.align == FormatArg::Align::DEFAULT) {
780 arg.align = FormatArg::Align::LEFT;
782 FormatValue<uintptr_t>(
783 reinterpret_cast<uintptr_t>(val_)).doFormat(arg, cb);
791 // Partial specialization of FormatValue for other pointers
795 typename std::enable_if<
796 !std::is_same<char, typename std::decay<T>::type>::value &&
797 !std::is_same<void, typename std::decay<T>::type>::value>::type>
800 explicit FormatValue(T* val) : val_(val) { }
802 template <class FormatCallback>
803 void format(FormatArg& arg, FormatCallback& cb) const {
804 if (arg.keyEmpty()) {
805 FormatValue<void*>((void*)val_).format(arg, cb);
807 FormatValue<typename std::decay<T>::type>(
808 val_[arg.splitIntKey()]).format(arg, cb);
817 // Shortcut, so we don't have to use enable_if everywhere
818 struct FormatTraitsBase {
819 typedef void enabled;
822 // Traits that define enabled, value_type, and at() for anything
823 // indexable with integral keys: pointers, arrays, vectors, and maps
824 // with integral keys
825 template <class T, class Enable=void> struct IndexableTraits;
827 // Base class for sequences (vectors, deques)
829 struct IndexableTraitsSeq : public FormatTraitsBase {
830 typedef C container_type;
831 typedef typename C::value_type value_type;
832 static const value_type& at(const C& c, int idx) {
837 // Base class for associative types (maps)
839 struct IndexableTraitsAssoc : public FormatTraitsBase {
840 typedef typename C::value_type::second_type value_type;
841 static const value_type& at(const C& c, int idx) {
842 return c.at(static_cast<typename C::key_type>(idx));
847 template <class T, size_t N>
848 struct IndexableTraits<std::array<T, N>>
849 : public IndexableTraitsSeq<std::array<T, N>> {
853 template <class T, class A>
854 struct IndexableTraits<std::vector<T, A>>
855 : public IndexableTraitsSeq<std::vector<T, A>> {
859 template <class T, class A>
860 struct IndexableTraits<std::deque<T, A>>
861 : public IndexableTraitsSeq<std::deque<T, A>> {
865 template <class T, class A>
866 struct IndexableTraits<fbvector<T, A>>
867 : public IndexableTraitsSeq<fbvector<T, A>> {
871 template <class T, size_t M, class A, class B, class C>
872 struct IndexableTraits<small_vector<T, M, A, B, C>>
873 : public IndexableTraitsSeq<small_vector<T, M, A, B, C>> {
876 // std::map with integral keys
877 template <class K, class T, class C, class A>
878 struct IndexableTraits<
879 std::map<K, T, C, A>,
880 typename std::enable_if<std::is_integral<K>::value>::type>
881 : public IndexableTraitsAssoc<std::map<K, T, C, A>> {
884 // std::unordered_map with integral keys
885 template <class K, class T, class H, class E, class A>
886 struct IndexableTraits<
887 std::unordered_map<K, T, H, E, A>,
888 typename std::enable_if<std::is_integral<K>::value>::type>
889 : public IndexableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
892 } // namespace detail
894 // Partial specialization of FormatValue for integer-indexable containers
898 typename detail::IndexableTraits<T>::enabled> {
900 explicit FormatValue(const T& val) : val_(val) { }
902 template <class FormatCallback>
903 void format(FormatArg& arg, FormatCallback& cb) const {
904 FormatValue<typename std::decay<
905 typename detail::IndexableTraits<T>::value_type>::type>(
906 detail::IndexableTraits<T>::at(
907 val_, arg.splitIntKey())).format(arg, cb);
916 // Define enabled, key_type, convert from StringPiece to the key types
918 template <class T> struct KeyFromStringPiece;
922 struct KeyFromStringPiece<std::string> : public FormatTraitsBase {
923 typedef std::string key_type;
924 static std::string convert(StringPiece s) {
927 typedef void enabled;
932 struct KeyFromStringPiece<fbstring> : public FormatTraitsBase {
933 typedef fbstring key_type;
934 static fbstring convert(StringPiece s) {
935 return s.toFbstring();
941 struct KeyFromStringPiece<StringPiece> : public FormatTraitsBase {
942 typedef StringPiece key_type;
943 static StringPiece convert(StringPiece s) {
948 // Base class for associative types keyed by strings
949 template <class T> struct KeyableTraitsAssoc : public FormatTraitsBase {
950 typedef typename T::key_type key_type;
951 typedef typename T::value_type::second_type value_type;
952 static const value_type& at(const T& map, StringPiece key) {
953 return map.at(KeyFromStringPiece<key_type>::convert(key));
957 // Define enabled, key_type, value_type, at() for supported string-keyed
959 template <class T, class Enabled=void> struct KeyableTraits;
961 // std::map with string key
962 template <class K, class T, class C, class A>
963 struct KeyableTraits<
964 std::map<K, T, C, A>,
965 typename KeyFromStringPiece<K>::enabled>
966 : public KeyableTraitsAssoc<std::map<K, T, C, A>> {
969 // std::unordered_map with string key
970 template <class K, class T, class H, class E, class A>
971 struct KeyableTraits<
972 std::unordered_map<K, T, H, E, A>,
973 typename KeyFromStringPiece<K>::enabled>
974 : public KeyableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
977 } // namespace detail
979 // Partial specialization of FormatValue for string-keyed containers
983 typename detail::KeyableTraits<T>::enabled> {
985 explicit FormatValue(const T& val) : val_(val) { }
987 template <class FormatCallback>
988 void format(FormatArg& arg, FormatCallback& cb) const {
989 FormatValue<typename std::decay<
990 typename detail::KeyableTraits<T>::value_type>::type>(
991 detail::KeyableTraits<T>::at(
992 val_, arg.splitKey())).format(arg, cb);
999 // Partial specialization of FormatValue for pairs
1000 template <class A, class B>
1001 class FormatValue<std::pair<A, B>> {
1003 explicit FormatValue(const std::pair<A, B>& val) : val_(val) { }
1005 template <class FormatCallback>
1006 void format(FormatArg& arg, FormatCallback& cb) const {
1007 int key = arg.splitIntKey();
1010 FormatValue<typename std::decay<A>::type>(val_.first).format(arg, cb);
1013 FormatValue<typename std::decay<B>::type>(val_.second).format(arg, cb);
1016 arg.error("invalid index for pair");
1021 const std::pair<A, B>& val_;
1024 // Partial specialization of FormatValue for tuples
1025 template <class... Args>
1026 class FormatValue<std::tuple<Args...>> {
1027 typedef std::tuple<Args...> Tuple;
1029 explicit FormatValue(const Tuple& val) : val_(val) { }
1031 template <class FormatCallback>
1032 void format(FormatArg& arg, FormatCallback& cb) const {
1033 int key = arg.splitIntKey();
1034 arg.enforce(key >= 0, "tuple index must be non-negative");
1035 doFormat(key, arg, cb);
1039 static constexpr size_t valueCount = std::tuple_size<Tuple>::value;
1041 template <size_t K, class Callback>
1042 typename std::enable_if<K == valueCount>::type
1043 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1044 arg.enforce("tuple index out of range, max=", i);
1047 template <size_t K, class Callback>
1048 typename std::enable_if<(K < valueCount)>::type
1049 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1051 FormatValue<typename std::decay<
1052 typename std::tuple_element<K, Tuple>::type>::type>(
1053 std::get<K>(val_)).format(arg, cb);
1055 doFormatFrom<K+1>(i, arg, cb);
1059 template <class Callback>
1060 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
1061 return doFormatFrom<0>(i, arg, cb);
1068 * Formatter objects can be appended to strings, and therefore they're
1069 * compatible with folly::toAppend and folly::to.
1071 template <class Tgt, bool containerMode, class... Args>
1072 typename std::enable_if<
1073 detail::IsSomeString<Tgt>::value>::type
1074 toAppend(const Formatter<containerMode, Args...>& value, Tgt * result) {
1075 value.appendTo(*result);
1078 } // namespace folly