improve ThreadLocalBenchmark
[folly.git] / folly / Format.h
1 /*
2  * Copyright 2017 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 #pragma once
18 #define FOLLY_FORMAT_H_
19
20 #include <cstdio>
21 #include <stdexcept>
22 #include <tuple>
23 #include <type_traits>
24
25 #include <folly/Conv.h>
26 #include <folly/FormatArg.h>
27 #include <folly/Range.h>
28 #include <folly/String.h>
29 #include <folly/Traits.h>
30
31 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
32 FOLLY_PUSH_WARNING
33 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
34
35 namespace folly {
36
37 // forward declarations
38 template <bool containerMode, class... Args>
39 class Formatter;
40 template <class... Args>
41 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
42 template <class C>
43 Formatter<true, C> vformat(StringPiece fmt, C&& container);
44 template <class T, class Enable = void>
45 class FormatValue;
46
47 // meta-attribute to identify formatters in this sea of template weirdness
48 namespace detail {
49 class FormatterTag {};
50 } // namespace detail
51
52 /**
53  * Formatter class.
54  *
55  * Note that this class is tricky, as it keeps *references* to its lvalue
56  * arguments (while it takes ownership of the temporaries), and it doesn't
57  * copy the passed-in format string. Thankfully, you can't use this
58  * directly, you have to use format(...) below.
59  */
60
61 /* BaseFormatter class.
62  * Overridable behaviours:
63  * You may override the actual formatting of positional parameters in
64  * `doFormatArg`. The Formatter class provides the default implementation.
65  *
66  * You may also override `doFormat` and `getSizeArg`. These override points were
67  * added to permit static analysis of format strings, when it is inconvenient
68  * or impossible to instantiate a BaseFormatter with the correct storage
69  */
70 template <class Derived, bool containerMode, class... Args>
71 class BaseFormatter {
72  public:
73   /**
74    * Append to output.  out(StringPiece sp) may be called (more than once)
75    */
76   template <class Output>
77   void operator()(Output& out) const;
78
79   /**
80    * Append to a string.
81    */
82   template <class Str>
83   typename std::enable_if<IsSomeString<Str>::value>::type appendTo(
84       Str& str) const {
85     auto appender = [&str](StringPiece s) { str.append(s.data(), s.size()); };
86     (*this)(appender);
87   }
88
89   /**
90    * Conversion to string
91    */
92   std::string str() const {
93     std::string s;
94     appendTo(s);
95     return s;
96   }
97
98   /**
99    * Conversion to fbstring
100    */
101   fbstring fbstr() const {
102     fbstring s;
103     appendTo(s);
104     return s;
105   }
106
107   /**
108    * Metadata to identify generated children of BaseFormatter
109    */
110   typedef detail::FormatterTag IsFormatter;
111   typedef BaseFormatter BaseType;
112
113  private:
114   typedef std::tuple<Args...> ValueTuple;
115   static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
116
117   Derived const& asDerived() const {
118     return *static_cast<const Derived*>(this);
119   }
120
121   template <size_t K, class Callback>
122   typename std::enable_if<K == valueCount>::type
123   doFormatFrom(size_t i, FormatArg& arg, Callback& /*cb*/) const {
124     arg.error("argument index out of range, max=", i);
125   }
126
127   template <size_t K, class Callback>
128   typename std::enable_if<(K < valueCount)>::type
129   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
130     if (i == K) {
131       asDerived().template doFormatArg<K>(arg, cb);
132     } else {
133       doFormatFrom<K + 1>(i, arg, cb);
134     }
135   }
136
137   template <class Callback>
138   void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
139     return doFormatFrom<0>(i, arg, cb);
140   }
141
142   template <size_t K>
143   typename std::enable_if<K == valueCount, int>::type getSizeArgFrom(
144       size_t i,
145       const FormatArg& arg) const {
146     arg.error("argument index out of range, max=", i);
147   }
148
149   template <class T>
150   typename std::enable_if<
151       std::is_integral<T>::value && !std::is_same<T, bool>::value,
152       int>::type
153   getValue(const FormatValue<T>& format, const FormatArg&) const {
154     return static_cast<int>(format.getValue());
155   }
156
157   template <class T>
158   typename std::enable_if<
159       !std::is_integral<T>::value || std::is_same<T, bool>::value,
160       int>::type
161   getValue(const FormatValue<T>&, const FormatArg& arg) const {
162     arg.error("dynamic field width argument must be integral");
163   }
164
165   template <size_t K>
166       typename std::enable_if <
167       K<valueCount, int>::type getSizeArgFrom(size_t i, const FormatArg& arg)
168           const {
169     if (i == K) {
170       return getValue(getFormatValue<K>(), arg);
171     }
172     return getSizeArgFrom<K + 1>(i, arg);
173   }
174
175   int getSizeArg(size_t i, const FormatArg& arg) const {
176     return getSizeArgFrom<0>(i, arg);
177   }
178
179   StringPiece str_;
180
181  protected:
182   explicit BaseFormatter(StringPiece str, Args&&... args);
183
184   // Not copyable
185   BaseFormatter(const BaseFormatter&) = delete;
186   BaseFormatter& operator=(const BaseFormatter&) = delete;
187
188   // Movable, but the move constructor and assignment operator are private,
189   // for the exclusive use of format() (below).  This way, you can't create
190   // a Formatter object, but can handle references to it (for streaming,
191   // conversion to string, etc) -- which is good, as Formatter objects are
192   // dangerous (they may hold references).
193   BaseFormatter(BaseFormatter&&) = default;
194   BaseFormatter& operator=(BaseFormatter&&) = default;
195
196   template <size_t K>
197   using ArgType = typename std::tuple_element<K, ValueTuple>::type;
198
199   template <size_t K>
200   FormatValue<typename std::decay<ArgType<K>>::type> getFormatValue() const {
201     return FormatValue<typename std::decay<ArgType<K>>::type>(
202         std::get<K>(values_));
203   }
204
205   ValueTuple values_;
206 };
207
208 template <bool containerMode, class... Args>
209 class Formatter : public BaseFormatter<
210                       Formatter<containerMode, Args...>,
211                       containerMode,
212                       Args...> {
213  private:
214   explicit Formatter(StringPiece& str, Args&&... args)
215       : BaseFormatter<
216             Formatter<containerMode, Args...>,
217             containerMode,
218             Args...>(str, std::forward<Args>(args)...) {
219     static_assert(
220         !containerMode || sizeof...(Args) == 1,
221         "Exactly one argument required in container mode");
222   }
223
224   template <size_t K, class Callback>
225   void doFormatArg(FormatArg& arg, Callback& cb) const {
226     this->template getFormatValue<K>().format(arg, cb);
227   }
228
229   friend class BaseFormatter<
230       Formatter<containerMode, Args...>,
231       containerMode,
232       Args...>;
233
234   template <class... A>
235   friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
236   template <class C>
237   friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
238 };
239
240 /**
241  * Formatter objects can be written to streams.
242  */
243 template <bool containerMode, class... Args>
244 std::ostream& operator<<(
245     std::ostream& out,
246     const Formatter<containerMode, Args...>& formatter) {
247   auto writer = [&out](StringPiece sp) {
248     out.write(sp.data(), std::streamsize(sp.size()));
249   };
250   formatter(writer);
251   return out;
252 }
253
254 /**
255  * Formatter objects can be written to stdio FILEs.
256  */
257 template <class Derived, bool containerMode, class... Args>
258 void writeTo(
259     FILE* fp,
260     const BaseFormatter<Derived, containerMode, Args...>& formatter);
261
262 /**
263  * Create a formatter object.
264  *
265  * std::string formatted = format("{} {}", 23, 42).str();
266  * LOG(INFO) << format("{} {}", 23, 42);
267  * writeTo(stdout, format("{} {}", 23, 42));
268  */
269 template <class... Args>
270 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
271   return Formatter<false, Args...>(fmt, std::forward<Args>(args)...);
272 }
273
274 /**
275  * Like format(), but immediately returns the formatted string instead of an
276  * intermediate format object.
277  */
278 template <class... Args>
279 inline std::string sformat(StringPiece fmt, Args&&... args) {
280   return format(fmt, std::forward<Args>(args)...).str();
281 }
282
283 /**
284  * Create a formatter object that takes one argument (of container type)
285  * and uses that container to get argument values from.
286  *
287  * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
288  *
289  * The following are equivalent:
290  * format("{0[hello]} {0[answer]}", map);
291  *
292  * vformat("{hello} {answer}", map);
293  *
294  * but the latter is cleaner.
295  */
296 template <class Container>
297 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
298   return Formatter<true, Container>(fmt, std::forward<Container>(container));
299 }
300
301 /**
302  * Like vformat(), but immediately returns the formatted string instead of an
303  * intermediate format object.
304  */
305 template <class Container>
306 inline std::string svformat(StringPiece fmt, Container&& container) {
307   return vformat(fmt, std::forward<Container>(container)).str();
308 }
309
310 /**
311  * Exception class thrown when a format key is not found in the given
312  * associative container keyed by strings. We inherit std::out_of_range for
313  * compatibility with callers that expect exception to be thrown directly
314  * by std::map or std::unordered_map.
315  *
316  * Having the key be at the end of the message string, we can access it by
317  * simply adding its offset to what(). Not storing separate std::string key
318  * makes the exception type small and noexcept-copyable like std::out_of_range,
319  * and therefore able to fit in-situ in exception_wrapper.
320  */
321 class FormatKeyNotFoundException : public std::out_of_range {
322  public:
323   explicit FormatKeyNotFoundException(StringPiece key);
324
325   char const* key() const noexcept {
326     return what() + kMessagePrefix.size();
327   }
328
329  private:
330   static constexpr StringPiece const kMessagePrefix = "format key not found: ";
331 };
332
333 namespace detail {
334 [[noreturn]] void throwFormatKeyNotFoundException(StringPiece key);
335 } // namespace detail
336
337 /**
338  * Wrap a sequence or associative container so that out-of-range lookups
339  * return a default value rather than throwing an exception.
340  *
341  * Usage:
342  * format("[no_such_key"], defaulted(map, 42))  -> 42
343  */
344 namespace detail {
345 template <class Container, class Value>
346 struct DefaultValueWrapper {
347   DefaultValueWrapper(const Container& container, const Value& defaultValue)
348       : container(container), defaultValue(defaultValue) {}
349
350   const Container& container;
351   const Value& defaultValue;
352 };
353 } // namespace detail
354
355 template <class Container, class Value>
356 detail::DefaultValueWrapper<Container, Value> defaulted(
357     const Container& c,
358     const Value& v) {
359   return detail::DefaultValueWrapper<Container, Value>(c, v);
360 }
361
362 /**
363  * Append formatted output to a string.
364  *
365  * std::string foo;
366  * format(&foo, "{} {}", 42, 23);
367  *
368  * Shortcut for toAppend(format(...), &foo);
369  */
370 template <class Str, class... Args>
371 typename std::enable_if<IsSomeString<Str>::value>::type
372 format(Str* out, StringPiece fmt, Args&&... args) {
373   format(fmt, std::forward<Args>(args)...).appendTo(*out);
374 }
375
376 /**
377  * Append vformatted output to a string.
378  */
379 template <class Str, class Container>
380 typename std::enable_if<IsSomeString<Str>::value>::type
381 vformat(Str* out, StringPiece fmt, Container&& container) {
382   vformat(fmt, std::forward<Container>(container)).appendTo(*out);
383 }
384
385 /**
386  * Utilities for all format value specializations.
387  */
388 namespace format_value {
389
390 /**
391  * Format a string in "val", obeying appropriate alignment, padding, width,
392  * and precision.  Treats Align::DEFAULT as Align::LEFT, and
393  * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
394  * number-specific formatting.
395  */
396 template <class FormatCallback>
397 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
398
399 /**
400  * Format a number in "val"; the first prefixLen characters form the prefix
401  * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
402  * is Align::PAD_AFTER_SIGN.  Treats Align::DEFAULT as Align::LEFT.  Ignores
403  * arg.precision, as that has a different meaning for numbers (not "maximum
404  * field width")
405  */
406 template <class FormatCallback>
407 void formatNumber(
408     StringPiece val,
409     int prefixLen,
410     FormatArg& arg,
411     FormatCallback& cb);
412
413 /**
414  * Format a Formatter object recursively.  Behaves just like
415  * formatString(fmt.str(), arg, cb); but avoids creating a temporary
416  * string if possible.
417  */
418 template <
419     class FormatCallback,
420     class Derived,
421     bool containerMode,
422     class... Args>
423 void formatFormatter(
424     const BaseFormatter<Derived, containerMode, Args...>& formatter,
425     FormatArg& arg,
426     FormatCallback& cb);
427
428 } // namespace format_value
429
430 /*
431  * Specialize folly::FormatValue for your type.
432  *
433  * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
434  * guaranteed to stay alive until the FormatValue object is destroyed, so you
435  * may keep a reference (or pointer) to it instead of making a copy.
436  *
437  * You must define
438  *   template <class Callback>
439  *   void format(FormatArg& arg, Callback& cb) const;
440  * with the following semantics: format the value using the given argument.
441  *
442  * arg is given by non-const reference for convenience -- it won't be reused,
443  * so feel free to modify it in place if necessary.  (For example, wrap an
444  * existing conversion but change the default, or remove the "key" when
445  * extracting an element from a container)
446  *
447  * Call the callback to append data to the output.  You may call the callback
448  * as many times as you'd like (or not at all, if you want to output an
449  * empty string)
450  */
451
452 namespace detail {
453
454 template <class T, class Enable = void>
455 struct IsFormatter : public std::false_type {};
456
457 template <class T>
458 struct IsFormatter<
459     T,
460     typename std::enable_if<
461         std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
462         type> : public std::true_type {};
463 } // namespace detail
464
465 // Deprecated API. formatChecked() et. al. now behave identically to their
466 // non-Checked counterparts.
467 template <class... Args>
468 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
469   return format(fmt, std::forward<Args>(args)...);
470 }
471 template <class... Args>
472 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
473   return formatChecked(fmt, std::forward<Args>(args)...).str();
474 }
475 template <class Container>
476 Formatter<true, Container> vformatChecked(
477     StringPiece fmt,
478     Container&& container) {
479   return vformat(fmt, std::forward<Container>(container));
480 }
481 template <class Container>
482 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
483   return vformatChecked(fmt, std::forward<Container>(container)).str();
484 }
485 template <class Str, class... Args>
486 typename std::enable_if<IsSomeString<Str>::value>::type
487 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
488   formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
489 }
490 template <class Str, class Container>
491 typename std::enable_if<IsSomeString<Str>::value>::type
492 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
493   vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
494 }
495
496 } // namespace folly
497
498 #include <folly/Format-inl.h>
499
500 FOLLY_POP_WARNING