589bcdff4b59d3f18f3100a299b56010a5a72fa6
[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   template <class... A>
65   friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
66   template <class C>
67   friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
68  public:
69   /**
70    * Append to output.  out(StringPiece sp) may be called (more than once)
71    */
72   template <class Output>
73   void operator()(Output& out) const;
74
75   /**
76    * Append to a string.
77    */
78   template <class Str>
79   typename std::enable_if<IsSomeString<Str>::value>::type
80   appendTo(Str& str) const {
81     auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
82     (*this)(appender);
83   }
84
85   /**
86    * Conversion to string
87    */
88   std::string str() const {
89     std::string s;
90     appendTo(s);
91     return s;
92   }
93
94   /**
95    * Conversion to fbstring
96    */
97   fbstring fbstr() const {
98     fbstring s;
99     appendTo(s);
100     return s;
101   }
102
103  private:
104   explicit Formatter(StringPiece str, Args&&... args);
105
106   // Not copyable
107   Formatter(const Formatter&) = delete;
108   Formatter& operator=(const Formatter&) = delete;
109
110   // Movable, but the move constructor and assignment operator are private,
111   // for the exclusive use of format() (below).  This way, you can't create
112   // a Formatter object, but can handle references to it (for streaming,
113   // conversion to string, etc) -- which is good, as Formatter objects are
114   // dangerous (they hold references, possibly to temporaries)
115   Formatter(Formatter&&) = default;
116   Formatter& operator=(Formatter&&) = default;
117
118   typedef std::tuple<FormatValue<
119       typename std::decay<Args>::type>...> ValueTuple;
120   static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
121
122   template <size_t K, class Callback>
123   typename std::enable_if<K == valueCount>::type
124   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
125     LOG(FATAL) << arg.errorStr("argument index out of range, max=", i);
126   }
127
128   template <size_t K, class Callback>
129   typename std::enable_if<(K < valueCount)>::type
130   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
131     if (i == K) {
132       std::get<K>(values_).format(arg, cb);
133     } else {
134       doFormatFrom<K+1>(i, arg, cb);
135     }
136   }
137
138   template <class Callback>
139   void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
140     return doFormatFrom<0>(i, arg, cb);
141   }
142
143   StringPiece str_;
144   ValueTuple values_;
145 };
146
147 /**
148  * Formatter objects can be written to streams.
149  */
150 template<bool containerMode, class... Args>
151 std::ostream& operator<<(std::ostream& out,
152                          const Formatter<containerMode, Args...>& formatter) {
153   auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
154   formatter(writer);
155   return out;
156 }
157
158 /**
159  * Formatter objects can be written to stdio FILEs.
160  */
161 template<bool containerMode, class... Args>
162 void writeTo(FILE* fp, const Formatter<containerMode, Args...>& formatter);
163
164 /**
165  * Create a formatter object.
166  *
167  * std::string formatted = format("{} {}", 23, 42).str();
168  * LOG(INFO) << format("{} {}", 23, 42);
169  * writeTo(stdout, format("{} {}", 23, 42));
170  */
171 template <class... Args>
172 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
173   return Formatter<false, Args...>(
174       fmt, std::forward<Args>(args)...);
175 }
176
177 /**
178  * Create a formatter object that takes one argument (of container type)
179  * and uses that container to get argument values from.
180  *
181  * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
182  *
183  * The following are equivalent:
184  * format("{0[hello]} {0[answer]}", map);
185  *
186  * vformat("{hello} {answer}", map);
187  *
188  * but the latter is cleaner.
189  */
190 template <class Container>
191 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
192   return Formatter<true, Container>(
193       fmt, std::forward<Container>(container));
194 }
195
196 /**
197  * Append formatted output to a string.
198  *
199  * std::string foo;
200  * format(&foo, "{} {}", 42, 23);
201  *
202  * Shortcut for toAppend(format(...), &foo);
203  */
204 template <class Str, class... Args>
205 typename std::enable_if<IsSomeString<Str>::value>::type
206 format(Str* out, StringPiece fmt, Args&&... args) {
207   format(fmt, std::forward<Args>(args)...).appendTo(*out);
208 }
209
210 /**
211  * Append vformatted output to a string.
212  */
213 template <class Str, class Container>
214 typename std::enable_if<IsSomeString<Str>::value>::type
215 vformat(Str* out, StringPiece fmt, Container&& container) {
216   vformat(fmt, std::forward<Container>(container)).appendTo(*out);
217 }
218
219 /**
220  * Utilities for all format value specializations.
221  */
222 namespace format_value {
223
224 /**
225  * Format a string in "val", obeying appropriate alignment, padding, width,
226  * and precision.  Treats Align::DEFAULT as Align::LEFT, and
227  * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
228  * number-specific formatting.
229  */
230 template <class FormatCallback>
231 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
232
233 /**
234  * Format a number in "val"; the first prefixLen characters form the prefix
235  * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
236  * is Align::PAD_AFTER_SIGN.  Treats Align::DEFAULT as Align::LEFT.  Ignores
237  * arg.precision, as that has a different meaning for numbers (not "maximum
238  * field width")
239  */
240 template <class FormatCallback>
241 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
242                   FormatCallback& cb);
243
244
245 /**
246  * Format a Formatter object recursively.  Behaves just like
247  * formatString(fmt.str(), arg, cb); but avoids creating a temporary
248  * string if possible.
249  */
250 template <class FormatCallback, bool containerMode, class... Args>
251 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
252                      FormatArg& arg,
253                      FormatCallback& cb);
254
255 }  // namespace format_value
256
257 /*
258  * Specialize folly::FormatValue for your type.
259  *
260  * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
261  * guaranteed to stay alive until the FormatValue object is destroyed, so you
262  * may keep a reference (or pointer) to it instead of making a copy.
263  *
264  * You must define
265  *   template <class Callback>
266  *   void format(FormatArg& arg, Callback& cb) const;
267  * with the following semantics: format the value using the given argument.
268  *
269  * arg is given by non-const reference for convenience -- it won't be reused,
270  * so feel free to modify it in place if necessary.  (For example, wrap an
271  * existing conversion but change the default, or remove the "key" when
272  * extracting an element from a container)
273  *
274  * Call the callback to append data to the output.  You may call the callback
275  * as many times as you'd like (or not at all, if you want to output an
276  * empty string)
277  */
278
279 }  // namespace folly
280
281 #include "folly/Format-inl.h"
282
283 #pragma GCC diagnostic pop
284
285 #endif /* FOLLY_FORMAT_H_ */