Support dynamic field width in folly::format()
[folly.git] / folly / Format-inl.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifndef FOLLY_FORMAT_H_
18 #error This file may only be included from Format.h.
19 #endif
20
21 #include <array>
22 #include <deque>
23 #include <map>
24 #include <unordered_map>
25 #include <vector>
26
27 #include <folly/Exception.h>
28 #include <folly/FormatTraits.h>
29 #include <folly/Traits.h>
30
31 // Ignore -Wformat-nonliteral warnings within this file
32 #pragma GCC diagnostic push
33 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
34
35 namespace folly {
36
37 namespace detail {
38
39 // Updates the end of the buffer after the comma separators have been added.
40 void insertThousandsGroupingUnsafe(char* start_buffer, char** end_buffer);
41
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];
46
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);
50
51 /**
52  * Convert an unsigned to hex, using repr (which maps from each possible
53  * 2-hex-bytes value to the 2-character representation).
54  *
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).
59  */
60 template <class Uint>
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) {
66     auto b = v & 0xff;
67     bufLen -= 2;
68     buffer[bufLen] = repr[b][0];
69     buffer[bufLen + 1] = repr[b][1];
70   }
71   buffer[--bufLen] = repr[v][1];
72   if (v >= 16) {
73     buffer[--bufLen] = repr[v][0];
74   }
75   return bufLen;
76 }
77
78 /**
79  * Convert an unsigned to hex, using lower-case letters for the digits
80  * above 9.  See the comments for uintToHex.
81  */
82 template <class Uint>
83 inline size_t uintToHexLower(char* buffer, size_t bufLen, Uint v) {
84   return uintToHex(buffer, bufLen, v, formatHexLower);
85 }
86
87 /**
88  * Convert an unsigned to hex, using upper-case letters for the digits
89  * above 9.  See the comments for uintToHex.
90  */
91 template <class Uint>
92 inline size_t uintToHexUpper(char* buffer, size_t bufLen, Uint v) {
93   return uintToHex(buffer, bufLen, v, formatHexUpper);
94 }
95
96 /**
97  * Convert an unsigned to octal.
98  *
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).
103  */
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) {
110     auto b = v & 0x1ff;
111     bufLen -= 3;
112     buffer[bufLen] = repr[b][0];
113     buffer[bufLen + 1] = repr[b][1];
114     buffer[bufLen + 2] = repr[b][2];
115   }
116   buffer[--bufLen] = repr[v][2];
117   if (v >= 8) {
118     buffer[--bufLen] = repr[v][1];
119   }
120   if (v >= 64) {
121     buffer[--bufLen] = repr[v][0];
122   }
123   return bufLen;
124 }
125
126 /**
127  * Convert an unsigned to binary.
128  *
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).
133  */
134 template <class Uint>
135 size_t uintToBinary(char* buffer, size_t bufLen, Uint v) {
136   auto& repr = formatBinary;
137   if (v == 0) {
138     buffer[--bufLen] = '0';
139     return bufLen;
140   }
141   for (; v; v >>= 7, v >>= 1) {
142     auto b = v & 0xff;
143     bufLen -= 8;
144     memcpy(buffer + bufLen, &(repr[b][0]), 8);
145   }
146   while (buffer[bufLen] == '0') {
147     ++bufLen;
148   }
149   return bufLen;
150 }
151
152 }  // namespace detail
153
154 template <class Derived, bool containerMode, class... Args>
155 BaseFormatter<Derived, containerMode, Args...>::BaseFormatter(StringPiece str,
156                                                               Args&&... args)
157     : str_(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");
162 }
163
164 template <class Derived, bool containerMode, class... Args>
165 template <class Output>
166 void BaseFormatter<Derived, containerMode, Args...>::operator()(Output& out)
167     const {
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) {
172     auto p = s.begin();
173     auto end = s.end();
174     while (p != end) {
175       auto q = static_cast<const char*>(memchr(p, '}', end - p));
176       if (!q) {
177         out(StringPiece(p, end));
178         break;
179       }
180       ++q;
181       out(StringPiece(p, q));
182       p = q;
183
184       if (p == end || *p != '}') {
185         throw BadFormatArg("folly::format: single '}' in format string");
186       }
187       ++p;
188     }
189   };
190
191   auto p = str_.begin();
192   auto end = str_.end();
193
194   int nextArg = 0;
195   bool hasDefaultArgIndex = false;
196   bool hasExplicitArgIndex = false;
197   while (p != end) {
198     auto q = static_cast<const char*>(memchr(p, '{', end - p));
199     if (!q) {
200       outputString(StringPiece(p, end));
201       break;
202     }
203     outputString(StringPiece(p, q));
204     p = q + 1;
205
206     if (p == end) {
207       throw BadFormatArg("folly::format: '}' at end of format string");
208     }
209
210     // "{{" -> "{"
211     if (*p == '{') {
212       out(StringPiece(p, 1));
213       ++p;
214       continue;
215     }
216
217     // Format string
218     q = static_cast<const char*>(memchr(p, '}', end - p));
219     if (q == nullptr) {
220       throw BadFormatArg("folly::format: missing ending '}'");
221     }
222     FormatArg arg(StringPiece(p, q));
223     p = q + 1;
224
225     int argIndex = 0;
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()");
230       if (piece.empty()) {
231         arg.setNextIntKey(nextArg++);
232         hasDefaultArgIndex = true;
233       } else {
234         arg.setNextKey(piece);
235         hasExplicitArgIndex = true;
236       }
237     } else {
238       if (piece.empty()) {
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);
244         }
245
246         argIndex = nextArg++;
247         hasDefaultArgIndex = true;
248       } else {
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);
253         }
254
255         try {
256           argIndex = to<int>(piece);
257         } catch (const std::out_of_range& e) {
258           arg.error("argument index must be integer");
259         }
260         arg.enforce(argIndex >= 0, "argument index must be non-negative");
261         hasExplicitArgIndex = true;
262       }
263     }
264
265     if (hasDefaultArgIndex && hasExplicitArgIndex) {
266       throw BadFormatArg(
267           "folly::format: may not have both default and explicit arg indexes");
268     }
269
270     doFormat(argIndex, arg, out);
271   }
272 }
273
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);
279     if (n < sp.size()) {
280       throwSystemError("Formatter writeTo", "fwrite failed");
281     }
282   };
283   formatter(writer);
284 }
285
286 namespace format_value {
287
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");
292   }
293   if (arg.precision != FormatArg::kDefaultPrecision && arg.precision < 0) {
294     throw BadFormatArg("folly::format: invalid precision");
295   }
296
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.
300
301   if (arg.precision != FormatArg::kDefaultPrecision &&
302       val.size() > static_cast<size_t>(arg.precision)) {
303     val.reset(val.data(), arg.precision);
304   }
305
306   constexpr int padBufSize = 128;
307   char padBuf[padBufSize];
308
309   // Output padding, no more than padBufSize at once
310   auto pad = [&padBuf, &cb, padBufSize] (int chars) {
311     while (chars) {
312       int n = std::min(chars, padBufSize);
313       cb(StringPiece(padBuf, n));
314       chars -= n;
315     }
316   };
317
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));
324
325     switch (arg.align) {
326     case FormatArg::Align::DEFAULT:
327     case FormatArg::Align::LEFT:
328       padRemaining = padChars;
329       break;
330     case FormatArg::Align::CENTER:
331       pad(padChars / 2);
332       padRemaining = padChars - padChars / 2;
333       break;
334     case FormatArg::Align::RIGHT:
335     case FormatArg::Align::PAD_AFTER_SIGN:
336       pad(padChars);
337       break;
338     default:
339       abort();
340       break;
341     }
342   }
343
344   cb(val);
345
346   if (padRemaining) {
347     pad(padRemaining);
348   }
349 }
350
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);
363   }
364   format_value::formatString(val, arg, cb);
365 }
366
367 template <class FormatCallback,
368           class Derived,
369           bool containerMode,
370           class... Args>
371 void formatFormatter(
372     const BaseFormatter<Derived, containerMode, Args...>& formatter,
373     FormatArg& arg,
374     FormatCallback& cb) {
375   if (arg.width == FormatArg::kDefaultWidth &&
376       arg.precision == FormatArg::kDefaultPrecision) {
377     // nothing to do
378     formatter(cb);
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);
384   } else {
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);
390         arg.precision -= sz;
391       }
392       if (!sp.empty()) {
393         cb(sp);
394         if (arg.width != FormatArg::kDefaultWidth) {
395           arg.width = std::max(arg.width - sz, 0);
396         }
397       }
398     };
399     formatter(fn);
400     if (arg.width != FormatArg::kDefaultWidth && arg.width != 0) {
401       // Rely on formatString to do appropriate padding
402       format_value::formatString(StringPiece(), arg, cb);
403     }
404   }
405 }
406
407 }  // namespace format_value
408
409 // Definitions for default FormatValue classes
410
411 // Integral types (except bool)
412 template <class T>
413 class FormatValue<
414   T, typename std::enable_if<
415     std::is_integral<T>::value &&
416     !std::is_same<T, bool>::value>::type>
417   {
418  public:
419   explicit FormatValue(T val) : val_(val) { }
420
421   T getValue() const {
422     return val_;
423   }
424
425   template <class FormatCallback>
426   void format(FormatArg& arg, FormatCallback& cb) const {
427     arg.validate(FormatArg::Type::INTEGER);
428     doFormat(arg, cb);
429   }
430
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';
436     }
437
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;
441     UT uval;
442     char sign;
443     if (std::is_signed<T>::value) {
444       if (folly::is_negative(val_)) {
445         uval = static_cast<UT>(-val_);
446         sign = '-';
447       } else {
448         uval = static_cast<UT>(val_);
449         switch (arg.sign) {
450         case FormatArg::Sign::PLUS_OR_MINUS:
451           sign = '+';
452           break;
453         case FormatArg::Sign::SPACE_OR_MINUS:
454           sign = ' ';
455           break;
456         default:
457           sign = '\0';
458           break;
459         }
460       }
461     } else {
462       uval = val_;
463       sign = '\0';
464
465       arg.enforce(arg.sign == FormatArg::Sign::DEFAULT,
466                   "sign specifications not allowed for unsigned values");
467     }
468
469     // max of:
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!)
474     // + nul terminator
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;
480
481     int prefixLen = 0;
482     switch (presentation) {
483     case 'n': {
484       arg.enforce(!arg.basePrefix,
485                   "base prefix not allowed with '", presentation,
486                   "' specifier");
487
488       arg.enforce(!arg.thousandsSeparator,
489                   "cannot use ',' with the '", presentation,
490                   "' specifier");
491
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
496       // happen.
497       assert(len < valBuf + valBufSize - valBufBegin);
498       valBufEnd = valBufBegin + len;
499       break;
500     }
501     case 'd':
502       arg.enforce(!arg.basePrefix,
503                   "base prefix not allowed with '", presentation,
504                   "' specifier");
505       valBufBegin = valBuf + 3;  // room for sign and base prefix
506
507       // Use uintToBuffer, faster than sprintf
508       valBufEnd = valBufBegin + uint64ToBufferUnsafe(uval, valBufBegin);
509       if (arg.thousandsSeparator) {
510         detail::insertThousandsGroupingUnsafe(valBufBegin, &valBufEnd);
511       }
512       break;
513     case 'c':
514       arg.enforce(!arg.basePrefix,
515                   "base prefix not allowed with '", presentation,
516                   "' specifier");
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;
523       break;
524     case 'o':
525     case 'O':
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';
533         prefixLen = 1;
534       }
535       break;
536     case 'x':
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,
542                                                     uval);
543       if (arg.basePrefix) {
544         *--valBufBegin = 'x';
545         *--valBufBegin = '0';
546         prefixLen = 2;
547       }
548       break;
549     case 'X':
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,
555                                                     uval);
556       if (arg.basePrefix) {
557         *--valBufBegin = 'X';
558         *--valBufBegin = '0';
559         prefixLen = 2;
560       }
561       break;
562     case 'b':
563     case 'B':
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,
569                                                   uval);
570       if (arg.basePrefix) {
571         *--valBufBegin = presentation;  // 0b or 0B
572         *--valBufBegin = '0';
573         prefixLen = 2;
574       }
575       break;
576     default:
577       arg.error("invalid specifier '", presentation, "'");
578     }
579
580     if (sign) {
581       *--valBufBegin = sign;
582       ++prefixLen;
583     }
584
585     format_value::formatNumber(StringPiece(valBufBegin, valBufEnd), prefixLen,
586                                arg, cb);
587   }
588
589  private:
590   T val_;
591 };
592
593 // Bool
594 template <>
595 class FormatValue<bool> {
596  public:
597   explicit FormatValue(bool val) : val_(val) { }
598
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);
604     } else {  // number
605       FormatValue<int>(val_).format(arg, cb);
606     }
607   }
608
609  private:
610   bool val_;
611 };
612
613 // double
614 template <>
615 class FormatValue<double> {
616  public:
617   explicit FormatValue(double val) : val_(val) { }
618
619   template <class FormatCallback>
620   void format(FormatArg& arg, FormatCallback& cb) const {
621     fbstring piece;
622     int prefixLen;
623     formatHelper(piece, prefixLen, arg);
624     format_value::formatNumber(piece, prefixLen, arg, cb);
625   }
626
627  private:
628   void formatHelper(fbstring& piece, int& prefixLen, FormatArg& arg) const;
629
630   double val_;
631 };
632
633 // float (defer to double)
634 template <>
635 class FormatValue<float> {
636  public:
637   explicit FormatValue(float val) : val_(val) { }
638
639   template <class FormatCallback>
640   void format(FormatArg& arg, FormatCallback& cb) const {
641     FormatValue<double>(val_).format(arg, cb);
642   }
643
644  private:
645   float val_;
646 };
647
648 // Sring-y types (implicitly convertible to StringPiece, except char*)
649 template <class T>
650 class FormatValue<
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>
656   {
657  public:
658   explicit FormatValue(StringPiece val) : val_(val) { }
659
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);
668     } else {
669       FormatValue<char>(val_.at(arg.splitIntKey())).format(arg, cb);
670     }
671   }
672
673  private:
674   StringPiece val_;
675 };
676
677 // Null
678 template <>
679 class FormatValue<std::nullptr_t> {
680  public:
681   explicit FormatValue(std::nullptr_t) { }
682
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);
689   }
690 };
691
692 // Partial specialization of FormatValue for char*
693 template <class T>
694 class FormatValue<
695   T*,
696   typename std::enable_if<
697       std::is_same<char, typename std::decay<T>::type>::value>::type>
698   {
699  public:
700   explicit FormatValue(T* val) : val_(val) { }
701
702   template <class FormatCallback>
703   void format(FormatArg& arg, FormatCallback& cb) const {
704     if (arg.keyEmpty()) {
705       if (!val_) {
706         FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
707       } else {
708         FormatValue<StringPiece>(val_).format(arg, cb);
709       }
710     } else {
711       FormatValue<typename std::decay<T>::type>(
712           val_[arg.splitIntKey()]).format(arg, cb);
713     }
714   }
715
716  private:
717   T* val_;
718 };
719
720 // Partial specialization of FormatValue for void*
721 template <class T>
722 class FormatValue<
723   T*,
724   typename std::enable_if<
725       std::is_same<void, typename std::decay<T>::type>::value>::type>
726   {
727  public:
728   explicit FormatValue(T* val) : val_(val) { }
729
730   template <class FormatCallback>
731   void format(FormatArg& arg, FormatCallback& cb) const {
732     if (!val_) {
733       FormatValue<std::nullptr_t>(nullptr).format(arg, cb);
734     } else {
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;
743       }
744       FormatValue<uintptr_t>(
745           reinterpret_cast<uintptr_t>(val_)).doFormat(arg, cb);
746     }
747   }
748
749  private:
750   T* val_;
751 };
752
753 template <class T, class = void>
754 class TryFormatValue {
755  public:
756   template <class FormatCallback>
757   static void formatOrFail(T& value, FormatArg& arg, FormatCallback& cb) {
758     arg.error("No formatter available for this type");
759   }
760 };
761
762 template <class T>
763 class TryFormatValue<
764   T,
765   typename std::enable_if<
766       0 < sizeof(FormatValue<typename std::decay<T>::type>)>::type>
767   {
768  public:
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);
772   }
773 };
774
775 // Partial specialization of FormatValue for other pointers
776 template <class T>
777 class FormatValue<
778   T*,
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>
782   {
783  public:
784   explicit FormatValue(T* val) : val_(val) { }
785
786   template <class FormatCallback>
787   void format(FormatArg& arg, FormatCallback& cb) const {
788     if (arg.keyEmpty()) {
789       FormatValue<void*>((void*)val_).format(arg, cb);
790     } else {
791       TryFormatValue<T>::formatOrFail(val_[arg.splitIntKey()], arg, cb);
792     }
793   }
794  private:
795   T* val_;
796 };
797
798 namespace detail {
799
800 // std::array
801 template <class T, size_t N>
802 struct IndexableTraits<std::array<T, N>>
803   : public IndexableTraitsSeq<std::array<T, N>> {
804 };
805
806 // std::vector
807 template <class T, class A>
808 struct IndexableTraits<std::vector<T, A>>
809   : public IndexableTraitsSeq<std::vector<T, A>> {
810 };
811
812 // std::deque
813 template <class T, class A>
814 struct IndexableTraits<std::deque<T, A>>
815   : public IndexableTraitsSeq<std::deque<T, A>> {
816 };
817
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>> {
824 };
825
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>> {
832 };
833
834 }  // namespace detail
835
836 // Partial specialization of FormatValue for integer-indexable containers
837 template <class T>
838 class FormatValue<
839   T,
840   typename detail::IndexableTraits<T>::enabled> {
841  public:
842   explicit FormatValue(const T& val) : val_(val) { }
843
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);
850   }
851
852  private:
853   const T& val_;
854 };
855
856 template <class Container, class Value>
857 class FormatValue<
858   detail::DefaultValueWrapper<Container, Value>,
859   typename detail::IndexableTraits<Container>::enabled> {
860  public:
861   explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
862     : val_(val) { }
863
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(
869               val_.container,
870               arg.splitIntKey(),
871               val_.defaultValue)).format(arg, cb);
872   }
873
874  private:
875   const detail::DefaultValueWrapper<Container, Value>& val_;
876 };
877
878 namespace detail {
879
880 // Define enabled, key_type, convert from StringPiece to the key types
881 // that we support
882 template <class T> struct KeyFromStringPiece;
883
884 // std::string
885 template <>
886 struct KeyFromStringPiece<std::string> : public FormatTraitsBase {
887   typedef std::string key_type;
888   static std::string convert(StringPiece s) {
889     return s.toString();
890   }
891   typedef void enabled;
892 };
893
894 // fbstring
895 template <>
896 struct KeyFromStringPiece<fbstring> : public FormatTraitsBase {
897   typedef fbstring key_type;
898   static fbstring convert(StringPiece s) {
899     return s.toFbstring();
900   }
901 };
902
903 // StringPiece
904 template <>
905 struct KeyFromStringPiece<StringPiece> : public FormatTraitsBase {
906   typedef StringPiece key_type;
907   static StringPiece convert(StringPiece s) {
908     return s;
909   }
910 };
911
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));
918   }
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;
923   }
924 };
925
926 // Define enabled, key_type, value_type, at() for supported string-keyed
927 // types
928 template <class T, class Enabled=void> struct KeyableTraits;
929
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>> {
936 };
937
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>> {
944 };
945
946 }  // namespace detail
947
948 // Partial specialization of FormatValue for string-keyed containers
949 template <class T>
950 class FormatValue<
951   T,
952   typename detail::KeyableTraits<T>::enabled> {
953  public:
954   explicit FormatValue(const T& val) : val_(val) { }
955
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);
962   }
963
964  private:
965   const T& val_;
966 };
967
968 template <class Container, class Value>
969 class FormatValue<
970   detail::DefaultValueWrapper<Container, Value>,
971   typename detail::KeyableTraits<Container>::enabled> {
972  public:
973   explicit FormatValue(const detail::DefaultValueWrapper<Container, Value>& val)
974     : val_(val) { }
975
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(
981               val_.container,
982               arg.splitKey(),
983               val_.defaultValue)).format(arg, cb);
984   }
985
986  private:
987   const detail::DefaultValueWrapper<Container, Value>& val_;
988 };
989
990 // Partial specialization of FormatValue for pairs
991 template <class A, class B>
992 class FormatValue<std::pair<A, B>> {
993  public:
994   explicit FormatValue(const std::pair<A, B>& val) : val_(val) { }
995
996   template <class FormatCallback>
997   void format(FormatArg& arg, FormatCallback& cb) const {
998     int key = arg.splitIntKey();
999     switch (key) {
1000     case 0:
1001       FormatValue<typename std::decay<A>::type>(val_.first).format(arg, cb);
1002       break;
1003     case 1:
1004       FormatValue<typename std::decay<B>::type>(val_.second).format(arg, cb);
1005       break;
1006     default:
1007       arg.error("invalid index for pair");
1008     }
1009   }
1010
1011  private:
1012   const std::pair<A, B>& val_;
1013 };
1014
1015 // Partial specialization of FormatValue for tuples
1016 template <class... Args>
1017 class FormatValue<std::tuple<Args...>> {
1018   typedef std::tuple<Args...> Tuple;
1019  public:
1020   explicit FormatValue(const Tuple& val) : val_(val) { }
1021
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);
1027   }
1028
1029  private:
1030   static constexpr size_t valueCount = std::tuple_size<Tuple>::value;
1031
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);
1036   }
1037
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 {
1041     if (i == K) {
1042       FormatValue<typename std::decay<
1043         typename std::tuple_element<K, Tuple>::type>::type>(
1044           std::get<K>(val_)).format(arg, cb);
1045     } else {
1046       doFormatFrom<K+1>(i, arg, cb);
1047     }
1048   }
1049
1050   template <class Callback>
1051   void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
1052     return doFormatFrom<0>(i, arg, cb);
1053   }
1054
1055   const Tuple& val_;
1056 };
1057
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;
1065
1066  public:
1067   explicit FormatValue(const FormatterValue& f) : f_(f) { }
1068
1069   template <class FormatCallback>
1070   void format(FormatArg& arg, FormatCallback& cb) const {
1071     format_value::formatFormatter(f_, arg, cb);
1072   }
1073  private:
1074   const FormatterValue& f_;
1075 };
1076
1077 /**
1078  * Formatter objects can be appended to strings, and therefore they're
1079  * compatible with folly::toAppend and folly::to.
1080  */
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);
1085 }
1086
1087 }  // namespace folly
1088
1089 #pragma GCC diagnostic pop