Adding a unit test for HHWheelTimer exercising the default timeout functionality.
[folly.git] / folly / Format.h
1 /*
2  * Copyright 2015 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 <cstdio>
21 #include <tuple>
22 #include <type_traits>
23
24 #include <folly/Conv.h>
25 #include <folly/Range.h>
26 #include <folly/Traits.h>
27 #include <folly/String.h>
28 #include <folly/FormatArg.h>
29
30 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
31 #pragma GCC diagnostic push
32 #pragma GCC diagnostic ignored "-Wshadow"
33
34 namespace folly {
35
36 // forward declarations
37 template <bool containerMode, class... Args> class Formatter;
38 template <class... Args>
39 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
40 template <class C>
41 Formatter<true, C> vformat(StringPiece fmt, C&& container);
42 template <class T, class Enable=void> class FormatValue;
43
44 // meta-attribute to identify formatters in this sea of template weirdness
45 namespace detail {
46 class FormatterTag {};
47 };
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 /* BaseFormatter class. Currently, the only behavior that can be
58  * overridden is the actual formatting of positional parameters in
59  * `doFormatArg`. The Formatter class provides the default implementation.
60  */
61 template <class Derived, bool containerMode, class... Args>
62 class BaseFormatter {
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<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   /**
99    * metadata to identify generated children of BaseFormatter
100    */
101   typedef detail::FormatterTag IsFormatter;
102   typedef BaseFormatter BaseType;
103
104  private:
105   typedef std::tuple<FormatValue<
106       typename std::decay<Args>::type>...> ValueTuple;
107   static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
108
109   template <size_t K, class Callback>
110   typename std::enable_if<K == valueCount>::type
111   doFormatFrom(size_t i, FormatArg& arg, Callback& /*cb*/) const {
112     arg.error("argument index out of range, max=", i);
113   }
114
115   template <size_t K, class Callback>
116   typename std::enable_if<(K < valueCount)>::type
117   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
118     if (i == K) {
119       static_cast<const Derived*>(this)->template doFormatArg<K>(arg, cb);
120     } else {
121       doFormatFrom<K+1>(i, arg, cb);
122     }
123   }
124
125   template <class Callback>
126   void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
127     return doFormatFrom<0>(i, arg, cb);
128   }
129
130   template <size_t K>
131   typename std::enable_if<K == valueCount, int>::type
132   getSizeArgFrom(size_t i, const FormatArg& arg) const {
133     arg.error("argument index out of range, max=", i);
134   }
135
136   template <class T>
137   typename std::enable_if<std::is_integral<T>::value &&
138                           !std::is_same<T, bool>::value, int>::type
139   getValue(const FormatValue<T>& format, const FormatArg&) const {
140     return static_cast<int>(format.getValue());
141   }
142
143   template <class T>
144   typename std::enable_if<!std::is_integral<T>::value ||
145                           std::is_same<T, bool>::value, int>::type
146   getValue(const FormatValue<T>&, const FormatArg& arg) const {
147     arg.error("dynamic field width argument must be integral");
148   }
149
150   template <size_t K>
151   typename std::enable_if<K < valueCount, int>::type
152   getSizeArgFrom(size_t i, const FormatArg& arg) const {
153     if (i == K) {
154       return getValue(std::get<K>(values_), arg);
155     }
156     return getSizeArgFrom<K+1>(i, arg);
157   }
158
159   int getSizeArg(size_t i, const FormatArg& arg) const {
160     return getSizeArgFrom<0>(i, arg);
161   }
162
163   StringPiece str_;
164
165  protected:
166   explicit BaseFormatter(StringPiece str, Args&&... args);
167
168   // Not copyable
169   BaseFormatter(const BaseFormatter&) = delete;
170   BaseFormatter& operator=(const BaseFormatter&) = delete;
171
172   // Movable, but the move constructor and assignment operator are private,
173   // for the exclusive use of format() (below).  This way, you can't create
174   // a Formatter object, but can handle references to it (for streaming,
175   // conversion to string, etc) -- which is good, as Formatter objects are
176   // dangerous (they hold references, possibly to temporaries)
177   BaseFormatter(BaseFormatter&&) = default;
178   BaseFormatter& operator=(BaseFormatter&&) = default;
179
180   ValueTuple values_;
181 };
182
183 template <bool containerMode, class... Args>
184 class Formatter : public BaseFormatter<Formatter<containerMode, Args...>,
185                                        containerMode,
186                                        Args...> {
187  private:
188   explicit Formatter(StringPiece& str, Args&&... args)
189       : BaseFormatter<Formatter<containerMode, Args...>,
190                       containerMode,
191                       Args...>(str, std::forward<Args>(args)...) {}
192
193   template <size_t K, class Callback>
194   void doFormatArg(FormatArg& arg, Callback& cb) const {
195     std::get<K>(this->values_).format(arg, cb);
196   }
197
198   friend class BaseFormatter<Formatter<containerMode, Args...>,
199                              containerMode,
200                              Args...>;
201
202   template <class... A>
203   friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
204   template <class C>
205   friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
206 };
207
208 /**
209  * Formatter objects can be written to streams.
210  */
211 template<bool containerMode, class... Args>
212 std::ostream& operator<<(std::ostream& out,
213                          const Formatter<containerMode, Args...>& formatter) {
214   auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
215   formatter(writer);
216   return out;
217 }
218
219 /**
220  * Formatter objects can be written to stdio FILEs.
221  */
222 template <class Derived, bool containerMode, class... Args>
223 void writeTo(FILE* fp,
224              const BaseFormatter<Derived, containerMode, Args...>& formatter);
225
226 /**
227  * Create a formatter object.
228  *
229  * std::string formatted = format("{} {}", 23, 42).str();
230  * LOG(INFO) << format("{} {}", 23, 42);
231  * writeTo(stdout, format("{} {}", 23, 42));
232  */
233 template <class... Args>
234 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
235   return Formatter<false, Args...>(
236       fmt, std::forward<Args>(args)...);
237 }
238
239 /**
240  * Like format(), but immediately returns the formatted string instead of an
241  * intermediate format object.
242  */
243 template <class... Args>
244 inline std::string sformat(StringPiece fmt, Args&&... args) {
245   return format(fmt, std::forward<Args>(args)...).str();
246 }
247
248 /**
249  * Create a formatter object that takes one argument (of container type)
250  * and uses that container to get argument values from.
251  *
252  * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
253  *
254  * The following are equivalent:
255  * format("{0[hello]} {0[answer]}", map);
256  *
257  * vformat("{hello} {answer}", map);
258  *
259  * but the latter is cleaner.
260  */
261 template <class Container>
262 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
263   return Formatter<true, Container>(
264       fmt, std::forward<Container>(container));
265 }
266
267 /**
268  * Like vformat(), but immediately returns the formatted string instead of an
269  * intermediate format object.
270  */
271 template <class Container>
272 inline std::string svformat(StringPiece fmt, Container&& container) {
273   return vformat(fmt, std::forward<Container>(container)).str();
274 }
275
276 /**
277  * Wrap a sequence or associative container so that out-of-range lookups
278  * return a default value rather than throwing an exception.
279  *
280  * Usage:
281  * format("[no_such_key"], defaulted(map, 42))  -> 42
282  */
283 namespace detail {
284 template <class Container, class Value> struct DefaultValueWrapper {
285   DefaultValueWrapper(const Container& container, const Value& defaultValue)
286     : container(container),
287       defaultValue(defaultValue) {
288   }
289
290   const Container& container;
291   const Value& defaultValue;
292 };
293 }  // namespace
294
295 template <class Container, class Value>
296 detail::DefaultValueWrapper<Container, Value>
297 defaulted(const Container& c, const Value& v) {
298   return detail::DefaultValueWrapper<Container, Value>(c, v);
299 }
300
301 /**
302  * Append formatted output to a string.
303  *
304  * std::string foo;
305  * format(&foo, "{} {}", 42, 23);
306  *
307  * Shortcut for toAppend(format(...), &foo);
308  */
309 template <class Str, class... Args>
310 typename std::enable_if<IsSomeString<Str>::value>::type
311 format(Str* out, StringPiece fmt, Args&&... args) {
312   format(fmt, std::forward<Args>(args)...).appendTo(*out);
313 }
314
315 /**
316  * Append vformatted output to a string.
317  */
318 template <class Str, class Container>
319 typename std::enable_if<IsSomeString<Str>::value>::type
320 vformat(Str* out, StringPiece fmt, Container&& container) {
321   vformat(fmt, std::forward<Container>(container)).appendTo(*out);
322 }
323
324 /**
325  * Utilities for all format value specializations.
326  */
327 namespace format_value {
328
329 /**
330  * Format a string in "val", obeying appropriate alignment, padding, width,
331  * and precision.  Treats Align::DEFAULT as Align::LEFT, and
332  * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
333  * number-specific formatting.
334  */
335 template <class FormatCallback>
336 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
337
338 /**
339  * Format a number in "val"; the first prefixLen characters form the prefix
340  * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
341  * is Align::PAD_AFTER_SIGN.  Treats Align::DEFAULT as Align::LEFT.  Ignores
342  * arg.precision, as that has a different meaning for numbers (not "maximum
343  * field width")
344  */
345 template <class FormatCallback>
346 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
347                   FormatCallback& cb);
348
349
350 /**
351  * Format a Formatter object recursively.  Behaves just like
352  * formatString(fmt.str(), arg, cb); but avoids creating a temporary
353  * string if possible.
354  */
355 template <class FormatCallback,
356           class Derived,
357           bool containerMode,
358           class... Args>
359 void formatFormatter(
360     const BaseFormatter<Derived, containerMode, Args...>& formatter,
361     FormatArg& arg,
362     FormatCallback& cb);
363
364 }  // namespace format_value
365
366 /*
367  * Specialize folly::FormatValue for your type.
368  *
369  * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
370  * guaranteed to stay alive until the FormatValue object is destroyed, so you
371  * may keep a reference (or pointer) to it instead of making a copy.
372  *
373  * You must define
374  *   template <class Callback>
375  *   void format(FormatArg& arg, Callback& cb) const;
376  * with the following semantics: format the value using the given argument.
377  *
378  * arg is given by non-const reference for convenience -- it won't be reused,
379  * so feel free to modify it in place if necessary.  (For example, wrap an
380  * existing conversion but change the default, or remove the "key" when
381  * extracting an element from a container)
382  *
383  * Call the callback to append data to the output.  You may call the callback
384  * as many times as you'd like (or not at all, if you want to output an
385  * empty string)
386  */
387
388 namespace detail {
389
390 template <class T, class Enable = void>
391 struct IsFormatter : public std::false_type {};
392
393 template <class T>
394 struct IsFormatter<
395     T,
396     typename std::enable_if<
397         std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
398         type> : public std::true_type {};
399 } // folly::detail
400
401 // Deprecated API. formatChecked() et. al. now behave identically to their
402 // non-Checked counterparts.
403 template <class... Args>
404 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
405   return format(fmt, std::forward<Args>(args)...);
406 }
407 template <class... Args>
408 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
409   return formatChecked(fmt, std::forward<Args>(args)...).str();
410 }
411 template <class Container>
412 Formatter<true, Container> vformatChecked(StringPiece fmt,
413                                           Container&& container) {
414   return vformat(fmt, std::forward<Container>(container));
415 }
416 template <class Container>
417 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
418   return vformatChecked(fmt, std::forward<Container>(container)).str();
419 }
420 template <class Str, class... Args>
421 typename std::enable_if<IsSomeString<Str>::value>::type
422 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
423   formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
424 }
425 template <class Str, class Container>
426 typename std::enable_if<IsSomeString<Str>::value>::type
427 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
428   vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
429 }
430
431 }  // namespace folly
432
433 #include <folly/Format-inl.h>
434
435 #pragma GCC diagnostic pop
436
437 #endif /* FOLLY_FORMAT_H_ */