Remove Stream
[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   StringPiece str_;
138   ValueTuple values_;
139 };
140
141 /**
142  * Formatter objects can be written to streams.
143  */
144 template<bool containerMode, class... Args>
145 std::ostream& operator<<(std::ostream& out,
146                          const Formatter<containerMode, Args...>& formatter) {
147   auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
148   formatter(writer);
149   return out;
150 }
151
152 /**
153  * Create a formatter object.
154  *
155  * std::string formatted = format("{} {}", 23, 42).str();
156  * LOG(INFO) << format("{} {}", 23, 42);
157  */
158 template <class... Args>
159 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
160   return Formatter<false, Args...>(
161       fmt, std::forward<Args>(args)...);
162 }
163
164 /**
165  * Create a formatter object that takes one argument (of container type)
166  * and uses that container to get argument values from.
167  *
168  * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
169  *
170  * The following are equivalent:
171  * format("{0[hello]} {0[answer]}", map);
172  *
173  * vformat("{hello} {answer}", map);
174  *
175  * but the latter is cleaner.
176  */
177 template <class Container>
178 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
179   return Formatter<true, Container>(
180       fmt, std::forward<Container>(container));
181 }
182
183 /**
184  * Append formatted output to a string.
185  *
186  * std::string foo;
187  * format(&foo, "{} {}", 42, 23);
188  *
189  * Shortcut for toAppend(format(...), &foo);
190  */
191 template <class Str, class... Args>
192 typename std::enable_if<detail::IsSomeString<Str>::value>::type
193 format(Str* out, StringPiece fmt, Args&&... args) {
194   format(fmt, std::forward<Args>(args)...).appendTo(*out);
195 }
196
197 /**
198  * Append vformatted output to a string.
199  */
200 template <class Str, class Container>
201 typename std::enable_if<detail::IsSomeString<Str>::value>::type
202 vformat(Str* out, StringPiece fmt, Container&& container) {
203   vformat(fmt, std::forward<Container>(container)).appendTo(*out);
204 }
205
206 /**
207  * Utilities for all format value specializations.
208  */
209 namespace format_value {
210
211 /**
212  * Format a string in "val", obeying appropriate alignment, padding, width,
213  * and precision.  Treats Align::DEFAULT as Align::LEFT, and
214  * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
215  * number-specific formatting.
216  */
217 template <class FormatCallback>
218 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
219
220 /**
221  * Format a number in "val"; the first prefixLen characters form the prefix
222  * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
223  * is Align::PAD_AFTER_SIGN.  Treats Align::DEFAULT as Align::LEFT.  Ignores
224  * arg.precision, as that has a different meaning for numbers (not "maximum
225  * field width")
226  */
227 template <class FormatCallback>
228 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
229                   FormatCallback& cb);
230
231
232 /**
233  * Format a Formatter object recursively.  Behaves just like
234  * formatString(fmt.str(), arg, cb); but avoids creating a temporary
235  * string if possible.
236  */
237 template <class FormatCallback, bool containerMode, class... Args>
238 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
239                      FormatArg& arg,
240                      FormatCallback& cb);
241
242 }  // namespace format_value
243
244 /*
245  * Specialize folly::FormatValue for your type.
246  *
247  * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
248  * guaranteed to stay alive until the FormatValue object is destroyed, so you
249  * may keep a reference (or pointer) to it instead of making a copy.
250  *
251  * You must define
252  *   template <class Callback>
253  *   void format(FormatArg& arg, Callback& cb) const;
254  * with the following semantics: format the value using the given argument.
255  *
256  * arg is given by non-const reference for convenience -- it won't be reused,
257  * so feel free to modify it in place if necessary.  (For example, wrap an
258  * existing conversion but change the default, or remove the "key" when
259  * extracting an element from a container)
260  *
261  * Call the callback to append data to the output.  You may call the callback
262  * as many times as you'd like (or not at all, if you want to output an
263  * empty string)
264  */
265
266 }  // namespace folly
267
268 #include "folly/Format-inl.h"
269
270 #endif /* FOLLY_FORMAT_H_ */
271