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