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