2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #define FOLLY_FORMAT_H_
22 #include <type_traits>
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>
30 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
32 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
36 // forward declarations
37 template <bool containerMode, class... Args>
39 template <class... Args>
40 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
42 Formatter<true, C> vformat(StringPiece fmt, C&& container);
43 template <class T, class Enable = void>
46 // meta-attribute to identify formatters in this sea of template weirdness
48 class FormatterTag {};
54 * Note that this class is tricky, as it keeps *references* to its arguments
55 * (and doesn't copy the passed-in format string). Thankfully, you can't use
56 * this directly, you have to use format(...) below.
59 /* BaseFormatter class.
60 * Overridable behaviours:
61 * You may override the actual formatting of positional parameters in
62 * `doFormatArg`. The Formatter class provides the default implementation.
64 * You may also override `doFormat` and `getSizeArg`. These override points were
65 * added to permit static analysis of format strings, when it is inconvenient
66 * or impossible to instantiate a BaseFormatter with the correct storage
68 template <class Derived, bool containerMode, class... Args>
72 * Append to output. out(StringPiece sp) may be called (more than once)
74 template <class Output>
75 void operator()(Output& out) const;
81 typename std::enable_if<IsSomeString<Str>::value>::type appendTo(
83 auto appender = [&str](StringPiece s) { str.append(s.data(), s.size()); };
88 * Conversion to string
90 std::string str() const {
97 * Conversion to fbstring
99 fbstring fbstr() const {
106 * metadata to identify generated children of BaseFormatter
108 typedef detail::FormatterTag IsFormatter;
109 typedef BaseFormatter BaseType;
112 typedef std::tuple<FormatValue<typename std::decay<Args>::type>...>
114 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
116 Derived const& asDerived() const {
117 return *static_cast<const Derived*>(this);
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);
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 {
130 asDerived().template doFormatArg<K>(arg, cb);
132 doFormatFrom<K + 1>(i, arg, cb);
136 template <class Callback>
137 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
138 return doFormatFrom<0>(i, arg, cb);
142 typename std::enable_if<K == valueCount, int>::type getSizeArgFrom(
144 const FormatArg& arg) const {
145 arg.error("argument index out of range, max=", i);
149 typename std::enable_if<
150 std::is_integral<T>::value && !std::is_same<T, bool>::value,
152 getValue(const FormatValue<T>& format, const FormatArg&) const {
153 return static_cast<int>(format.getValue());
157 typename std::enable_if<
158 !std::is_integral<T>::value || std::is_same<T, bool>::value,
160 getValue(const FormatValue<T>&, const FormatArg& arg) const {
161 arg.error("dynamic field width argument must be integral");
165 typename std::enable_if <
166 K<valueCount, int>::type getSizeArgFrom(size_t i, const FormatArg& arg)
169 return getValue(std::get<K>(values_), arg);
171 return getSizeArgFrom<K + 1>(i, arg);
174 int getSizeArg(size_t i, const FormatArg& arg) const {
175 return getSizeArgFrom<0>(i, arg);
181 explicit BaseFormatter(StringPiece str, Args&&... args);
184 BaseFormatter(const BaseFormatter&) = delete;
185 BaseFormatter& operator=(const BaseFormatter&) = delete;
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 hold references, possibly to temporaries)
192 BaseFormatter(BaseFormatter&&) = default;
193 BaseFormatter& operator=(BaseFormatter&&) = default;
198 template <bool containerMode, class... Args>
199 class Formatter : public BaseFormatter<
200 Formatter<containerMode, Args...>,
204 explicit Formatter(StringPiece& str, Args&&... args)
206 Formatter<containerMode, Args...>,
208 Args...>(str, std::forward<Args>(args)...) {
210 !containerMode || sizeof...(Args) == 1,
211 "Exactly one argument required in container mode");
214 template <size_t K, class Callback>
215 void doFormatArg(FormatArg& arg, Callback& cb) const {
216 std::get<K>(this->values_).format(arg, cb);
219 friend class BaseFormatter<
220 Formatter<containerMode, Args...>,
224 template <class... A>
225 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
227 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
231 * Formatter objects can be written to streams.
233 template <bool containerMode, class... Args>
234 std::ostream& operator<<(
236 const Formatter<containerMode, Args...>& formatter) {
237 auto writer = [&out](StringPiece sp) {
238 out.write(sp.data(), std::streamsize(sp.size()));
245 * Formatter objects can be written to stdio FILEs.
247 template <class Derived, bool containerMode, class... Args>
250 const BaseFormatter<Derived, containerMode, Args...>& formatter);
253 * Create a formatter object.
255 * std::string formatted = format("{} {}", 23, 42).str();
256 * LOG(INFO) << format("{} {}", 23, 42);
257 * writeTo(stdout, format("{} {}", 23, 42));
259 template <class... Args>
260 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
261 return Formatter<false, Args...>(fmt, std::forward<Args>(args)...);
265 * Like format(), but immediately returns the formatted string instead of an
266 * intermediate format object.
268 template <class... Args>
269 inline std::string sformat(StringPiece fmt, Args&&... args) {
270 return format(fmt, std::forward<Args>(args)...).str();
274 * Create a formatter object that takes one argument (of container type)
275 * and uses that container to get argument values from.
277 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
279 * The following are equivalent:
280 * format("{0[hello]} {0[answer]}", map);
282 * vformat("{hello} {answer}", map);
284 * but the latter is cleaner.
286 template <class Container>
287 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
288 return Formatter<true, Container>(fmt, std::forward<Container>(container));
292 * Like vformat(), but immediately returns the formatted string instead of an
293 * intermediate format object.
295 template <class Container>
296 inline std::string svformat(StringPiece fmt, Container&& container) {
297 return vformat(fmt, std::forward<Container>(container)).str();
301 * Wrap a sequence or associative container so that out-of-range lookups
302 * return a default value rather than throwing an exception.
305 * format("[no_such_key"], defaulted(map, 42)) -> 42
308 template <class Container, class Value>
309 struct DefaultValueWrapper {
310 DefaultValueWrapper(const Container& container, const Value& defaultValue)
311 : container(container), defaultValue(defaultValue) {}
313 const Container& container;
314 const Value& defaultValue;
318 template <class Container, class Value>
319 detail::DefaultValueWrapper<Container, Value> defaulted(
322 return detail::DefaultValueWrapper<Container, Value>(c, v);
326 * Append formatted output to a string.
329 * format(&foo, "{} {}", 42, 23);
331 * Shortcut for toAppend(format(...), &foo);
333 template <class Str, class... Args>
334 typename std::enable_if<IsSomeString<Str>::value>::type
335 format(Str* out, StringPiece fmt, Args&&... args) {
336 format(fmt, std::forward<Args>(args)...).appendTo(*out);
340 * Append vformatted output to a string.
342 template <class Str, class Container>
343 typename std::enable_if<IsSomeString<Str>::value>::type
344 vformat(Str* out, StringPiece fmt, Container&& container) {
345 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
349 * Utilities for all format value specializations.
351 namespace format_value {
354 * Format a string in "val", obeying appropriate alignment, padding, width,
355 * and precision. Treats Align::DEFAULT as Align::LEFT, and
356 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
357 * number-specific formatting.
359 template <class FormatCallback>
360 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
363 * Format a number in "val"; the first prefixLen characters form the prefix
364 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
365 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
366 * arg.precision, as that has a different meaning for numbers (not "maximum
369 template <class FormatCallback>
377 * Format a Formatter object recursively. Behaves just like
378 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
379 * string if possible.
382 class FormatCallback,
386 void formatFormatter(
387 const BaseFormatter<Derived, containerMode, Args...>& formatter,
391 } // namespace format_value
394 * Specialize folly::FormatValue for your type.
396 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
397 * guaranteed to stay alive until the FormatValue object is destroyed, so you
398 * may keep a reference (or pointer) to it instead of making a copy.
401 * template <class Callback>
402 * void format(FormatArg& arg, Callback& cb) const;
403 * with the following semantics: format the value using the given argument.
405 * arg is given by non-const reference for convenience -- it won't be reused,
406 * so feel free to modify it in place if necessary. (For example, wrap an
407 * existing conversion but change the default, or remove the "key" when
408 * extracting an element from a container)
410 * Call the callback to append data to the output. You may call the callback
411 * as many times as you'd like (or not at all, if you want to output an
417 template <class T, class Enable = void>
418 struct IsFormatter : public std::false_type {};
423 typename std::enable_if<
424 std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
425 type> : public std::true_type {};
428 // Deprecated API. formatChecked() et. al. now behave identically to their
429 // non-Checked counterparts.
430 template <class... Args>
431 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
432 return format(fmt, std::forward<Args>(args)...);
434 template <class... Args>
435 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
436 return formatChecked(fmt, std::forward<Args>(args)...).str();
438 template <class Container>
439 Formatter<true, Container> vformatChecked(
441 Container&& container) {
442 return vformat(fmt, std::forward<Container>(container));
444 template <class Container>
445 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
446 return vformatChecked(fmt, std::forward<Container>(container)).str();
448 template <class Str, class... Args>
449 typename std::enable_if<IsSomeString<Str>::value>::type
450 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
451 formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
453 template <class Str, class Container>
454 typename std::enable_if<IsSomeString<Str>::value>::type
455 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
456 vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
461 #include <folly/Format-inl.h>