2 * Copyright 2016 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
34 #pragma GCC diagnostic push
35 #pragma GCC diagnostic ignored "-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).
63 size_t uintToHex(char* buffer, size_t bufLen, Uint v,
64 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(StringPiece str,
160 values_(FormatValue<typename std::decay<Args>::type>(
161 std::forward<Args>(args))...) {
162 static_assert(!containerMode || sizeof...(Args) == 1,
163 "Exactly one argument required in container mode");
166 template <class Derived, bool containerMode, class... Args>
167 template <class Output>
168 void BaseFormatter<Derived, containerMode, Args...>::operator()(Output& out)
170 // Copy raw string (without format specifiers) to output;
171 // not as simple as we'd like, as we still need to translate "}}" to "}"
172 // and throw if we see any lone "}"
173 auto outputString = [&out] (StringPiece s) {
177 auto q = static_cast<const char*>(memchr(p, '}', size_t(end - p)));
179 out(StringPiece(p, end));
183 out(StringPiece(p, q));
186 if (p == end || *p != '}') {
187 throw BadFormatArg("folly::format: single '}' in format string");
193 auto p = str_.begin();
194 auto end = str_.end();
197 bool hasDefaultArgIndex = false;
198 bool hasExplicitArgIndex = false;
200 auto q = static_cast<const char*>(memchr(p, '{', size_t(end - p)));
202 outputString(StringPiece(p, end));
205 outputString(StringPiece(p, q));
209 throw BadFormatArg("folly::format: '}' at end of format string");
214 out(StringPiece(p, 1));
220 q = static_cast<const char*>(memchr(p, '}', size_t(end - p)));
222 throw BadFormatArg("folly::format: missing ending '}'");
224 FormatArg arg(StringPiece(p, q));
228 auto piece = arg.splitKey<true>(); // empty key component is okay
229 if (containerMode) { // static
230 arg.enforce(arg.width != FormatArg::kDynamicWidth,
231 "dynamic field width not supported in vformat()");
233 arg.setNextIntKey(nextArg++);
234 hasDefaultArgIndex = true;
236 arg.setNextKey(piece);
237 hasExplicitArgIndex = true;
241 if (arg.width == FormatArg::kDynamicWidth) {
242 arg.enforce(arg.widthIndex == FormatArg::kNoIndex,
243 "cannot provide width arg index without value arg index");
244 int sizeArg = nextArg++;
245 arg.width = getSizeArg(size_t(sizeArg), arg);
248 argIndex = nextArg++;
249 hasDefaultArgIndex = true;
251 if (arg.width == FormatArg::kDynamicWidth) {
252 arg.enforce(arg.widthIndex != FormatArg::kNoIndex,
253 "cannot provide value arg index without width arg index");
254 arg.width = getSizeArg(size_t(arg.widthIndex), arg);
258 argIndex = to<int>(piece);
259 } catch (const std::out_of_range&) {
260 arg.error("argument index must be integer");
262 arg.enforce(argIndex >= 0, "argument index must be non-negative");
263 hasExplicitArgIndex = true;
267 if (hasDefaultArgIndex && hasExplicitArgIndex) {
269 "folly::format: may not have both default and explicit arg indexes");
272 doFormat(size_t(argIndex), arg, out);
276 template <class Derived, bool containerMode, class... Args>
277 void writeTo(FILE* fp,
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 throw BadFormatArg("folly::format: invalid width");
295 if (arg.precision != FormatArg::kDefaultPrecision && arg.precision < 0) {
296 throw BadFormatArg("folly::format: invalid precision");
299 // XXX: clang should be smart enough to not need the two static_cast<size_t>
300 // uses below given the above checks. If clang ever becomes that smart, we
301 // should remove the otherwise unnecessary warts.
303 if (arg.precision != FormatArg::kDefaultPrecision &&
304 val.size() > static_cast<size_t>(arg.precision)) {
305 val.reset(val.data(), size_t(arg.precision));
308 constexpr int padBufSize = 128;
309 char padBuf[padBufSize];
311 // Output padding, no more than padBufSize at once
312 auto pad = [&padBuf, &cb, padBufSize] (int chars) {
314 int n = std::min(chars, padBufSize);
315 cb(StringPiece(padBuf, size_t(n)));
320 int padRemaining = 0;
321 if (arg.width != FormatArg::kDefaultWidth &&
322 val.size() < static_cast<size_t>(arg.width)) {
323 char fill = arg.fill == FormatArg::kDefaultFill ? ' ' : arg.fill;
324 int padChars = static_cast<int> (arg.width - val.size());
325 memset(padBuf, fill, size_t(std::min(padBufSize, padChars)));
328 case FormatArg::Align::DEFAULT:
329 case FormatArg::Align::LEFT:
330 padRemaining = padChars;
332 case FormatArg::Align::CENTER:
334 padRemaining = padChars - padChars / 2;
336 case FormatArg::Align::RIGHT:
337 case FormatArg::Align::PAD_AFTER_SIGN:
353 template <class FormatCallback>
354 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
355 FormatCallback& cb) {
356 // precision means something different for numbers
357 arg.precision = FormatArg::kDefaultPrecision;
358 if (arg.align == FormatArg::Align::DEFAULT) {
359 arg.align = FormatArg::Align::RIGHT;
360 } else if (prefixLen && arg.align == FormatArg::Align::PAD_AFTER_SIGN) {
361 // Split off the prefix, then do any padding if necessary
362 cb(val.subpiece(0, size_t(prefixLen)));
363 val.advance(size_t(prefixLen));
364 arg.width = std::max(arg.width - prefixLen, 0);
366 format_value::formatString(val, arg, cb);
369 template <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) {
381 } else if (arg.align != FormatArg::Align::LEFT &&
382 arg.align != FormatArg::Align::DEFAULT) {
383 // We can only avoid creating a temporary string if we align left,
384 // as we'd need to know the size beforehand otherwise
385 format_value::formatString(formatter.fbstr(), arg, cb);
387 auto fn = [&arg, &cb] (StringPiece sp) mutable {
388 int sz = static_cast<int>(sp.size());
389 if (arg.precision != FormatArg::kDefaultPrecision) {
390 sz = std::min(arg.precision, sz);
391 sp.reset(sp.data(), sz);
396 if (arg.width != FormatArg::kDefaultWidth) {
397 arg.width = std::max(arg.width - sz, 0);
402 if (arg.width != FormatArg::kDefaultWidth && arg.width != 0) {
403 // Rely on formatString to do appropriate padding
404 format_value::formatString(StringPiece(), arg, cb);
409 } // namespace format_value
411 // Definitions for default FormatValue classes
413 // Integral types (except bool)
416 T, typename std::enable_if<
417 std::is_integral<T>::value &&
418 !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_);
467 arg.enforce(arg.sign == FormatArg::Sign::DEFAULT,
468 "sign specifications not allowed for unsigned values");
472 // #x: 0x prefix + 16 bytes = 18 bytes
473 // #o: 0 prefix + 22 bytes = 23 bytes
474 // #b: 0b prefix + 64 bytes = 65 bytes
475 // ,d: 26 bytes (including thousands separators!)
477 // + 3 for sign and prefix shenanigans (see below)
478 constexpr size_t valBufSize = 69;
479 char valBuf[valBufSize];
480 char* valBufBegin = nullptr;
481 char* valBufEnd = nullptr;
484 switch (presentation) {
486 arg.enforce(!arg.basePrefix,
487 "base prefix not allowed with '", presentation,
490 arg.enforce(!arg.thousandsSeparator,
491 "cannot use ',' with the '", presentation,
494 valBufBegin = valBuf + 3; // room for sign and base prefix
495 #if defined(__ANDROID__)
496 int len = snprintf(valBufBegin, (valBuf + valBufSize) - valBufBegin,
497 "%" PRIuMAX, static_cast<uintmax_t>(uval));
501 size_t((valBuf + valBufSize) - valBufBegin),
503 static_cast<uintmax_t>(uval));
505 // valBufSize should always be big enough, so this should never
507 assert(len < valBuf + valBufSize - valBufBegin);
508 valBufEnd = valBufBegin + len;
512 arg.enforce(!arg.basePrefix,
513 "base prefix not allowed with '", presentation,
515 valBufBegin = valBuf + 3; // room for sign and base prefix
517 // Use uintToBuffer, faster than sprintf
518 valBufEnd = valBufBegin + uint64ToBufferUnsafe(uval, valBufBegin);
519 if (arg.thousandsSeparator) {
520 detail::insertThousandsGroupingUnsafe(valBufBegin, &valBufEnd);
524 arg.enforce(!arg.basePrefix,
525 "base prefix not allowed with '", presentation,
527 arg.enforce(!arg.thousandsSeparator,
528 "thousands separator (',') not allowed with '",
529 presentation, "' specifier");
530 valBufBegin = valBuf + 3;
531 *valBufBegin = static_cast<char>(uval);
532 valBufEnd = valBufBegin + 1;
536 arg.enforce(!arg.thousandsSeparator,
537 "thousands separator (',') not allowed with '",
538 presentation, "' specifier");
539 valBufEnd = valBuf + valBufSize - 1;
540 valBufBegin = valBuf + detail::uintToOctal(valBuf, valBufSize - 1, uval);
541 if (arg.basePrefix) {
542 *--valBufBegin = '0';
547 arg.enforce(!arg.thousandsSeparator,
548 "thousands separator (',') not allowed with '",
549 presentation, "' specifier");
550 valBufEnd = valBuf + valBufSize - 1;
551 valBufBegin = valBuf + detail::uintToHexLower(valBuf, valBufSize - 1,
553 if (arg.basePrefix) {
554 *--valBufBegin = 'x';
555 *--valBufBegin = '0';
560 arg.enforce(!arg.thousandsSeparator,
561 "thousands separator (',') not allowed with '",
562 presentation, "' specifier");
563 valBufEnd = valBuf + valBufSize - 1;
564 valBufBegin = valBuf + detail::uintToHexUpper(valBuf, valBufSize - 1,
566 if (arg.basePrefix) {
567 *--valBufBegin = 'X';
568 *--valBufBegin = '0';
574 arg.enforce(!arg.thousandsSeparator,
575 "thousands separator (',') not allowed with '",
576 presentation, "' specifier");
577 valBufEnd = valBuf + valBufSize - 1;
578 valBufBegin = valBuf + detail::uintToBinary(valBuf, valBufSize - 1,
580 if (arg.basePrefix) {
581 *--valBufBegin = presentation; // 0b or 0B
582 *--valBufBegin = '0';
587 arg.error("invalid specifier '", presentation, "'");
591 *--valBufBegin = sign;
595 format_value::formatNumber(StringPiece(valBufBegin, valBufEnd), prefixLen,
605 class FormatValue<bool> {
607 explicit FormatValue(bool val) : val_(val) { }
609 template <class FormatCallback>
610 void format(FormatArg& arg, FormatCallback& cb) const {
611 if (arg.presentation == FormatArg::kDefaultPresentation) {
612 arg.validate(FormatArg::Type::OTHER);
613 format_value::formatString(val_ ? "true" : "false", arg, cb);
615 FormatValue<int>(val_).format(arg, cb);
625 class FormatValue<double> {
627 explicit FormatValue(double val) : val_(val) { }
629 template <class FormatCallback>
630 void format(FormatArg& arg, FormatCallback& cb) const {
633 formatHelper(piece, prefixLen, arg);
634 format_value::formatNumber(piece, prefixLen, arg, cb);
638 void formatHelper(fbstring& piece, int& prefixLen, FormatArg& arg) const;
643 // float (defer to double)
645 class FormatValue<float> {
647 explicit FormatValue(float val) : val_(val) { }
649 template <class FormatCallback>
650 void format(FormatArg& arg, FormatCallback& cb) const {
651 FormatValue<double>(val_).format(arg, cb);
658 // Sring-y types (implicitly convertible to StringPiece, except char*)
661 T, typename std::enable_if<
662 (!std::is_pointer<T>::value ||
663 !std::is_same<char, typename std::decay<
664 typename std::remove_pointer<T>::type>::type>::value) &&
665 std::is_convertible<T, StringPiece>::value>::type>
668 explicit FormatValue(StringPiece val) : val_(val) { }
670 template <class FormatCallback>
671 void format(FormatArg& arg, FormatCallback& cb) const {
672 if (arg.keyEmpty()) {
673 arg.validate(FormatArg::Type::OTHER);
674 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation ||
675 arg.presentation == 's',
676 "invalid specifier '", arg.presentation, "'");
677 format_value::formatString(val_, arg, cb);
679 FormatValue<char>(val_.at(size_t(arg.splitIntKey()))).format(arg, cb);
689 class FormatValue<std::nullptr_t> {
691 explicit FormatValue(std::nullptr_t) { }
693 template <class FormatCallback>
694 void format(FormatArg& arg, FormatCallback& cb) const {
695 arg.validate(FormatArg::Type::OTHER);
696 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
697 "invalid specifier '", arg.presentation, "'");
698 format_value::formatString("(null)", arg, cb);
702 // Partial specialization of FormatValue for char*
706 typename std::enable_if<
707 std::is_same<char, typename std::decay<T>::type>::value>::type>
710 explicit FormatValue(T* val) : val_(val) { }
712 template <class FormatCallback>
713 void format(FormatArg& arg, FormatCallback& cb) const {
714 if (arg.keyEmpty()) {
716 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
718 FormatValue<StringPiece>(val_).format(arg, cb);
721 FormatValue<typename std::decay<T>::type>(
722 val_[arg.splitIntKey()]).format(arg, cb);
730 // Partial specialization of FormatValue for void*
734 typename std::enable_if<
735 std::is_same<void, 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 {
743 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
745 // Print as a pointer, in hex.
746 arg.validate(FormatArg::Type::OTHER);
747 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
748 "invalid specifier '", arg.presentation, "'");
749 arg.basePrefix = true;
750 arg.presentation = 'x';
751 if (arg.align == FormatArg::Align::DEFAULT) {
752 arg.align = FormatArg::Align::LEFT;
754 FormatValue<uintptr_t>(
755 reinterpret_cast<uintptr_t>(val_)).doFormat(arg, cb);
763 template <class T, class = void>
764 class TryFormatValue {
766 template <class FormatCallback>
767 static void formatOrFail(T& /* value */,
769 FormatCallback& /* cb */) {
770 arg.error("No formatter available for this type");
775 class TryFormatValue<
777 typename std::enable_if<
778 0 < sizeof(FormatValue<typename std::decay<T>::type>)>::type>
781 template <class FormatCallback>
782 static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
783 FormatValue<typename std::decay<T>::type>(value).format(arg, cb);
787 // Partial specialization of FormatValue for other pointers
791 typename std::enable_if<
792 !std::is_same<char, typename std::decay<T>::type>::value &&
793 !std::is_same<void, typename std::decay<T>::type>::value>::type>
796 explicit FormatValue(T* val) : val_(val) { }
798 template <class FormatCallback>
799 void format(FormatArg& arg, FormatCallback& cb) const {
800 if (arg.keyEmpty()) {
801 FormatValue<void*>((void*)val_).format(arg, cb);
803 TryFormatValue<T>::formatOrFail(val_[arg.splitIntKey()], arg, cb);
813 template <class T, size_t N>
814 struct IndexableTraits<std::array<T, N>>
815 : public IndexableTraitsSeq<std::array<T, N>> {
819 template <class T, class A>
820 struct IndexableTraits<std::vector<T, A>>
821 : public IndexableTraitsSeq<std::vector<T, A>> {
825 template <class T, class A>
826 struct IndexableTraits<std::deque<T, A>>
827 : public IndexableTraitsSeq<std::deque<T, A>> {
830 // std::map with integral keys
831 template <class K, class T, class C, class A>
832 struct IndexableTraits<
833 std::map<K, T, C, A>,
834 typename std::enable_if<std::is_integral<K>::value>::type>
835 : public IndexableTraitsAssoc<std::map<K, T, C, A>> {
838 // std::unordered_map with integral keys
839 template <class K, class T, class H, class E, class A>
840 struct IndexableTraits<
841 std::unordered_map<K, T, H, E, A>,
842 typename std::enable_if<std::is_integral<K>::value>::type>
843 : public IndexableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
846 } // namespace detail
848 // Partial specialization of FormatValue for integer-indexable containers
852 typename detail::IndexableTraits<T>::enabled> {
854 explicit FormatValue(const T& val) : val_(val) { }
856 template <class FormatCallback>
857 void format(FormatArg& arg, FormatCallback& cb) const {
858 FormatValue<typename std::decay<
859 typename detail::IndexableTraits<T>::value_type>::type>(
860 detail::IndexableTraits<T>::at(
861 val_, arg.splitIntKey())).format(arg, cb);
868 template <class Container, class Value>
870 detail::DefaultValueWrapper<Container, Value>,
871 typename detail::IndexableTraits<Container>::enabled> {
873 explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
876 template <class FormatCallback>
877 void format(FormatArg& arg, FormatCallback& cb) const {
878 FormatValue<typename std::decay<
879 typename detail::IndexableTraits<Container>::value_type>::type>(
880 detail::IndexableTraits<Container>::at(
883 val_.defaultValue)).format(arg, cb);
887 const detail::DefaultValueWrapper<Container, Value>& val_;
892 // Define enabled, key_type, convert from StringPiece to the key types
894 template <class T> struct KeyFromStringPiece;
898 struct KeyFromStringPiece<std::string> : public FormatTraitsBase {
899 typedef std::string key_type;
900 static std::string convert(StringPiece s) {
903 typedef void enabled;
908 struct KeyFromStringPiece<fbstring> : public FormatTraitsBase {
909 typedef fbstring key_type;
910 static fbstring convert(StringPiece s) {
911 return s.toFbstring();
917 struct KeyFromStringPiece<StringPiece> : public FormatTraitsBase {
918 typedef StringPiece key_type;
919 static StringPiece convert(StringPiece s) {
924 // Base class for associative types keyed by strings
925 template <class T> struct KeyableTraitsAssoc : public FormatTraitsBase {
926 typedef typename T::key_type key_type;
927 typedef typename T::value_type::second_type value_type;
928 static const value_type& at(const T& map, StringPiece key) {
929 return map.at(KeyFromStringPiece<key_type>::convert(key));
931 static const value_type& at(const T& map, StringPiece key,
932 const value_type& dflt) {
933 auto pos = map.find(KeyFromStringPiece<key_type>::convert(key));
934 return pos != map.end() ? pos->second : dflt;
938 // Define enabled, key_type, value_type, at() for supported string-keyed
940 template <class T, class Enabled=void> struct KeyableTraits;
942 // std::map with string key
943 template <class K, class T, class C, class A>
944 struct KeyableTraits<
945 std::map<K, T, C, A>,
946 typename KeyFromStringPiece<K>::enabled>
947 : public KeyableTraitsAssoc<std::map<K, T, C, A>> {
950 // std::unordered_map with string key
951 template <class K, class T, class H, class E, class A>
952 struct KeyableTraits<
953 std::unordered_map<K, T, H, E, A>,
954 typename KeyFromStringPiece<K>::enabled>
955 : public KeyableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
958 } // namespace detail
960 // Partial specialization of FormatValue for string-keyed containers
964 typename detail::KeyableTraits<T>::enabled> {
966 explicit FormatValue(const T& val) : val_(val) { }
968 template <class FormatCallback>
969 void format(FormatArg& arg, FormatCallback& cb) const {
970 FormatValue<typename std::decay<
971 typename detail::KeyableTraits<T>::value_type>::type>(
972 detail::KeyableTraits<T>::at(
973 val_, arg.splitKey())).format(arg, cb);
980 template <class Container, class Value>
982 detail::DefaultValueWrapper<Container, Value>,
983 typename detail::KeyableTraits<Container>::enabled> {
985 explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
988 template <class FormatCallback>
989 void format(FormatArg& arg, FormatCallback& cb) const {
990 FormatValue<typename std::decay<
991 typename detail::KeyableTraits<Container>::value_type>::type>(
992 detail::KeyableTraits<Container>::at(
995 val_.defaultValue)).format(arg, cb);
999 const detail::DefaultValueWrapper<Container, Value>& val_;
1002 // Partial specialization of FormatValue for pairs
1003 template <class A, class B>
1004 class FormatValue<std::pair<A, B>> {
1006 explicit FormatValue(const std::pair<A, B>& val) : val_(val) { }
1008 template <class FormatCallback>
1009 void format(FormatArg& arg, FormatCallback& cb) const {
1010 int key = arg.splitIntKey();
1013 FormatValue<typename std::decay<A>::type>(val_.first).format(arg, cb);
1016 FormatValue<typename std::decay<B>::type>(val_.second).format(arg, cb);
1019 arg.error("invalid index for pair");
1024 const std::pair<A, B>& val_;
1027 // Partial specialization of FormatValue for tuples
1028 template <class... Args>
1029 class FormatValue<std::tuple<Args...>> {
1030 typedef std::tuple<Args...> Tuple;
1032 explicit FormatValue(const Tuple& val) : val_(val) { }
1034 template <class FormatCallback>
1035 void format(FormatArg& arg, FormatCallback& cb) const {
1036 int key = arg.splitIntKey();
1037 arg.enforce(key >= 0, "tuple index must be non-negative");
1038 doFormat(key, arg, cb);
1042 static constexpr size_t valueCount = std::tuple_size<Tuple>::value;
1044 template <size_t K, class Callback>
1045 typename std::enable_if<K == valueCount>::type doFormatFrom(
1046 size_t i, FormatArg& arg, Callback& /* cb */) const {
1047 arg.enforce("tuple index out of range, max=", i);
1050 template <size_t K, class Callback>
1051 typename std::enable_if<(K < valueCount)>::type
1052 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1054 FormatValue<typename std::decay<
1055 typename std::tuple_element<K, Tuple>::type>::type>(
1056 std::get<K>(val_)).format(arg, cb);
1058 doFormatFrom<K+1>(i, arg, cb);
1062 template <class Callback>
1063 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
1064 return doFormatFrom<0>(i, arg, cb);
1070 // Partial specialization of FormatValue for nested Formatters
1071 template <bool containerMode, class... Args,
1072 template <bool, class...> class F>
1073 class FormatValue<F<containerMode, Args...>,
1074 typename std::enable_if<detail::IsFormatter<
1075 F<containerMode, Args...>>::value>::type> {
1076 typedef typename F<containerMode, Args...>::BaseType FormatterValue;
1079 explicit FormatValue(const FormatterValue& f) : f_(f) { }
1081 template <class FormatCallback>
1082 void format(FormatArg& arg, FormatCallback& cb) const {
1083 format_value::formatFormatter(f_, arg, cb);
1086 const FormatterValue& f_;
1090 * Formatter objects can be appended to strings, and therefore they're
1091 * compatible with folly::toAppend and folly::to.
1093 template <class Tgt, class Derived, bool containerMode, class... Args>
1094 typename std::enable_if<IsSomeString<Tgt>::value>::type toAppend(
1095 const BaseFormatter<Derived, containerMode, Args...>& value, Tgt* result) {
1096 value.appendTo(*result);
1099 } // namespace folly
1101 #pragma GCC diagnostic pop