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"
28 extern const char formatHexUpper[256][2];
29 extern const char formatHexLower[256][2];
30 extern const char formatOctal[512][3];
31 extern const char formatBinary[256][8];
33 const size_t kMaxHexLength = 2 * sizeof(uintmax_t);
34 const size_t kMaxOctalLength = 3 * sizeof(uintmax_t);
35 const size_t kMaxBinaryLength = 8 * sizeof(uintmax_t);
38 * Convert an unsigned to hex, using repr (which maps from each possible
39 * 2-hex-bytes value to the 2-character representation).
41 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
42 * the supplied buffer and returns the offset of the beginning of the string
43 * from the start of the buffer. The formatted string will be in range
44 * [buf+begin, buf+bufLen).
47 size_t uintToHex(char* buffer, size_t bufLen, Uint v,
48 const char (&repr)[256][2]) {
49 // 'v >>= 7, v >>= 1' is no more than a work around to get rid of shift size
50 // warning when Uint = uint8_t (it's false as v >= 256 implies sizeof(v) > 1).
51 for (; !less_than<unsigned, 256>(v); v >>= 7, v >>= 1) {
54 buffer[bufLen] = repr[b][0];
55 buffer[bufLen + 1] = repr[b][1];
57 buffer[--bufLen] = repr[v][1];
59 buffer[--bufLen] = repr[v][0];
65 * Convert an unsigned to hex, using lower-case letters for the digits
66 * above 9. See the comments for uintToHex.
69 inline size_t uintToHexLower(char* buffer, size_t bufLen, Uint v) {
70 return uintToHex(buffer, bufLen, v, formatHexLower);
74 * Convert an unsigned to hex, using upper-case letters for the digits
75 * above 9. See the comments for uintToHex.
78 inline size_t uintToHexUpper(char* buffer, size_t bufLen, Uint v) {
79 return uintToHex(buffer, bufLen, v, formatHexUpper);
83 * Convert an unsigned to octal.
85 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
86 * the supplied buffer and returns the offset of the beginning of the string
87 * from the start of the buffer. The formatted string will be in range
88 * [buf+begin, buf+bufLen).
91 size_t uintToOctal(char* buffer, size_t bufLen, Uint v) {
92 auto& repr = formatOctal;
93 // 'v >>= 7, v >>= 2' is no more than a work around to get rid of shift size
94 // warning when Uint = uint8_t (it's false as v >= 512 implies sizeof(v) > 1).
95 for (; !less_than<unsigned, 512>(v); v >>= 7, v >>= 2) {
98 buffer[bufLen] = repr[b][0];
99 buffer[bufLen + 1] = repr[b][1];
100 buffer[bufLen + 2] = repr[b][2];
102 buffer[--bufLen] = repr[v][2];
104 buffer[--bufLen] = repr[v][1];
107 buffer[--bufLen] = repr[v][0];
113 * Convert an unsigned to binary.
115 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
116 * the supplied buffer and returns the offset of the beginning of the string
117 * from the start of the buffer. The formatted string will be in range
118 * [buf+begin, buf+bufLen).
120 template <class Uint>
121 size_t uintToBinary(char* buffer, size_t bufLen, Uint v) {
122 auto& repr = formatBinary;
124 buffer[--bufLen] = '0';
127 for (; v; v >>= 7, v >>= 1) {
130 memcpy(buffer + bufLen, &(repr[b][0]), 8);
132 while (buffer[bufLen] == '0') {
138 } // namespace detail
141 template <bool containerMode, class... Args>
142 Formatter<containerMode, Args...>::Formatter(StringPiece str, Args&&... args)
144 values_(FormatValue<typename std::decay<Args>::type>(
145 std::forward<Args>(args))...) {
146 static_assert(!containerMode || sizeof...(Args) == 1,
147 "Exactly one argument required in container mode");
150 template <bool containerMode, class... Args>
151 template <class Output>
152 void Formatter<containerMode, Args...>::operator()(Output& out) const {
153 auto p = str_.begin();
154 auto end = str_.end();
156 // Copy raw string (without format specifiers) to output;
157 // not as simple as we'd like, as we still need to translate "}}" to "}"
158 // and throw if we see any lone "}"
159 auto outputString = [&out] (StringPiece s) {
163 auto q = static_cast<const char*>(memchr(p, '}', end - p));
165 out(StringPiece(p, end));
169 out(StringPiece(p, q));
172 if (p == end || *p != '}') {
173 throw std::invalid_argument(
174 "folly::format: single '}' in format string");
181 bool hasDefaultArgIndex = false;
182 bool hasExplicitArgIndex = false;
184 auto q = static_cast<const char*>(memchr(p, '{', end - p));
186 outputString(StringPiece(p, end));
189 outputString(StringPiece(p, q));
193 throw std::invalid_argument(
194 "folly::format: '}' at end of format string");
199 out(StringPiece(p, 1));
205 q = static_cast<const char*>(memchr(p, '}', end - p));
207 throw std::invalid_argument("folly::format: missing ending '}'");
209 FormatArg arg(StringPiece(p, q));
213 auto piece = arg.splitKey<true>(); // empty key component is okay
214 if (containerMode) { // static
216 arg.setNextIntKey(nextArg++);
217 hasDefaultArgIndex = true;
219 arg.setNextKey(piece);
220 hasExplicitArgIndex = true;
224 argIndex = nextArg++;
225 hasDefaultArgIndex = true;
228 argIndex = to<int>(piece);
229 } catch (const std::out_of_range& e) {
230 arg.error("argument index must be integer");
232 arg.enforce(argIndex >= 0, "argument index must be non-negative");
233 hasExplicitArgIndex = true;
237 if (hasDefaultArgIndex && hasExplicitArgIndex) {
238 throw std::invalid_argument(
239 "folly::format: may not have both default and explicit arg indexes");
242 doFormat(argIndex, arg, out);
246 template <bool containerMode, class... Args>
247 void writeTo(FILE* fp, const Formatter<containerMode, Args...>& formatter) {
248 auto writer = [fp] (StringPiece sp) {
249 ssize_t n = fwrite(sp.data(), 1, sp.size(), fp);
251 throwSystemError("Formatter writeTo", "fwrite failed");
257 namespace format_value {
259 template <class FormatCallback>
260 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb) {
261 if (arg.precision != FormatArg::kDefaultPrecision &&
262 val.size() > arg.precision) {
263 val.reset(val.data(), arg.precision);
266 constexpr int padBufSize = 128;
267 char padBuf[padBufSize];
269 // Output padding, no more than padBufSize at once
270 auto pad = [&padBuf, &cb, padBufSize] (int chars) {
272 int n = std::min(chars, padBufSize);
273 cb(StringPiece(padBuf, n));
278 int padRemaining = 0;
279 if (arg.width != FormatArg::kDefaultWidth && val.size() < arg.width) {
280 char fill = arg.fill == FormatArg::kDefaultFill ? ' ' : arg.fill;
281 int padChars = arg.width - val.size();
282 memset(padBuf, fill, std::min(padBufSize, padChars));
285 case FormatArg::Align::DEFAULT:
286 case FormatArg::Align::LEFT:
287 padRemaining = padChars;
289 case FormatArg::Align::CENTER:
291 padRemaining = padChars - padChars / 2;
293 case FormatArg::Align::RIGHT:
294 case FormatArg::Align::PAD_AFTER_SIGN:
310 template <class FormatCallback>
311 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
312 FormatCallback& cb) {
313 // precision means something different for numbers
314 arg.precision = FormatArg::kDefaultPrecision;
315 if (arg.align == FormatArg::Align::DEFAULT) {
316 arg.align = FormatArg::Align::RIGHT;
317 } else if (prefixLen && arg.align == FormatArg::Align::PAD_AFTER_SIGN) {
318 // Split off the prefix, then do any padding if necessary
319 cb(val.subpiece(0, prefixLen));
320 val.advance(prefixLen);
321 arg.width = std::max(arg.width - prefixLen, 0);
323 format_value::formatString(val, arg, cb);
326 template <class FormatCallback, bool containerMode, class... Args>
327 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
329 FormatCallback& cb) {
330 if (arg.width == FormatArg::kDefaultWidth &&
331 arg.precision == FormatArg::kDefaultPrecision) {
334 } else if (arg.align != FormatArg::Align::LEFT &&
335 arg.align != FormatArg::Align::DEFAULT) {
336 // We can only avoid creating a temporary string if we align left,
337 // as we'd need to know the size beforehand otherwise
338 format_value::formatString(formatter.fbstr(), arg, cb);
340 auto fn = [&arg, &cb] (StringPiece sp) mutable {
341 int sz = static_cast<int>(sp.size());
342 if (arg.precision != FormatArg::kDefaultPrecision) {
343 sz = std::min(arg.precision, sz);
344 sp.reset(sp.data(), sz);
349 if (arg.width != FormatArg::kDefaultWidth) {
350 arg.width = std::max(arg.width - sz, 0);
355 if (arg.width != FormatArg::kDefaultWidth && arg.width != 0) {
356 // Rely on formatString to do appropriate padding
357 format_value::formatString(StringPiece(), arg, cb);
362 } // namespace format_value
364 // Definitions for default FormatValue classes
366 // Integral types (except bool)
369 T, typename std::enable_if<
370 std::is_integral<T>::value &&
371 !std::is_same<T, bool>::value>::type>
374 explicit FormatValue(T val) : val_(val) { }
375 template <class FormatCallback>
376 void format(FormatArg& arg, FormatCallback& cb) const {
377 arg.validate(FormatArg::Type::INTEGER);
381 template <class FormatCallback>
382 void doFormat(FormatArg& arg, FormatCallback& cb) const {
383 char presentation = arg.presentation;
384 if (presentation == FormatArg::kDefaultPresentation) {
385 presentation = std::is_same<T, char>::value ? 'c' : 'd';
388 // Do all work as unsigned, we'll add the prefix ('0' or '0x' if necessary)
389 // and sign ourselves.
390 typedef typename std::make_unsigned<T>::type UT;
393 if (std::is_signed<T>::value) {
394 if (folly::is_negative(val_)) {
395 uval = static_cast<UT>(-val_);
398 uval = static_cast<UT>(val_);
400 case FormatArg::Sign::PLUS_OR_MINUS:
403 case FormatArg::Sign::SPACE_OR_MINUS:
415 arg.enforce(arg.sign == FormatArg::Sign::DEFAULT,
416 "sign specifications not allowed for unsigned values");
420 // #x: 0x prefix + 16 bytes = 18 bytes
421 // #o: 0 prefix + 22 bytes = 23 bytes
422 // #b: 0b prefix + 64 bytes = 65 bytes
423 // ,d: 26 bytes (including thousands separators!)
425 // + 3 for sign and prefix shenanigans (see below)
426 constexpr size_t valBufSize = 69;
427 char valBuf[valBufSize];
428 char* valBufBegin = nullptr;
429 char* valBufEnd = nullptr;
432 auto useSprintf = [&] (const char* format) mutable {
433 valBufBegin = valBuf + 3; // room for sign and base prefix
434 valBufEnd = valBufBegin + sprintf(valBufBegin, format,
435 static_cast<uintmax_t>(uval));
440 switch (presentation) {
441 case 'n': // TODO(tudorb): locale awareness?
443 arg.enforce(!arg.basePrefix,
444 "base prefix not allowed with '", presentation,
446 if (arg.thousandsSeparator) {
449 // Use uintToBuffer, faster than sprintf
450 valBufBegin = valBuf + 3;
451 valBufEnd = valBufBegin + uint64ToBufferUnsafe(uval, valBufBegin);
455 arg.enforce(!arg.basePrefix,
456 "base prefix not allowed with '", presentation,
458 arg.enforce(!arg.thousandsSeparator,
459 "thousands separator (',') not allowed with '",
460 presentation, "' specifier");
461 valBufBegin = valBuf + 3;
462 *valBufBegin = static_cast<char>(uval);
463 valBufEnd = valBufBegin + 1;
467 arg.enforce(!arg.thousandsSeparator,
468 "thousands separator (',') not allowed with '",
469 presentation, "' specifier");
470 valBufEnd = valBuf + valBufSize - 1;
471 valBufBegin = valBuf + detail::uintToOctal(valBuf, valBufSize - 1, uval);
472 if (arg.basePrefix) {
473 *--valBufBegin = '0';
478 arg.enforce(!arg.thousandsSeparator,
479 "thousands separator (',') not allowed with '",
480 presentation, "' specifier");
481 valBufEnd = valBuf + valBufSize - 1;
482 valBufBegin = valBuf + detail::uintToHexLower(valBuf, valBufSize - 1,
484 if (arg.basePrefix) {
485 *--valBufBegin = 'x';
486 *--valBufBegin = '0';
491 arg.enforce(!arg.thousandsSeparator,
492 "thousands separator (',') not allowed with '",
493 presentation, "' specifier");
494 valBufEnd = valBuf + valBufSize - 1;
495 valBufBegin = valBuf + detail::uintToHexUpper(valBuf, valBufSize - 1,
497 if (arg.basePrefix) {
498 *--valBufBegin = 'X';
499 *--valBufBegin = '0';
505 arg.enforce(!arg.thousandsSeparator,
506 "thousands separator (',') not allowed with '",
507 presentation, "' specifier");
508 valBufEnd = valBuf + valBufSize - 1;
509 valBufBegin = valBuf + detail::uintToBinary(valBuf, valBufSize - 1,
511 if (arg.basePrefix) {
512 *--valBufBegin = presentation; // 0b or 0B
513 *--valBufBegin = '0';
518 arg.error("invalid specifier '", presentation, "'");
522 *--valBufBegin = sign;
526 format_value::formatNumber(StringPiece(valBufBegin, valBufEnd), prefixLen,
536 class FormatValue<bool> {
538 explicit FormatValue(bool val) : val_(val) { }
540 template <class FormatCallback>
541 void format(FormatArg& arg, FormatCallback& cb) const {
542 if (arg.presentation == FormatArg::kDefaultPresentation) {
543 arg.validate(FormatArg::Type::OTHER);
544 format_value::formatString(val_ ? "true" : "false", arg, cb);
546 FormatValue<int>(val_).format(arg, cb);
556 class FormatValue<double> {
558 explicit FormatValue(double val) : val_(val) { }
560 template <class FormatCallback>
561 void format(FormatArg& arg, FormatCallback& cb) const {
562 using ::double_conversion::DoubleToStringConverter;
563 using ::double_conversion::StringBuilder;
565 arg.validate(FormatArg::Type::FLOAT);
567 if (arg.presentation == FormatArg::kDefaultPresentation) {
568 arg.presentation = 'g';
571 const char* infinitySymbol = isupper(arg.presentation) ? "INF" : "inf";
572 const char* nanSymbol = isupper(arg.presentation) ? "NAN" : "nan";
573 char exponentSymbol = isupper(arg.presentation) ? 'E' : 'e';
575 if (arg.precision == FormatArg::kDefaultPrecision) {
579 // 2+: for null terminator and optional sign shenanigans.
580 char buf[2 + std::max({
581 (2 + DoubleToStringConverter::kMaxFixedDigitsBeforePoint +
582 DoubleToStringConverter::kMaxFixedDigitsAfterPoint),
583 (8 + DoubleToStringConverter::kMaxExponentialDigits),
584 (7 + DoubleToStringConverter::kMaxPrecisionDigits)})];
585 StringBuilder builder(buf + 1, sizeof(buf) - 1);
589 case FormatArg::Sign::PLUS_OR_MINUS:
592 case FormatArg::Sign::SPACE_OR_MINUS:
601 switch (arg.presentation) {
608 DoubleToStringConverter::kMaxFixedDigitsAfterPoint) {
609 arg.precision = DoubleToStringConverter::kMaxFixedDigitsAfterPoint;
611 DoubleToStringConverter conv(
612 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,
618 arg.enforce(conv.ToFixed(val, arg.precision, &builder),
619 "fixed double conversion failed");
625 if (arg.precision > DoubleToStringConverter::kMaxExponentialDigits) {
626 arg.precision = DoubleToStringConverter::kMaxExponentialDigits;
629 DoubleToStringConverter conv(
630 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,
636 arg.enforce(conv.ToExponential(val, arg.precision, &builder));
639 case 'n': // should be locale-aware, but isn't
643 if (arg.precision < DoubleToStringConverter::kMinPrecisionDigits) {
644 arg.precision = DoubleToStringConverter::kMinPrecisionDigits;
645 } else if (arg.precision >
646 DoubleToStringConverter::kMaxPrecisionDigits) {
647 arg.precision = DoubleToStringConverter::kMaxPrecisionDigits;
649 DoubleToStringConverter conv(
650 DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,
656 arg.enforce(conv.ToShortest(val, &builder));
660 arg.error("invalid specifier '", arg.presentation, "'");
663 int len = builder.position();
667 // Add '+' or ' ' sign if needed
669 // anything that's neither negative nor nan
671 if (plusSign && (*p != '-' && *p != 'n' && *p != 'N')) {
675 } else if (*p == '-') {
679 format_value::formatNumber(StringPiece(p, len), prefixLen, arg, cb);
686 // float (defer to double)
688 class FormatValue<float> {
690 explicit FormatValue(float val) : val_(val) { }
692 template <class FormatCallback>
693 void format(FormatArg& arg, FormatCallback& cb) const {
694 FormatValue<double>(val_).format(arg, cb);
701 // Sring-y types (implicitly convertible to StringPiece, except char*)
704 T, typename std::enable_if<
705 (!std::is_pointer<T>::value ||
706 !std::is_same<char, typename std::decay<
707 typename std::remove_pointer<T>::type>::type>::value) &&
708 std::is_convertible<T, StringPiece>::value>::type>
711 explicit FormatValue(StringPiece val) : val_(val) { }
713 template <class FormatCallback>
714 void format(FormatArg& arg, FormatCallback& cb) const {
715 if (arg.keyEmpty()) {
716 arg.validate(FormatArg::Type::OTHER);
717 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation ||
718 arg.presentation == 's',
719 "invalid specifier '", arg.presentation, "'");
720 format_value::formatString(val_, arg, cb);
722 FormatValue<char>(val_.at(arg.splitIntKey())).format(arg, cb);
732 class FormatValue<std::nullptr_t> {
734 explicit FormatValue(std::nullptr_t) { }
736 template <class FormatCallback>
737 void format(FormatArg& arg, FormatCallback& cb) const {
738 arg.validate(FormatArg::Type::OTHER);
739 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
740 "invalid specifier '", arg.presentation, "'");
741 format_value::formatString("(null)", arg, cb);
745 // Partial specialization of FormatValue for char*
749 typename std::enable_if<
750 std::is_same<char, typename std::decay<T>::type>::value>::type>
753 explicit FormatValue(T* val) : val_(val) { }
755 template <class FormatCallback>
756 void format(FormatArg& arg, FormatCallback& cb) const {
757 if (arg.keyEmpty()) {
759 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
761 FormatValue<StringPiece>(val_).format(arg, cb);
764 FormatValue<typename std::decay<T>::type>(
765 val_[arg.splitIntKey()]).format(arg, cb);
773 // Partial specialization of FormatValue for void*
777 typename std::enable_if<
778 std::is_same<void, typename std::decay<T>::type>::value>::type>
781 explicit FormatValue(T* val) : val_(val) { }
783 template <class FormatCallback>
784 void format(FormatArg& arg, FormatCallback& cb) const {
786 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
788 // Print as a pointer, in hex.
789 arg.validate(FormatArg::Type::OTHER);
790 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
791 "invalid specifier '", arg.presentation, "'");
792 arg.basePrefix = true;
793 arg.presentation = 'x';
794 if (arg.align == FormatArg::Align::DEFAULT) {
795 arg.align = FormatArg::Align::LEFT;
797 FormatValue<uintptr_t>(
798 reinterpret_cast<uintptr_t>(val_)).doFormat(arg, cb);
806 template <class T, class = void>
807 class TryFormatValue {
809 template <class FormatCallback>
810 static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
811 arg.error("No formatter available for this type");
816 class TryFormatValue<
818 typename std::enable_if<
819 0 < sizeof(FormatValue<typename std::decay<T>::type>)>::type>
822 template <class FormatCallback>
823 static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
824 FormatValue<typename std::decay<T>::type>(value).format(arg, cb);
828 // Partial specialization of FormatValue for other pointers
832 typename std::enable_if<
833 !std::is_same<char, typename std::decay<T>::type>::value &&
834 !std::is_same<void, typename std::decay<T>::type>::value>::type>
837 explicit FormatValue(T* val) : val_(val) { }
839 template <class FormatCallback>
840 void format(FormatArg& arg, FormatCallback& cb) const {
841 if (arg.keyEmpty()) {
842 FormatValue<void*>((void*)val_).format(arg, cb);
844 TryFormatValue<T>::formatOrFail(val_[arg.splitIntKey()], arg, cb);
853 // Shortcut, so we don't have to use enable_if everywhere
854 struct FormatTraitsBase {
855 typedef void enabled;
858 // Traits that define enabled, value_type, and at() for anything
859 // indexable with integral keys: pointers, arrays, vectors, and maps
860 // with integral keys
861 template <class T, class Enable=void> struct IndexableTraits;
863 // Base class for sequences (vectors, deques)
865 struct IndexableTraitsSeq : public FormatTraitsBase {
866 typedef C container_type;
867 typedef typename C::value_type value_type;
868 static const value_type& at(const C& c, int idx) {
873 // Base class for associative types (maps)
875 struct IndexableTraitsAssoc : public FormatTraitsBase {
876 typedef typename C::value_type::second_type value_type;
877 static const value_type& at(const C& c, int idx) {
878 return c.at(static_cast<typename C::key_type>(idx));
883 template <class T, size_t N>
884 struct IndexableTraits<std::array<T, N>>
885 : public IndexableTraitsSeq<std::array<T, N>> {
889 template <class T, class A>
890 struct IndexableTraits<std::vector<T, A>>
891 : public IndexableTraitsSeq<std::vector<T, A>> {
895 template <class T, class A>
896 struct IndexableTraits<std::deque<T, A>>
897 : public IndexableTraitsSeq<std::deque<T, A>> {
901 template <class T, class A>
902 struct IndexableTraits<fbvector<T, A>>
903 : public IndexableTraitsSeq<fbvector<T, A>> {
907 template <class T, size_t M, class A, class B, class C>
908 struct IndexableTraits<small_vector<T, M, A, B, C>>
909 : public IndexableTraitsSeq<small_vector<T, M, A, B, C>> {
912 // std::map with integral keys
913 template <class K, class T, class C, class A>
914 struct IndexableTraits<
915 std::map<K, T, C, A>,
916 typename std::enable_if<std::is_integral<K>::value>::type>
917 : public IndexableTraitsAssoc<std::map<K, T, C, A>> {
920 // std::unordered_map with integral keys
921 template <class K, class T, class H, class E, class A>
922 struct IndexableTraits<
923 std::unordered_map<K, T, H, E, A>,
924 typename std::enable_if<std::is_integral<K>::value>::type>
925 : public IndexableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
928 } // namespace detail
930 // Partial specialization of FormatValue for integer-indexable containers
934 typename detail::IndexableTraits<T>::enabled> {
936 explicit FormatValue(const T& val) : val_(val) { }
938 template <class FormatCallback>
939 void format(FormatArg& arg, FormatCallback& cb) const {
940 FormatValue<typename std::decay<
941 typename detail::IndexableTraits<T>::value_type>::type>(
942 detail::IndexableTraits<T>::at(
943 val_, arg.splitIntKey())).format(arg, cb);
952 // Define enabled, key_type, convert from StringPiece to the key types
954 template <class T> struct KeyFromStringPiece;
958 struct KeyFromStringPiece<std::string> : public FormatTraitsBase {
959 typedef std::string key_type;
960 static std::string convert(StringPiece s) {
963 typedef void enabled;
968 struct KeyFromStringPiece<fbstring> : public FormatTraitsBase {
969 typedef fbstring key_type;
970 static fbstring convert(StringPiece s) {
971 return s.toFbstring();
977 struct KeyFromStringPiece<StringPiece> : public FormatTraitsBase {
978 typedef StringPiece key_type;
979 static StringPiece convert(StringPiece s) {
984 // Base class for associative types keyed by strings
985 template <class T> struct KeyableTraitsAssoc : public FormatTraitsBase {
986 typedef typename T::key_type key_type;
987 typedef typename T::value_type::second_type value_type;
988 static const value_type& at(const T& map, StringPiece key) {
989 return map.at(KeyFromStringPiece<key_type>::convert(key));
993 // Define enabled, key_type, value_type, at() for supported string-keyed
995 template <class T, class Enabled=void> struct KeyableTraits;
997 // std::map with string key
998 template <class K, class T, class C, class A>
999 struct KeyableTraits<
1000 std::map<K, T, C, A>,
1001 typename KeyFromStringPiece<K>::enabled>
1002 : public KeyableTraitsAssoc<std::map<K, T, C, A>> {
1005 // std::unordered_map with string key
1006 template <class K, class T, class H, class E, class A>
1007 struct KeyableTraits<
1008 std::unordered_map<K, T, H, E, A>,
1009 typename KeyFromStringPiece<K>::enabled>
1010 : public KeyableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
1013 } // namespace detail
1015 // Partial specialization of FormatValue for string-keyed containers
1019 typename detail::KeyableTraits<T>::enabled> {
1021 explicit FormatValue(const T& val) : val_(val) { }
1023 template <class FormatCallback>
1024 void format(FormatArg& arg, FormatCallback& cb) const {
1025 FormatValue<typename std::decay<
1026 typename detail::KeyableTraits<T>::value_type>::type>(
1027 detail::KeyableTraits<T>::at(
1028 val_, arg.splitKey())).format(arg, cb);
1035 // Partial specialization of FormatValue for pairs
1036 template <class A, class B>
1037 class FormatValue<std::pair<A, B>> {
1039 explicit FormatValue(const std::pair<A, B>& val) : val_(val) { }
1041 template <class FormatCallback>
1042 void format(FormatArg& arg, FormatCallback& cb) const {
1043 int key = arg.splitIntKey();
1046 FormatValue<typename std::decay<A>::type>(val_.first).format(arg, cb);
1049 FormatValue<typename std::decay<B>::type>(val_.second).format(arg, cb);
1052 arg.error("invalid index for pair");
1057 const std::pair<A, B>& val_;
1060 // Partial specialization of FormatValue for tuples
1061 template <class... Args>
1062 class FormatValue<std::tuple<Args...>> {
1063 typedef std::tuple<Args...> Tuple;
1065 explicit FormatValue(const Tuple& val) : val_(val) { }
1067 template <class FormatCallback>
1068 void format(FormatArg& arg, FormatCallback& cb) const {
1069 int key = arg.splitIntKey();
1070 arg.enforce(key >= 0, "tuple index must be non-negative");
1071 doFormat(key, arg, cb);
1075 static constexpr size_t valueCount = std::tuple_size<Tuple>::value;
1077 template <size_t K, class Callback>
1078 typename std::enable_if<K == valueCount>::type
1079 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1080 arg.enforce("tuple index out of range, max=", i);
1083 template <size_t K, class Callback>
1084 typename std::enable_if<(K < valueCount)>::type
1085 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1087 FormatValue<typename std::decay<
1088 typename std::tuple_element<K, Tuple>::type>::type>(
1089 std::get<K>(val_)).format(arg, cb);
1091 doFormatFrom<K+1>(i, arg, cb);
1095 template <class Callback>
1096 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
1097 return doFormatFrom<0>(i, arg, cb);
1103 // Partial specialization of FormatValue for nested Formatters
1104 template <bool containerMode, class... Args>
1105 class FormatValue<Formatter<containerMode, Args...>, void> {
1106 typedef Formatter<containerMode, Args...> FormatterValue;
1108 explicit FormatValue(const FormatterValue& f) : f_(f) { }
1110 template <class FormatCallback>
1111 void format(FormatArg& arg, FormatCallback& cb) const {
1112 format_value::formatFormatter(f_, arg, cb);
1115 const FormatterValue& f_;
1119 * Formatter objects can be appended to strings, and therefore they're
1120 * compatible with folly::toAppend and folly::to.
1122 template <class Tgt, bool containerMode, class... Args>
1123 typename std::enable_if<
1124 IsSomeString<Tgt>::value>::type
1125 toAppend(const Formatter<containerMode, Args...>& value, Tgt * result) {
1126 value.appendTo(*result);
1129 } // namespace folly