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