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