A few fixes for clang support
[folly.git] / folly / Format.h
1 /*
2  * Copyright 2013 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/Traits.h"
34 #include "folly/Likely.h"
35 #include "folly/String.h"
36 #include "folly/small_vector.h"
37 #include "folly/FormatArg.h"
38
39 namespace folly {
40
41 // forward declarations
42 template <bool containerMode, class... Args> class Formatter;
43 template <class... Args>
44 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
45 template <class C>
46 Formatter<true, C> vformat(StringPiece fmt, C&& container);
47 template <class T, class Enable=void> class FormatValue;
48
49 /**
50  * Formatter class.
51  *
52  * Note that this class is tricky, as it keeps *references* to its arguments
53  * (and doesn't copy the passed-in format string).  Thankfully, you can't use
54  * this directly, you have to use format(...) below.
55  */
56
57 template <bool containerMode, class... Args>
58 class Formatter {
59   template <class... A>
60   friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
61   template <class C>
62   friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
63  public:
64   /**
65    * Append to output.  out(StringPiece sp) may be called (more than once)
66    */
67   template <class Output>
68   void operator()(Output& out) const;
69
70   /**
71    * Append to a string.
72    */
73   template <class Str>
74   typename std::enable_if<detail::IsSomeString<Str>::value>::type
75   appendTo(Str& str) const {
76     auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
77     (*this)(appender);
78   }
79
80   /**
81    * Conversion to string
82    */
83   std::string str() const {
84     std::string s;
85     appendTo(s);
86     return s;
87   }
88
89   /**
90    * Conversion to fbstring
91    */
92   fbstring fbstr() const {
93     fbstring s;
94     appendTo(s);
95     return s;
96   }
97
98  private:
99   explicit Formatter(StringPiece str, Args&&... args);
100
101   // Not copyable
102   Formatter(const Formatter&) = delete;
103   Formatter& operator=(const Formatter&) = delete;
104
105   // Movable, but the move constructor and assignment operator are private,
106   // for the exclusive use of format() (below).  This way, you can't create
107   // a Formatter object, but can handle references to it (for streaming,
108   // conversion to string, etc) -- which is good, as Formatter objects are
109   // dangerous (they hold references, possibly to temporaries)
110   Formatter(Formatter&&) = default;
111   Formatter& operator=(Formatter&&) = default;
112
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       std::get<K>(values_).format(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   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).str();
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