2 * Copyright 2015 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.
24 #include <unordered_map>
27 #include <folly/Exception.h>
28 #include <folly/FormatTraits.h>
29 #include <folly/Traits.h>
31 // Ignore -Wformat-nonliteral warnings within this file
32 #pragma GCC diagnostic push
33 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
39 // Updates the end of the buffer after the comma separators have been added.
40 void insertThousandsGroupingUnsafe(char* start_buffer, char** end_buffer);
42 extern const char formatHexUpper[256][2];
43 extern const char formatHexLower[256][2];
44 extern const char formatOctal[512][3];
45 extern const char formatBinary[256][8];
47 const size_t kMaxHexLength = 2 * sizeof(uintmax_t);
48 const size_t kMaxOctalLength = 3 * sizeof(uintmax_t);
49 const size_t kMaxBinaryLength = 8 * sizeof(uintmax_t);
52 * Convert an unsigned to hex, using repr (which maps from each possible
53 * 2-hex-bytes value to the 2-character representation).
55 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
56 * the supplied buffer and returns the offset of the beginning of the string
57 * from the start of the buffer. The formatted string will be in range
58 * [buf+begin, buf+bufLen).
61 size_t uintToHex(char* buffer, size_t bufLen, Uint v,
62 const char (&repr)[256][2]) {
63 // 'v >>= 7, v >>= 1' is no more than a work around to get rid of shift size
64 // warning when Uint = uint8_t (it's false as v >= 256 implies sizeof(v) > 1).
65 for (; !less_than<unsigned, 256>(v); v >>= 7, v >>= 1) {
68 buffer[bufLen] = repr[b][0];
69 buffer[bufLen + 1] = repr[b][1];
71 buffer[--bufLen] = repr[v][1];
73 buffer[--bufLen] = repr[v][0];
79 * Convert an unsigned to hex, using lower-case letters for the digits
80 * above 9. See the comments for uintToHex.
83 inline size_t uintToHexLower(char* buffer, size_t bufLen, Uint v) {
84 return uintToHex(buffer, bufLen, v, formatHexLower);
88 * Convert an unsigned to hex, using upper-case letters for the digits
89 * above 9. See the comments for uintToHex.
92 inline size_t uintToHexUpper(char* buffer, size_t bufLen, Uint v) {
93 return uintToHex(buffer, bufLen, v, formatHexUpper);
97 * Convert an unsigned to octal.
99 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
100 * the supplied buffer and returns the offset of the beginning of the string
101 * from the start of the buffer. The formatted string will be in range
102 * [buf+begin, buf+bufLen).
104 template <class Uint>
105 size_t uintToOctal(char* buffer, size_t bufLen, Uint v) {
106 auto& repr = formatOctal;
107 // 'v >>= 7, v >>= 2' is no more than a work around to get rid of shift size
108 // warning when Uint = uint8_t (it's false as v >= 512 implies sizeof(v) > 1).
109 for (; !less_than<unsigned, 512>(v); v >>= 7, v >>= 2) {
112 buffer[bufLen] = repr[b][0];
113 buffer[bufLen + 1] = repr[b][1];
114 buffer[bufLen + 2] = repr[b][2];
116 buffer[--bufLen] = repr[v][2];
118 buffer[--bufLen] = repr[v][1];
121 buffer[--bufLen] = repr[v][0];
127 * Convert an unsigned to binary.
129 * Just like folly::detail::uintToBuffer in Conv.h, writes at the *end* of
130 * the supplied buffer and returns the offset of the beginning of the string
131 * from the start of the buffer. The formatted string will be in range
132 * [buf+begin, buf+bufLen).
134 template <class Uint>
135 size_t uintToBinary(char* buffer, size_t bufLen, Uint v) {
136 auto& repr = formatBinary;
138 buffer[--bufLen] = '0';
141 for (; v; v >>= 7, v >>= 1) {
144 memcpy(buffer + bufLen, &(repr[b][0]), 8);
146 while (buffer[bufLen] == '0') {
152 } // namespace detail
154 template <class Derived, bool containerMode, class... Args>
155 BaseFormatter<Derived, containerMode, Args...>::BaseFormatter(StringPiece str,
158 values_(FormatValue<typename std::decay<Args>::type>(
159 std::forward<Args>(args))...) {
160 static_assert(!containerMode || sizeof...(Args) == 1,
161 "Exactly one argument required in container mode");
164 template <class Derived, bool containerMode, class... Args>
165 template <class Output>
166 void BaseFormatter<Derived, containerMode, Args...>::operator()(Output& out)
168 // Copy raw string (without format specifiers) to output;
169 // not as simple as we'd like, as we still need to translate "}}" to "}"
170 // and throw if we see any lone "}"
171 auto outputString = [&out] (StringPiece s) {
175 auto q = static_cast<const char*>(memchr(p, '}', end - p));
177 out(StringPiece(p, end));
181 out(StringPiece(p, q));
184 if (p == end || *p != '}') {
185 throw BadFormatArg("folly::format: single '}' in format string");
191 auto p = str_.begin();
192 auto end = str_.end();
195 bool hasDefaultArgIndex = false;
196 bool hasExplicitArgIndex = false;
198 auto q = static_cast<const char*>(memchr(p, '{', end - p));
200 outputString(StringPiece(p, end));
203 outputString(StringPiece(p, q));
207 throw BadFormatArg("folly::format: '}' at end of format string");
212 out(StringPiece(p, 1));
218 q = static_cast<const char*>(memchr(p, '}', end - p));
220 throw BadFormatArg("folly::format: missing ending '}'");
222 FormatArg arg(StringPiece(p, q));
226 auto piece = arg.splitKey<true>(); // empty key component is okay
227 if (containerMode) { // static
228 arg.enforce(arg.width != FormatArg::kDynamicWidth,
229 "dynamic field width not supported in vformat()");
231 arg.setNextIntKey(nextArg++);
232 hasDefaultArgIndex = true;
234 arg.setNextKey(piece);
235 hasExplicitArgIndex = true;
239 if (arg.width == FormatArg::kDynamicWidth) {
240 arg.enforce(arg.widthIndex == FormatArg::kNoIndex,
241 "cannot provide width arg index without value arg index");
242 int sizeArg = nextArg++;
243 arg.width = getSizeArg(sizeArg, arg);
246 argIndex = nextArg++;
247 hasDefaultArgIndex = true;
249 if (arg.width == FormatArg::kDynamicWidth) {
250 arg.enforce(arg.widthIndex != FormatArg::kNoIndex,
251 "cannot provide value arg index without width arg index");
252 arg.width = getSizeArg(arg.widthIndex, arg);
256 argIndex = to<int>(piece);
257 } catch (const std::out_of_range& e) {
258 arg.error("argument index must be integer");
260 arg.enforce(argIndex >= 0, "argument index must be non-negative");
261 hasExplicitArgIndex = true;
265 if (hasDefaultArgIndex && hasExplicitArgIndex) {
267 "folly::format: may not have both default and explicit arg indexes");
270 doFormat(argIndex, arg, out);
274 template <class Derived, bool containerMode, class... Args>
275 void writeTo(FILE* fp,
276 const BaseFormatter<Derived, containerMode, Args...>& formatter) {
277 auto writer = [fp] (StringPiece sp) {
278 size_t n = fwrite(sp.data(), 1, sp.size(), fp);
280 throwSystemError("Formatter writeTo", "fwrite failed");
286 namespace format_value {
288 template <class FormatCallback>
289 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb) {
290 if (arg.width != FormatArg::kDefaultWidth && arg.width < 0) {
291 throw BadFormatArg("folly::format: invalid width");
293 if (arg.precision != FormatArg::kDefaultPrecision && arg.precision < 0) {
294 throw BadFormatArg("folly::format: invalid precision");
297 // XXX: clang should be smart enough to not need the two static_cast<size_t>
298 // uses below given the above checks. If clang ever becomes that smart, we
299 // should remove the otherwise unnecessary warts.
301 if (arg.precision != FormatArg::kDefaultPrecision &&
302 val.size() > static_cast<size_t>(arg.precision)) {
303 val.reset(val.data(), arg.precision);
306 constexpr int padBufSize = 128;
307 char padBuf[padBufSize];
309 // Output padding, no more than padBufSize at once
310 auto pad = [&padBuf, &cb, padBufSize] (int chars) {
312 int n = std::min(chars, padBufSize);
313 cb(StringPiece(padBuf, n));
318 int padRemaining = 0;
319 if (arg.width != FormatArg::kDefaultWidth &&
320 val.size() < static_cast<size_t>(arg.width)) {
321 char fill = arg.fill == FormatArg::kDefaultFill ? ' ' : arg.fill;
322 int padChars = static_cast<int> (arg.width - val.size());
323 memset(padBuf, fill, std::min(padBufSize, padChars));
326 case FormatArg::Align::DEFAULT:
327 case FormatArg::Align::LEFT:
328 padRemaining = padChars;
330 case FormatArg::Align::CENTER:
332 padRemaining = padChars - padChars / 2;
334 case FormatArg::Align::RIGHT:
335 case FormatArg::Align::PAD_AFTER_SIGN:
351 template <class FormatCallback>
352 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
353 FormatCallback& cb) {
354 // precision means something different for numbers
355 arg.precision = FormatArg::kDefaultPrecision;
356 if (arg.align == FormatArg::Align::DEFAULT) {
357 arg.align = FormatArg::Align::RIGHT;
358 } else if (prefixLen && arg.align == FormatArg::Align::PAD_AFTER_SIGN) {
359 // Split off the prefix, then do any padding if necessary
360 cb(val.subpiece(0, prefixLen));
361 val.advance(prefixLen);
362 arg.width = std::max(arg.width - prefixLen, 0);
364 format_value::formatString(val, arg, cb);
367 template <class FormatCallback,
371 void formatFormatter(
372 const BaseFormatter<Derived, containerMode, Args...>& formatter,
374 FormatCallback& cb) {
375 if (arg.width == FormatArg::kDefaultWidth &&
376 arg.precision == FormatArg::kDefaultPrecision) {
379 } else if (arg.align != FormatArg::Align::LEFT &&
380 arg.align != FormatArg::Align::DEFAULT) {
381 // We can only avoid creating a temporary string if we align left,
382 // as we'd need to know the size beforehand otherwise
383 format_value::formatString(formatter.fbstr(), arg, cb);
385 auto fn = [&arg, &cb] (StringPiece sp) mutable {
386 int sz = static_cast<int>(sp.size());
387 if (arg.precision != FormatArg::kDefaultPrecision) {
388 sz = std::min(arg.precision, sz);
389 sp.reset(sp.data(), sz);
394 if (arg.width != FormatArg::kDefaultWidth) {
395 arg.width = std::max(arg.width - sz, 0);
400 if (arg.width != FormatArg::kDefaultWidth && arg.width != 0) {
401 // Rely on formatString to do appropriate padding
402 format_value::formatString(StringPiece(), arg, cb);
407 } // namespace format_value
409 // Definitions for default FormatValue classes
411 // Integral types (except bool)
414 T, typename std::enable_if<
415 std::is_integral<T>::value &&
416 !std::is_same<T, bool>::value>::type>
419 explicit FormatValue(T val) : val_(val) { }
425 template <class FormatCallback>
426 void format(FormatArg& arg, FormatCallback& cb) const {
427 arg.validate(FormatArg::Type::INTEGER);
431 template <class FormatCallback>
432 void doFormat(FormatArg& arg, FormatCallback& cb) const {
433 char presentation = arg.presentation;
434 if (presentation == FormatArg::kDefaultPresentation) {
435 presentation = std::is_same<T, char>::value ? 'c' : 'd';
438 // Do all work as unsigned, we'll add the prefix ('0' or '0x' if necessary)
439 // and sign ourselves.
440 typedef typename std::make_unsigned<T>::type UT;
443 if (std::is_signed<T>::value) {
444 if (folly::is_negative(val_)) {
445 uval = static_cast<UT>(-val_);
448 uval = static_cast<UT>(val_);
450 case FormatArg::Sign::PLUS_OR_MINUS:
453 case FormatArg::Sign::SPACE_OR_MINUS:
465 arg.enforce(arg.sign == FormatArg::Sign::DEFAULT,
466 "sign specifications not allowed for unsigned values");
470 // #x: 0x prefix + 16 bytes = 18 bytes
471 // #o: 0 prefix + 22 bytes = 23 bytes
472 // #b: 0b prefix + 64 bytes = 65 bytes
473 // ,d: 26 bytes (including thousands separators!)
475 // + 3 for sign and prefix shenanigans (see below)
476 constexpr size_t valBufSize = 69;
477 char valBuf[valBufSize];
478 char* valBufBegin = nullptr;
479 char* valBufEnd = nullptr;
482 switch (presentation) {
484 arg.enforce(!arg.basePrefix,
485 "base prefix not allowed with '", presentation,
488 arg.enforce(!arg.thousandsSeparator,
489 "cannot use ',' with the '", presentation,
492 valBufBegin = valBuf + 3; // room for sign and base prefix
493 int len = snprintf(valBufBegin, (valBuf + valBufSize) - valBufBegin,
494 "%'ju", static_cast<uintmax_t>(uval));
495 // valBufSize should always be big enough, so this should never
497 assert(len < valBuf + valBufSize - valBufBegin);
498 valBufEnd = valBufBegin + len;
502 arg.enforce(!arg.basePrefix,
503 "base prefix not allowed with '", presentation,
505 valBufBegin = valBuf + 3; // room for sign and base prefix
507 // Use uintToBuffer, faster than sprintf
508 valBufEnd = valBufBegin + uint64ToBufferUnsafe(uval, valBufBegin);
509 if (arg.thousandsSeparator) {
510 detail::insertThousandsGroupingUnsafe(valBufBegin, &valBufEnd);
514 arg.enforce(!arg.basePrefix,
515 "base prefix not allowed with '", presentation,
517 arg.enforce(!arg.thousandsSeparator,
518 "thousands separator (',') not allowed with '",
519 presentation, "' specifier");
520 valBufBegin = valBuf + 3;
521 *valBufBegin = static_cast<char>(uval);
522 valBufEnd = valBufBegin + 1;
526 arg.enforce(!arg.thousandsSeparator,
527 "thousands separator (',') not allowed with '",
528 presentation, "' specifier");
529 valBufEnd = valBuf + valBufSize - 1;
530 valBufBegin = valBuf + detail::uintToOctal(valBuf, valBufSize - 1, uval);
531 if (arg.basePrefix) {
532 *--valBufBegin = '0';
537 arg.enforce(!arg.thousandsSeparator,
538 "thousands separator (',') not allowed with '",
539 presentation, "' specifier");
540 valBufEnd = valBuf + valBufSize - 1;
541 valBufBegin = valBuf + detail::uintToHexLower(valBuf, valBufSize - 1,
543 if (arg.basePrefix) {
544 *--valBufBegin = 'x';
545 *--valBufBegin = '0';
550 arg.enforce(!arg.thousandsSeparator,
551 "thousands separator (',') not allowed with '",
552 presentation, "' specifier");
553 valBufEnd = valBuf + valBufSize - 1;
554 valBufBegin = valBuf + detail::uintToHexUpper(valBuf, valBufSize - 1,
556 if (arg.basePrefix) {
557 *--valBufBegin = 'X';
558 *--valBufBegin = '0';
564 arg.enforce(!arg.thousandsSeparator,
565 "thousands separator (',') not allowed with '",
566 presentation, "' specifier");
567 valBufEnd = valBuf + valBufSize - 1;
568 valBufBegin = valBuf + detail::uintToBinary(valBuf, valBufSize - 1,
570 if (arg.basePrefix) {
571 *--valBufBegin = presentation; // 0b or 0B
572 *--valBufBegin = '0';
577 arg.error("invalid specifier '", presentation, "'");
581 *--valBufBegin = sign;
585 format_value::formatNumber(StringPiece(valBufBegin, valBufEnd), prefixLen,
595 class FormatValue<bool> {
597 explicit FormatValue(bool val) : val_(val) { }
599 template <class FormatCallback>
600 void format(FormatArg& arg, FormatCallback& cb) const {
601 if (arg.presentation == FormatArg::kDefaultPresentation) {
602 arg.validate(FormatArg::Type::OTHER);
603 format_value::formatString(val_ ? "true" : "false", arg, cb);
605 FormatValue<int>(val_).format(arg, cb);
615 class FormatValue<double> {
617 explicit FormatValue(double val) : val_(val) { }
619 template <class FormatCallback>
620 void format(FormatArg& arg, FormatCallback& cb) const {
623 formatHelper(piece, prefixLen, arg);
624 format_value::formatNumber(piece, prefixLen, arg, cb);
628 void formatHelper(fbstring& piece, int& prefixLen, FormatArg& arg) const;
633 // float (defer to double)
635 class FormatValue<float> {
637 explicit FormatValue(float val) : val_(val) { }
639 template <class FormatCallback>
640 void format(FormatArg& arg, FormatCallback& cb) const {
641 FormatValue<double>(val_).format(arg, cb);
648 // Sring-y types (implicitly convertible to StringPiece, except char*)
651 T, typename std::enable_if<
652 (!std::is_pointer<T>::value ||
653 !std::is_same<char, typename std::decay<
654 typename std::remove_pointer<T>::type>::type>::value) &&
655 std::is_convertible<T, StringPiece>::value>::type>
658 explicit FormatValue(StringPiece val) : val_(val) { }
660 template <class FormatCallback>
661 void format(FormatArg& arg, FormatCallback& cb) const {
662 if (arg.keyEmpty()) {
663 arg.validate(FormatArg::Type::OTHER);
664 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation ||
665 arg.presentation == 's',
666 "invalid specifier '", arg.presentation, "'");
667 format_value::formatString(val_, arg, cb);
669 FormatValue<char>(val_.at(arg.splitIntKey())).format(arg, cb);
679 class FormatValue<std::nullptr_t> {
681 explicit FormatValue(std::nullptr_t) { }
683 template <class FormatCallback>
684 void format(FormatArg& arg, FormatCallback& cb) const {
685 arg.validate(FormatArg::Type::OTHER);
686 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
687 "invalid specifier '", arg.presentation, "'");
688 format_value::formatString("(null)", arg, cb);
692 // Partial specialization of FormatValue for char*
696 typename std::enable_if<
697 std::is_same<char, typename std::decay<T>::type>::value>::type>
700 explicit FormatValue(T* val) : val_(val) { }
702 template <class FormatCallback>
703 void format(FormatArg& arg, FormatCallback& cb) const {
704 if (arg.keyEmpty()) {
706 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
708 FormatValue<StringPiece>(val_).format(arg, cb);
711 FormatValue<typename std::decay<T>::type>(
712 val_[arg.splitIntKey()]).format(arg, cb);
720 // Partial specialization of FormatValue for void*
724 typename std::enable_if<
725 std::is_same<void, typename std::decay<T>::type>::value>::type>
728 explicit FormatValue(T* val) : val_(val) { }
730 template <class FormatCallback>
731 void format(FormatArg& arg, FormatCallback& cb) const {
733 FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
735 // Print as a pointer, in hex.
736 arg.validate(FormatArg::Type::OTHER);
737 arg.enforce(arg.presentation == FormatArg::kDefaultPresentation,
738 "invalid specifier '", arg.presentation, "'");
739 arg.basePrefix = true;
740 arg.presentation = 'x';
741 if (arg.align == FormatArg::Align::DEFAULT) {
742 arg.align = FormatArg::Align::LEFT;
744 FormatValue<uintptr_t>(
745 reinterpret_cast<uintptr_t>(val_)).doFormat(arg, cb);
753 template <class T, class = void>
754 class TryFormatValue {
756 template <class FormatCallback>
757 static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
758 arg.error("No formatter available for this type");
763 class TryFormatValue<
765 typename std::enable_if<
766 0 < sizeof(FormatValue<typename std::decay<T>::type>)>::type>
769 template <class FormatCallback>
770 static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
771 FormatValue<typename std::decay<T>::type>(value).format(arg, cb);
775 // Partial specialization of FormatValue for other pointers
779 typename std::enable_if<
780 !std::is_same<char, typename std::decay<T>::type>::value &&
781 !std::is_same<void, typename std::decay<T>::type>::value>::type>
784 explicit FormatValue(T* val) : val_(val) { }
786 template <class FormatCallback>
787 void format(FormatArg& arg, FormatCallback& cb) const {
788 if (arg.keyEmpty()) {
789 FormatValue<void*>((void*)val_).format(arg, cb);
791 TryFormatValue<T>::formatOrFail(val_[arg.splitIntKey()], arg, cb);
801 template <class T, size_t N>
802 struct IndexableTraits<std::array<T, N>>
803 : public IndexableTraitsSeq<std::array<T, N>> {
807 template <class T, class A>
808 struct IndexableTraits<std::vector<T, A>>
809 : public IndexableTraitsSeq<std::vector<T, A>> {
813 template <class T, class A>
814 struct IndexableTraits<std::deque<T, A>>
815 : public IndexableTraitsSeq<std::deque<T, A>> {
818 // std::map with integral keys
819 template <class K, class T, class C, class A>
820 struct IndexableTraits<
821 std::map<K, T, C, A>,
822 typename std::enable_if<std::is_integral<K>::value>::type>
823 : public IndexableTraitsAssoc<std::map<K, T, C, A>> {
826 // std::unordered_map with integral keys
827 template <class K, class T, class H, class E, class A>
828 struct IndexableTraits<
829 std::unordered_map<K, T, H, E, A>,
830 typename std::enable_if<std::is_integral<K>::value>::type>
831 : public IndexableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
834 } // namespace detail
836 // Partial specialization of FormatValue for integer-indexable containers
840 typename detail::IndexableTraits<T>::enabled> {
842 explicit FormatValue(const T& val) : val_(val) { }
844 template <class FormatCallback>
845 void format(FormatArg& arg, FormatCallback& cb) const {
846 FormatValue<typename std::decay<
847 typename detail::IndexableTraits<T>::value_type>::type>(
848 detail::IndexableTraits<T>::at(
849 val_, arg.splitIntKey())).format(arg, cb);
856 template <class Container, class Value>
858 detail::DefaultValueWrapper<Container, Value>,
859 typename detail::IndexableTraits<Container>::enabled> {
861 explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
864 template <class FormatCallback>
865 void format(FormatArg& arg, FormatCallback& cb) const {
866 FormatValue<typename std::decay<
867 typename detail::IndexableTraits<Container>::value_type>::type>(
868 detail::IndexableTraits<Container>::at(
871 val_.defaultValue)).format(arg, cb);
875 const detail::DefaultValueWrapper<Container, Value>& val_;
880 // Define enabled, key_type, convert from StringPiece to the key types
882 template <class T> struct KeyFromStringPiece;
886 struct KeyFromStringPiece<std::string> : public FormatTraitsBase {
887 typedef std::string key_type;
888 static std::string convert(StringPiece s) {
891 typedef void enabled;
896 struct KeyFromStringPiece<fbstring> : public FormatTraitsBase {
897 typedef fbstring key_type;
898 static fbstring convert(StringPiece s) {
899 return s.toFbstring();
905 struct KeyFromStringPiece<StringPiece> : public FormatTraitsBase {
906 typedef StringPiece key_type;
907 static StringPiece convert(StringPiece s) {
912 // Base class for associative types keyed by strings
913 template <class T> struct KeyableTraitsAssoc : public FormatTraitsBase {
914 typedef typename T::key_type key_type;
915 typedef typename T::value_type::second_type value_type;
916 static const value_type& at(const T& map, StringPiece key) {
917 return map.at(KeyFromStringPiece<key_type>::convert(key));
919 static const value_type& at(const T& map, StringPiece key,
920 const value_type& dflt) {
921 auto pos = map.find(KeyFromStringPiece<key_type>::convert(key));
922 return pos != map.end() ? pos->second : dflt;
926 // Define enabled, key_type, value_type, at() for supported string-keyed
928 template <class T, class Enabled=void> struct KeyableTraits;
930 // std::map with string key
931 template <class K, class T, class C, class A>
932 struct KeyableTraits<
933 std::map<K, T, C, A>,
934 typename KeyFromStringPiece<K>::enabled>
935 : public KeyableTraitsAssoc<std::map<K, T, C, A>> {
938 // std::unordered_map with string key
939 template <class K, class T, class H, class E, class A>
940 struct KeyableTraits<
941 std::unordered_map<K, T, H, E, A>,
942 typename KeyFromStringPiece<K>::enabled>
943 : public KeyableTraitsAssoc<std::unordered_map<K, T, H, E, A>> {
946 } // namespace detail
948 // Partial specialization of FormatValue for string-keyed containers
952 typename detail::KeyableTraits<T>::enabled> {
954 explicit FormatValue(const T& val) : val_(val) { }
956 template <class FormatCallback>
957 void format(FormatArg& arg, FormatCallback& cb) const {
958 FormatValue<typename std::decay<
959 typename detail::KeyableTraits<T>::value_type>::type>(
960 detail::KeyableTraits<T>::at(
961 val_, arg.splitKey())).format(arg, cb);
968 template <class Container, class Value>
970 detail::DefaultValueWrapper<Container, Value>,
971 typename detail::KeyableTraits<Container>::enabled> {
973 explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
976 template <class FormatCallback>
977 void format(FormatArg& arg, FormatCallback& cb) const {
978 FormatValue<typename std::decay<
979 typename detail::KeyableTraits<Container>::value_type>::type>(
980 detail::KeyableTraits<Container>::at(
983 val_.defaultValue)).format(arg, cb);
987 const detail::DefaultValueWrapper<Container, Value>& val_;
990 // Partial specialization of FormatValue for pairs
991 template <class A, class B>
992 class FormatValue<std::pair<A, B>> {
994 explicit FormatValue(const std::pair<A, B>& val) : val_(val) { }
996 template <class FormatCallback>
997 void format(FormatArg& arg, FormatCallback& cb) const {
998 int key = arg.splitIntKey();
1001 FormatValue<typename std::decay<A>::type>(val_.first).format(arg, cb);
1004 FormatValue<typename std::decay<B>::type>(val_.second).format(arg, cb);
1007 arg.error("invalid index for pair");
1012 const std::pair<A, B>& val_;
1015 // Partial specialization of FormatValue for tuples
1016 template <class... Args>
1017 class FormatValue<std::tuple<Args...>> {
1018 typedef std::tuple<Args...> Tuple;
1020 explicit FormatValue(const Tuple& val) : val_(val) { }
1022 template <class FormatCallback>
1023 void format(FormatArg& arg, FormatCallback& cb) const {
1024 int key = arg.splitIntKey();
1025 arg.enforce(key >= 0, "tuple index must be non-negative");
1026 doFormat(key, arg, cb);
1030 static constexpr size_t valueCount = std::tuple_size<Tuple>::value;
1032 template <size_t K, class Callback>
1033 typename std::enable_if<K == valueCount>::type
1034 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1035 arg.enforce("tuple index out of range, max=", i);
1038 template <size_t K, class Callback>
1039 typename std::enable_if<(K < valueCount)>::type
1040 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
1042 FormatValue<typename std::decay<
1043 typename std::tuple_element<K, Tuple>::type>::type>(
1044 std::get<K>(val_)).format(arg, cb);
1046 doFormatFrom<K+1>(i, arg, cb);
1050 template <class Callback>
1051 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
1052 return doFormatFrom<0>(i, arg, cb);
1058 // Partial specialization of FormatValue for nested Formatters
1059 template <bool containerMode, class... Args,
1060 template <bool, class...> class F>
1061 class FormatValue<F<containerMode, Args...>,
1062 typename std::enable_if<detail::IsFormatter<
1063 F<containerMode, Args...>>::value>::type> {
1064 typedef typename F<containerMode, Args...>::BaseType FormatterValue;
1067 explicit FormatValue(const FormatterValue& f) : f_(f) { }
1069 template <class FormatCallback>
1070 void format(FormatArg& arg, FormatCallback& cb) const {
1071 format_value::formatFormatter(f_, arg, cb);
1074 const FormatterValue& f_;
1078 * Formatter objects can be appended to strings, and therefore they're
1079 * compatible with folly::toAppend and folly::to.
1081 template <class Tgt, class Derived, bool containerMode, class... Args>
1082 typename std::enable_if<IsSomeString<Tgt>::value>::type toAppend(
1083 const BaseFormatter<Derived, containerMode, Args...>& value, Tgt* result) {
1084 value.appendTo(*result);
1087 } // namespace folly
1089 #pragma GCC diagnostic pop