2 * Copyright 2017 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 #include <unordered_map>
28 #include <folly/Exception.h>
29 #include <folly/FormatTraits.h>
30 #include <folly/Traits.h>
31 #include <folly/portability/Windows.h>
33 // Ignore -Wformat-nonliteral warnings within this file
35 FOLLY_GCC_DISABLE_WARNING("-Wformat-nonliteral")
41 // Updates the end of the buffer after the comma separators have been added.
42 void insertThousandsGroupingUnsafe(char* start_buffer, char** end_buffer);
44 extern const char formatHexUpper[256][2];
45 extern const char formatHexLower[256][2];
46 extern const char formatOctal[512][3];
47 extern const char formatBinary[256][8];
49 const size_t kMaxHexLength = 2 * sizeof(uintmax_t);
50 const size_t kMaxOctalLength = 3 * sizeof(uintmax_t);
51 const size_t kMaxBinaryLength = 8 * sizeof(uintmax_t);
54 * Convert an unsigned to hex, using repr (which maps from each possible
55 * 2-hex-bytes value to the 2-character representation).
57 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
58 * the supplied buffer and returns the offset of the beginning of the string
59 * from the start of the buffer. The formatted string will be in range
60 * [buf+begin, buf+bufLen).
64 uintToHex(char* buffer, size_t bufLen, Uint v, const char (&repr)[256][2]) {
65 // 'v >>= 7, v >>= 1' is no more than a work around to get rid of shift size
66 // warning when Uint = uint8_t (it's false as v >= 256 implies sizeof(v) > 1).
67 for (; !less_than<unsigned, 256>(v); v >>= 7, v >>= 1) {
70 buffer[bufLen] = repr[b][0];
71 buffer[bufLen + 1] = repr[b][1];
73 buffer[--bufLen] = repr[v][1];
75 buffer[--bufLen] = repr[v][0];
81 * Convert an unsigned to hex, using lower-case letters for the digits
82 * above 9. See the comments for uintToHex.
85 inline size_t uintToHexLower(char* buffer, size_t bufLen, Uint v) {
86 return uintToHex(buffer, bufLen, v, formatHexLower);
90 * Convert an unsigned to hex, using upper-case letters for the digits
91 * above 9. See the comments for uintToHex.
94 inline size_t uintToHexUpper(char* buffer, size_t bufLen, Uint v) {
95 return uintToHex(buffer, bufLen, v, formatHexUpper);
99 * Convert an unsigned to octal.
101 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
102 * the supplied buffer and returns the offset of the beginning of the string
103 * from the start of the buffer. The formatted string will be in range
104 * [buf+begin, buf+bufLen).
106 template <class Uint>
107 size_t uintToOctal(char* buffer, size_t bufLen, Uint v) {
108 auto& repr = formatOctal;
109 // 'v >>= 7, v >>= 2' is no more than a work around to get rid of shift size
110 // warning when Uint = uint8_t (it's false as v >= 512 implies sizeof(v) > 1).
111 for (; !less_than<unsigned, 512>(v); v >>= 7, v >>= 2) {
114 buffer[bufLen] = repr[b][0];
115 buffer[bufLen + 1] = repr[b][1];
116 buffer[bufLen + 2] = repr[b][2];
118 buffer[--bufLen] = repr[v][2];
120 buffer[--bufLen] = repr[v][1];
123 buffer[--bufLen] = repr[v][0];
129 * Convert an unsigned to binary.
131 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
132 * the supplied buffer and returns the offset of the beginning of the string
133 * from the start of the buffer. The formatted string will be in range
134 * [buf+begin, buf+bufLen).
136 template <class Uint>
137 size_t uintToBinary(char* buffer, size_t bufLen, Uint v) {
138 auto& repr = formatBinary;
140 buffer[--bufLen] = '0';
143 for (; v; v >>= 7, v >>= 1) {
146 memcpy(buffer + bufLen, &(repr[b][0]), 8);
148 while (buffer[bufLen] == '0') {
154 } // namespace detail
156 template <class Derived, bool containerMode, class... Args>
157 BaseFormatter<Derived, containerMode, Args...>::BaseFormatter(
160 : str_(str), values_(std::forward<Args>(args)...) {}
162 template <class Derived, bool containerMode, class... Args>
163 template <class Output>
164 void BaseFormatter<Derived, containerMode, Args...>::operator()(
166 // Copy raw string (without format specifiers) to output;
167 // not as simple as we'd like, as we still need to translate "}}" to "}"
168 // and throw if we see any lone "}"
169 auto outputString = [&out](StringPiece s) {
173 auto q = static_cast<const char*>(memchr(p, '}', size_t(end - p)));
175 out(StringPiece(p, end));
179 out(StringPiece(p, q));
182 if (p == end || *p != '}') {
183 throwBadFormatArg("folly::format: single '}' in format string");
189 auto p = str_.begin();
190 auto end = str_.end();
193 bool hasDefaultArgIndex = false;
194 bool hasExplicitArgIndex = false;
196 auto q = static_cast<const char*>(memchr(p, '{', size_t(end - p)));
198 outputString(StringPiece(p, end));
201 outputString(StringPiece(p, q));
205 throwBadFormatArg("folly::format: '}' at end of format string");
210 out(StringPiece(p, 1));
216 q = static_cast<const char*>(memchr(p, '}', size_t(end - p)));
218 throwBadFormatArg("folly::format: missing ending '}'");
220 FormatArg arg(StringPiece(p, q));
224 auto piece = arg.splitKey<true>(); // empty key component is okay
225 if (containerMode) { // static
227 arg.width != FormatArg::kDynamicWidth,
228 "dynamic field width not supported in vformat()");
230 arg.setNextIntKey(nextArg++);
231 hasDefaultArgIndex = true;
233 arg.setNextKey(piece);
234 hasExplicitArgIndex = true;
238 if (arg.width == FormatArg::kDynamicWidth) {
240 arg.widthIndex == FormatArg::kNoIndex,
241 "cannot provide width arg index without value arg index");
242 int sizeArg = nextArg++;
243 arg.width = asDerived().getSizeArg(size_t(sizeArg), arg);
246 argIndex = nextArg++;
247 hasDefaultArgIndex = true;
249 if (arg.width == FormatArg::kDynamicWidth) {
251 arg.widthIndex != FormatArg::kNoIndex,
252 "cannot provide value arg index without width arg index");
253 arg.width = asDerived().getSizeArg(size_t(arg.widthIndex), arg);
257 argIndex = to<int>(piece);
258 } catch (const std::out_of_range&) {
259 arg.error("argument index must be integer");
261 arg.enforce(argIndex >= 0, "argument index must be non-negative");
262 hasExplicitArgIndex = true;
266 if (hasDefaultArgIndex && hasExplicitArgIndex) {
268 "folly::format: may not have both default and explicit arg indexes");
271 asDerived().doFormat(size_t(argIndex), arg, out);
275 template <class Derived, bool containerMode, class... Args>
278 const BaseFormatter<Derived, containerMode, Args...>& formatter) {
279 auto writer = [fp](StringPiece sp) {
280 size_t n = fwrite(sp.data(), 1, sp.size(), fp);
282 throwSystemError("Formatter writeTo", "fwrite failed");
288 namespace format_value {
290 template <class FormatCallback>
291 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb) {
292 if (arg.width != FormatArg::kDefaultWidth && arg.width < 0) {
293 throwBadFormatArg("folly::format: invalid width");
295 if (arg.precision != FormatArg::kDefaultPrecision && arg.precision < 0) {
296 throwBadFormatArg("folly::format: invalid precision");
299 if (arg.precision != FormatArg::kDefaultPrecision &&
300 val.size() > static_cast<size_t>(arg.precision)) {
301 val.reset(val.data(), static_cast<size_t>(arg.precision));
304 constexpr int padBufSize = 128;
305 char padBuf[padBufSize];
307 // Output padding, no more than padBufSize at once
308 auto pad = [&padBuf, &cb, padBufSize](int chars) {
310 int n = std::min(chars, padBufSize);
311 cb(StringPiece(padBuf, size_t(n)));
316 int padRemaining = 0;
317 if (arg.width != FormatArg::kDefaultWidth &&
318 val.size() < static_cast<size_t>(arg.width)) {
319 char fill = arg.fill == FormatArg::kDefaultFill ? ' ' : arg.fill;
320 int padChars = static_cast<int>(arg.width - val.size());
321 memset(padBuf, fill, size_t(std::min(padBufSize, padChars)));
324 case FormatArg::Align::DEFAULT:
325 case FormatArg::Align::LEFT:
326 padRemaining = padChars;
328 case FormatArg::Align::CENTER:
330 padRemaining = padChars - padChars / 2;
332 case FormatArg::Align::RIGHT:
333 case FormatArg::Align::PAD_AFTER_SIGN:
349 template <class FormatCallback>
354 FormatCallback& cb) {
355 // precision means something different for numbers
356 arg.precision = FormatArg::kDefaultPrecision;
357 if (arg.align == FormatArg::Align::DEFAULT) {
358 arg.align = FormatArg::Align::RIGHT;
359 } else if (prefixLen && arg.align == FormatArg::Align::PAD_AFTER_SIGN) {
360 // Split off the prefix, then do any padding if necessary
361 cb(val.subpiece(0, size_t(prefixLen)));
362 val.advance(size_t(prefixLen));
363 arg.width = std::max(arg.width - prefixLen, 0);
365 format_value::formatString(val, arg, cb);
369 class FormatCallback,
373 void formatFormatter(
374 const BaseFormatter<Derived, containerMode, Args...>& formatter,
376 FormatCallback& cb) {
377 if (arg.width == FormatArg::kDefaultWidth &&
378 arg.precision == FormatArg::kDefaultPrecision) {
382 arg.align != FormatArg::Align::LEFT &&
383 arg.align != FormatArg::Align::DEFAULT) {
384 // We can only avoid creating a temporary string if we align left,
385 // as we'd need to know the size beforehand otherwise
386 format_value::formatString(formatter.fbstr(), arg, cb);
388 auto fn = [&arg, &cb](StringPiece sp) mutable {
389 int sz = static_cast<int>(sp.size());
390 if (arg.precision != FormatArg::kDefaultPrecision) {
391 sz = std::min(arg.precision, sz);
392 sp.reset(sp.data(), size_t(sz));
397 if (arg.width != FormatArg::kDefaultWidth) {
398 arg.width = std::max(arg.width - sz, 0);
403 if (arg.width != FormatArg::kDefaultWidth && arg.width != 0) {
404 // Rely on formatString to do appropriate padding
405 format_value::formatString(StringPiece(), arg, cb);
410 } // namespace format_value
412 // Definitions for default FormatValue classes
414 // Integral types (except bool)
418 typename std::enable_if<
419 std::is_integral<T>::value && !std::is_same<T, bool>::value>::type> {
421 explicit FormatValue(T val) : val_(val) {}
427 template <class FormatCallback>
428 void format(FormatArg& arg, FormatCallback& cb) const {
429 arg.validate(FormatArg::Type::INTEGER);
433 template <class FormatCallback>
434 void doFormat(FormatArg& arg, FormatCallback& cb) const {
435 char presentation = arg.presentation;
436 if (presentation == FormatArg::kDefaultPresentation) {
437 presentation = std::is_same<T, char>::value ? 'c' : 'd';
440 // Do all work as unsigned, we'll add the prefix ('0' or '0x' if necessary)
441 // and sign ourselves.
442 typedef typename std::make_unsigned<T>::type UT;
445 if (std::is_signed<T>::value) {
446 if (folly::is_negative(val_)) {
447 uval = UT(-static_cast<UT>(val_));
450 uval = static_cast<UT>(val_);
452 case FormatArg::Sign::PLUS_OR_MINUS:
455 case FormatArg::Sign::SPACE_OR_MINUS:
464 uval = static_cast<UT>(val_);
468 arg.sign == FormatArg::Sign::DEFAULT,
469 "sign specifications not allowed for unsigned values");
473 // #x: 0x prefix + 16 bytes = 18 bytes
474 // #o: 0 prefix + 22 bytes = 23 bytes
475 // #b: 0b prefix + 64 bytes = 65 bytes
476 // ,d: 26 bytes (including thousands separators!)
478 // + 3 for sign and prefix shenanigans (see below)
479 constexpr size_t valBufSize = 69;
480 char valBuf[valBufSize];
481 char* valBufBegin = nullptr;
482 char* valBufEnd = nullptr;
485 switch (presentation) {
489 "base prefix not allowed with '",
494 !arg.thousandsSeparator,
495 "cannot use ',' with the '",
499 valBufBegin = valBuf + 3; // room for sign and base prefix
500 #if defined(__ANDROID__)
503 (valBuf + valBufSize) - valBufBegin,
505 static_cast<uintmax_t>(uval));
509 size_t((valBuf + valBufSize) - valBufBegin),
511 static_cast<uintmax_t>(uval));
513 // valBufSize should always be big enough, so this should never
515 assert(len < valBuf + valBufSize - valBufBegin);
516 valBufEnd = valBufBegin + len;
522 "base prefix not allowed with '",
525 valBufBegin = valBuf + 3; // room for sign and base prefix
527 // Use uintToBuffer, faster than sprintf
528 valBufEnd = valBufBegin + uint64ToBufferUnsafe(uval, valBufBegin);
529 if (arg.thousandsSeparator) {
530 detail::insertThousandsGroupingUnsafe(valBufBegin, &valBufEnd);
536 "base prefix not allowed with '",
540 !arg.thousandsSeparator,
541 "thousands separator (',') not allowed with '",
544 valBufBegin = valBuf + 3;
545 *valBufBegin = static_cast<char>(uval);
546 valBufEnd = valBufBegin + 1;
551 !arg.thousandsSeparator,
552 "thousands separator (',') not allowed with '",
555 valBufEnd = valBuf + valBufSize - 1;
557 valBuf + detail::uintToOctal(valBuf, valBufSize - 1, uval);
558 if (arg.basePrefix) {
559 *--valBufBegin = '0';
565 !arg.thousandsSeparator,
566 "thousands separator (',') not allowed with '",
569 valBufEnd = valBuf + valBufSize - 1;
571 valBuf + detail::uintToHexLower(valBuf, valBufSize - 1, uval);
572 if (arg.basePrefix) {
573 *--valBufBegin = 'x';
574 *--valBufBegin = '0';
580 !arg.thousandsSeparator,
581 "thousands separator (',') not allowed with '",
584 valBufEnd = valBuf + valBufSize - 1;
586 valBuf + detail::uintToHexUpper(valBuf, valBufSize - 1, uval);
587 if (arg.basePrefix) {
588 *--valBufBegin = 'X';
589 *--valBufBegin = '0';
596 !arg.thousandsSeparator,
597 "thousands separator (',') not allowed with '",
600 valBufEnd = valBuf + valBufSize - 1;
602 valBuf + detail::uintToBinary(valBuf, valBufSize - 1, uval);
603 if (arg.basePrefix) {
604 *--valBufBegin = presentation; // 0b or 0B
605 *--valBufBegin = '0';
610 arg.error("invalid specifier '", presentation, "'");
614 *--valBufBegin = sign;
618 format_value::formatNumber(
619 StringPiece(valBufBegin, valBufEnd), prefixLen, arg, cb);
628 class FormatValue<bool> {
630 explicit FormatValue(bool val) : val_(val) {}
632 template <class FormatCallback>
633 void format(FormatArg& arg, FormatCallback& cb) const {
634 if (arg.presentation == FormatArg::kDefaultPresentation) {
635 arg.validate(FormatArg::Type::OTHER);
636 format_value::formatString(val_ ? "true" : "false", arg, cb);
638 FormatValue<int>(val_).format(arg, cb);
648 class FormatValue<double> {
650 explicit FormatValue(double val) : val_(val) {}
652 template <class FormatCallback>
653 void format(FormatArg& arg, FormatCallback& cb) const {
656 formatHelper(piece, prefixLen, arg);
657 format_value::formatNumber(piece, prefixLen, arg, cb);
661 void formatHelper(fbstring& piece, int& prefixLen, FormatArg& arg) const;
666 // float (defer to double)
668 class FormatValue<float> {
670 explicit FormatValue(float val) : val_(val) {}
672 template <class FormatCallback>
673 void format(FormatArg& arg, FormatCallback& cb) const {
674 FormatValue<double>(val_).format(arg, cb);
681 // String-y types (implicitly convertible to StringPiece, except char*)
685 typename std::enable_if<
686 (!std::is_pointer<T>::value ||
689 typename std::decay<typename std::remove_pointer<T>::type>::type>::
691 std::is_convertible<T, StringPiece>::value>::type> {
693 explicit FormatValue(StringPiece val) : val_(val) {}
695 template <class FormatCallback>
696 void format(FormatArg& arg, FormatCallback& cb) const {
697 if (arg.keyEmpty()) {
698 arg.validate(FormatArg::Type::OTHER);
700 arg.presentation == FormatArg::kDefaultPresentation ||
701 arg.presentation == 's',
702 "invalid specifier '",
705 format_value::formatString(val_, arg, cb);
707 FormatValue<char>(val_.at(size_t(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);
725 arg.presentation == FormatArg::kDefaultPresentation,
726 "invalid specifier '",
729 format_value::formatString("(null)", arg, cb);
733 // Partial specialization of FormatValue for char*
737 typename std::enable_if<
738 std::is_same<char, typename std::decay<T>::type>::value>::type> {
740 explicit FormatValue(T* val) : val_(val) {}
742 template <class FormatCallback>
743 void format(FormatArg& arg, FormatCallback& cb) const {
744 if (arg.keyEmpty()) {
746 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
748 FormatValue<StringPiece>(val_).format(arg, cb);
751 FormatValue<typename std::decay<T>::type>(val_[arg.splitIntKey()])
760 // Partial specialization of FormatValue for void*
764 typename std::enable_if<
765 std::is_same<void, typename std::decay<T>::type>::value>::type> {
767 explicit FormatValue(T* val) : val_(val) {}
769 template <class FormatCallback>
770 void format(FormatArg& arg, FormatCallback& cb) const {
772 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
774 // Print as a pointer, in hex.
775 arg.validate(FormatArg::Type::OTHER);
777 arg.presentation == FormatArg::kDefaultPresentation,
778 "invalid specifier '",
781 arg.basePrefix = true;
782 arg.presentation = 'x';
783 if (arg.align == FormatArg::Align::DEFAULT) {
784 arg.align = FormatArg::Align::LEFT;
786 FormatValue<uintptr_t>(reinterpret_cast<uintptr_t>(val_))
795 template <class T, class = void>
796 class TryFormatValue {
798 template <class FormatCallback>
800 formatOrFail(T& /* value */, FormatArg& arg, FormatCallback& /* cb */) {
801 arg.error("No formatter available for this type");
806 class TryFormatValue<
808 typename std::enable_if<
809 0 < sizeof(FormatValue<typename std::decay<T>::type>)>::type> {
811 template <class FormatCallback>
812 static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
813 FormatValue<typename std::decay<T>::type>(value).format(arg, cb);
817 // Partial specialization of FormatValue for other pointers
821 typename std::enable_if<
822 !std::is_same<char, typename std::decay<T>::type>::value &&
823 !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 {
829 if (arg.keyEmpty()) {
830 FormatValue<void*>((void*)val_).format(arg, cb);
832 TryFormatValue<T>::formatOrFail(val_[arg.splitIntKey()], arg, cb);
843 template <class T, size_t N>
844 struct IndexableTraits<std::array<T, N>>
845 : public IndexableTraitsSeq<std::array<T, N>> {};
848 template <class T, class A>
849 struct IndexableTraits<std::vector<T, A>>
850 : public IndexableTraitsSeq<std::vector<T, A>> {};
853 template <class T, class A>
854 struct IndexableTraits<std::deque<T, A>>
855 : public IndexableTraitsSeq<std::deque<T, A>> {};
857 // std::map with integral keys
858 template <class K, class T, class C, class A>
859 struct IndexableTraits<
860 std::map<K, T, C, A>,
861 typename std::enable_if<std::is_integral<K>::value>::type>
862 : public IndexableTraitsAssoc<std::map<K, T, C, A>> {};
864 // std::unordered_map with integral keys
865 template <class K, class T, class H, class E, class A>
866 struct IndexableTraits<
867 std::unordered_map<K, T, H, E, A>,
868 typename std::enable_if<std::is_integral<K>::value>::type>
869 : public IndexableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {};
871 } // namespace detail
873 // Partial specialization of FormatValue for integer-indexable containers
875 class FormatValue<T, typename detail::IndexableTraits<T>::enabled> {
877 explicit FormatValue(const T& val) : val_(val) {}
879 template <class FormatCallback>
880 void format(FormatArg& arg, FormatCallback& cb) const {
881 FormatValue<typename std::decay<
882 typename detail::IndexableTraits<T>::value_type>::type>(
883 detail::IndexableTraits<T>::at(val_, arg.splitIntKey()))
891 template <class Container, class Value>
893 detail::DefaultValueWrapper<Container, Value>,
894 typename detail::IndexableTraits<Container>::enabled> {
896 explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
899 template <class FormatCallback>
900 void format(FormatArg& arg, FormatCallback& cb) const {
901 FormatValue<typename std::decay<
902 typename detail::IndexableTraits<Container>::value_type>::type>(
903 detail::IndexableTraits<Container>::at(
904 val_.container, arg.splitIntKey(), val_.defaultValue))
909 const detail::DefaultValueWrapper<Container, Value>& val_;
914 // Define enabled, key_type, convert from StringPiece to the key types
917 struct KeyFromStringPiece;
921 struct KeyFromStringPiece<std::string> : public FormatTraitsBase {
922 typedef std::string key_type;
923 static std::string convert(StringPiece s) {
926 typedef void enabled;
931 struct KeyFromStringPiece<fbstring> : public FormatTraitsBase {
932 typedef fbstring key_type;
933 static fbstring convert(StringPiece s) {
934 return s.to<fbstring>();
940 struct KeyFromStringPiece<StringPiece> : public FormatTraitsBase {
941 typedef StringPiece key_type;
942 static StringPiece convert(StringPiece s) {
947 // Base class for associative types keyed by strings
949 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));
955 static const value_type&
956 at(const T& map, StringPiece key, const value_type& dflt) {
957 auto pos = map.find(KeyFromStringPiece<key_type>::convert(key));
958 return pos != map.end() ? pos->second : dflt;
962 // Define enabled, key_type, value_type, at() for supported string-keyed
964 template <class T, class Enabled = void>
965 struct KeyableTraits;
967 // std::map with string key
968 template <class K, class T, class C, class A>
969 struct KeyableTraits<
970 std::map<K, T, C, A>,
971 typename KeyFromStringPiece<K>::enabled>
972 : public KeyableTraitsAssoc<std::map<K, T, C, A>> {};
974 // std::unordered_map with string key
975 template <class K, class T, class H, class E, class A>
976 struct KeyableTraits<
977 std::unordered_map<K, T, H, E, A>,
978 typename KeyFromStringPiece<K>::enabled>
979 : public KeyableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {};
981 } // namespace detail
983 // Partial specialization of FormatValue for string-keyed containers
985 class FormatValue<T, typename detail::KeyableTraits<T>::enabled> {
987 explicit FormatValue(const T& val) : val_(val) {}
989 template <class FormatCallback>
990 void format(FormatArg& arg, FormatCallback& cb) const {
991 FormatValue<typename std::decay<
992 typename detail::KeyableTraits<T>::value_type>::type>(
993 detail::KeyableTraits<T>::at(val_, arg.splitKey()))
1001 template <class Container, class Value>
1003 detail::DefaultValueWrapper<Container, Value>,
1004 typename detail::KeyableTraits<Container>::enabled> {
1006 explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
1009 template <class FormatCallback>
1010 void format(FormatArg& arg, FormatCallback& cb) const {
1011 FormatValue<typename std::decay<
1012 typename detail::KeyableTraits<Container>::value_type>::type>(
1013 detail::KeyableTraits<Container>::at(
1014 val_.container, arg.splitKey(), val_.defaultValue))
1019 const detail::DefaultValueWrapper<Container, Value>& val_;
1022 // Partial specialization of FormatValue for pairs
1023 template <class A, class B>
1024 class FormatValue<std::pair<A, B>> {
1026 explicit FormatValue(const std::pair<A, B>& val) : val_(val) {}
1028 template <class FormatCallback>
1029 void format(FormatArg& arg, FormatCallback& cb) const {
1030 int key = arg.splitIntKey();
1033 FormatValue<typename std::decay<A>::type>(val_.first).format(arg, cb);
1036 FormatValue<typename std::decay<B>::type>(val_.second).format(arg, cb);
1039 arg.error("invalid index for pair");
1044 const std::pair<A, B>& val_;
1047 // Partial specialization of FormatValue for tuples
1048 template <class... Args>
1049 class FormatValue<std::tuple<Args...>> {
1050 typedef std::tuple<Args...> Tuple;
1053 explicit FormatValue(const Tuple& val) : val_(val) {}
1055 template <class FormatCallback>
1056 void format(FormatArg& arg, FormatCallback& cb) const {
1057 int key = arg.splitIntKey();
1058 arg.enforce(key >= 0, "tuple index must be non-negative");
1059 doFormat(size_t(key), arg, cb);
1063 static constexpr size_t valueCount = std::tuple_size<Tuple>::value;
1065 template <size_t K, class Callback>
1066 typename std::enable_if<K == valueCount>::type
1067 doFormatFrom(size_t i, FormatArg& arg, Callback& /* cb */) const {
1068 arg.enforce("tuple index out of range, max=", i);
1071 template <size_t K, class Callback>
1072 typename std::enable_if<(K < valueCount)>::type
1073 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1075 FormatValue<typename std::decay<
1076 typename std::tuple_element<K, Tuple>::type>::type>(std::get<K>(val_))
1079 doFormatFrom<K + 1>(i, arg, cb);
1083 template <class Callback>
1084 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
1085 return doFormatFrom<0>(i, arg, cb);
1091 // Partial specialization of FormatValue for nested Formatters
1092 template <bool containerMode, class... Args, template <bool, class...> class F>
1094 F<containerMode, Args...>,
1095 typename std::enable_if<
1096 detail::IsFormatter<F<containerMode, Args...>>::value>::type> {
1097 typedef typename F<containerMode, Args...>::BaseType FormatterValue;
1100 explicit FormatValue(const FormatterValue& f) : f_(f) {}
1102 template <class FormatCallback>
1103 void format(FormatArg& arg, FormatCallback& cb) const {
1104 format_value::formatFormatter(f_, arg, cb);
1108 const FormatterValue& f_;
1112 * Formatter objects can be appended to strings, and therefore they're
1113 * compatible with folly::toAppend and folly::to.
1115 template <class Tgt, class Derived, bool containerMode, class... Args>
1116 typename std::enable_if<IsSomeString<Tgt>::value>::type toAppend(
1117 const BaseFormatter<Derived, containerMode, Args...>& value,
1119 value.appendTo(*result);
1122 } // namespace folly