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