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