Remove disallowed &* of FwdIterator
[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.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   void handleFormatStrError() const FOLLY_NORETURN;
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  * Create a formatter object from a dynamic format string.
212  *
213  * This is identical to format(), but throws an exception if the format string
214  * is invalid, rather than aborting the program.  This allows it to be used
215  * with user-specified format strings which are not guaranteed to be well
216  * formed.
217  */
218 template <class... Args>
219 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
220   Formatter<false, Args...> f(fmt, std::forward<Args>(args)...);
221   f.setCrashOnError(false);
222   return f;
223 }
224
225 /**
226  * Create a formatter object that takes one argument (of container type)
227  * and uses that container to get argument values from.
228  *
229  * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
230  *
231  * The following are equivalent:
232  * format("{0[hello]} {0[answer]}", map);
233  *
234  * vformat("{hello} {answer}", map);
235  *
236  * but the latter is cleaner.
237  */
238 template <class Container>
239 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
240   return Formatter<true, Container>(
241       fmt, std::forward<Container>(container));
242 }
243
244 /**
245  * Create a formatter object from a dynamic format string.
246  *
247  * This is identical to vformat(), but throws an exception if the format string
248  * is invalid, rather than aborting the program.  This allows it to be used
249  * with user-specified format strings which are not guaranteed to be well
250  * formed.
251  */
252 template <class Container>
253 Formatter<true, Container> vformatChecked(StringPiece fmt,
254                                           Container&& container) {
255   Formatter<true, Container> f(fmt, std::forward<Container>(container));
256   f.setCrashOnError(false);
257   return f;
258 }
259
260 /**
261  * Append formatted output to a string.
262  *
263  * std::string foo;
264  * format(&foo, "{} {}", 42, 23);
265  *
266  * Shortcut for toAppend(format(...), &foo);
267  */
268 template <class Str, class... Args>
269 typename std::enable_if<IsSomeString<Str>::value>::type
270 format(Str* out, StringPiece fmt, Args&&... args) {
271   format(fmt, std::forward<Args>(args)...).appendTo(*out);
272 }
273
274 template <class Str, class... Args>
275 typename std::enable_if<IsSomeString<Str>::value>::type
276 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
277   formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
278 }
279
280 /**
281  * Append vformatted output to a string.
282  */
283 template <class Str, class Container>
284 typename std::enable_if<IsSomeString<Str>::value>::type
285 vformat(Str* out, StringPiece fmt, Container&& container) {
286   vformat(fmt, std::forward<Container>(container)).appendTo(*out);
287 }
288
289 template <class Str, class Container>
290 typename std::enable_if<IsSomeString<Str>::value>::type
291 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
292   vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
293 }
294
295 /**
296  * Utilities for all format value specializations.
297  */
298 namespace format_value {
299
300 /**
301  * Format a string in "val", obeying appropriate alignment, padding, width,
302  * and precision.  Treats Align::DEFAULT as Align::LEFT, and
303  * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
304  * number-specific formatting.
305  */
306 template <class FormatCallback>
307 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
308
309 /**
310  * Format a number in "val"; the first prefixLen characters form the prefix
311  * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
312  * is Align::PAD_AFTER_SIGN.  Treats Align::DEFAULT as Align::LEFT.  Ignores
313  * arg.precision, as that has a different meaning for numbers (not "maximum
314  * field width")
315  */
316 template <class FormatCallback>
317 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
318                   FormatCallback& cb);
319
320
321 /**
322  * Format a Formatter object recursively.  Behaves just like
323  * formatString(fmt.str(), arg, cb); but avoids creating a temporary
324  * string if possible.
325  */
326 template <class FormatCallback, bool containerMode, class... Args>
327 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
328                      FormatArg& arg,
329                      FormatCallback& cb);
330
331 }  // namespace format_value
332
333 /*
334  * Specialize folly::FormatValue for your type.
335  *
336  * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
337  * guaranteed to stay alive until the FormatValue object is destroyed, so you
338  * may keep a reference (or pointer) to it instead of making a copy.
339  *
340  * You must define
341  *   template <class Callback>
342  *   void format(FormatArg& arg, Callback& cb) const;
343  * with the following semantics: format the value using the given argument.
344  *
345  * arg is given by non-const reference for convenience -- it won't be reused,
346  * so feel free to modify it in place if necessary.  (For example, wrap an
347  * existing conversion but change the default, or remove the "key" when
348  * extracting an element from a container)
349  *
350  * Call the callback to append data to the output.  You may call the callback
351  * as many times as you'd like (or not at all, if you want to output an
352  * empty string)
353  */
354
355 }  // namespace folly
356
357 #include "folly/Format-inl.h"
358
359 #pragma GCC diagnostic pop
360
361 #endif /* FOLLY_FORMAT_H_ */