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 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.
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.
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
69 template <class Derived, bool containerMode, class... Args>
73 * Append to output. out(StringPiece sp) may be called (more than once)
75 template <class Output>
76 void operator()(Output& out) const;
82 typename std::enable_if<IsSomeString<Str>::value>::type appendTo(
84 auto appender = [&str](StringPiece s) { str.append(s.data(), s.size()); };
89 * Conversion to string
91 std::string str() const {
98 * Conversion to fbstring
100 fbstring fbstr() const {
107 * Metadata to identify generated children of BaseFormatter
109 typedef detail::FormatterTag IsFormatter;
110 typedef BaseFormatter BaseType;
113 typedef std::tuple<Args...> ValueTuple;
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(getFormatValue<K>(), 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 may hold references).
192 BaseFormatter(BaseFormatter&&) = default;
193 BaseFormatter& operator=(BaseFormatter&&) = default;
196 using ArgType = typename std::tuple_element<K, ValueTuple>::type;
199 FormatValue<typename std::decay<ArgType<K>>::type> getFormatValue() const {
200 return FormatValue<typename std::decay<ArgType<K>>::type>(
201 std::get<K>(values_));
207 template <bool containerMode, class... Args>
208 class Formatter : public BaseFormatter<
209 Formatter<containerMode, Args...>,
213 explicit Formatter(StringPiece& str, Args&&... args)
215 Formatter<containerMode, Args...>,
217 Args...>(str, std::forward<Args>(args)...) {
219 !containerMode || sizeof...(Args) == 1,
220 "Exactly one argument required in container mode");
223 template <size_t K, class Callback>
224 void doFormatArg(FormatArg& arg, Callback& cb) const {
225 this->template getFormatValue<K>().format(arg, cb);
228 friend class BaseFormatter<
229 Formatter<containerMode, Args...>,
233 template <class... A>
234 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
236 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
240 * Formatter objects can be written to streams.
242 template <bool containerMode, class... Args>
243 std::ostream& operator<<(
245 const Formatter<containerMode, Args...>& formatter) {
246 auto writer = [&out](StringPiece sp) {
247 out.write(sp.data(), std::streamsize(sp.size()));
254 * Formatter objects can be written to stdio FILEs.
256 template <class Derived, bool containerMode, class... Args>
259 const BaseFormatter<Derived, containerMode, Args...>& formatter);
262 * Create a formatter object.
264 * std::string formatted = format("{} {}", 23, 42).str();
265 * LOG(INFO) << format("{} {}", 23, 42);
266 * writeTo(stdout, format("{} {}", 23, 42));
268 template <class... Args>
269 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
270 return Formatter<false, Args...>(fmt, std::forward<Args>(args)...);
274 * Like format(), but immediately returns the formatted string instead of an
275 * intermediate format object.
277 template <class... Args>
278 inline std::string sformat(StringPiece fmt, Args&&... args) {
279 return format(fmt, std::forward<Args>(args)...).str();
283 * Create a formatter object that takes one argument (of container type)
284 * and uses that container to get argument values from.
286 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
288 * The following are equivalent:
289 * format("{0[hello]} {0[answer]}", map);
291 * vformat("{hello} {answer}", map);
293 * but the latter is cleaner.
295 template <class Container>
296 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
297 return Formatter<true, Container>(fmt, std::forward<Container>(container));
301 * Like vformat(), but immediately returns the formatted string instead of an
302 * intermediate format object.
304 template <class Container>
305 inline std::string svformat(StringPiece fmt, Container&& container) {
306 return vformat(fmt, std::forward<Container>(container)).str();
310 * Wrap a sequence or associative container so that out-of-range lookups
311 * return a default value rather than throwing an exception.
314 * format("[no_such_key"], defaulted(map, 42)) -> 42
317 template <class Container, class Value>
318 struct DefaultValueWrapper {
319 DefaultValueWrapper(const Container& container, const Value& defaultValue)
320 : container(container), defaultValue(defaultValue) {}
322 const Container& container;
323 const Value& defaultValue;
327 template <class Container, class Value>
328 detail::DefaultValueWrapper<Container, Value> defaulted(
331 return detail::DefaultValueWrapper<Container, Value>(c, v);
335 * Append formatted output to a string.
338 * format(&foo, "{} {}", 42, 23);
340 * Shortcut for toAppend(format(...), &foo);
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);
349 * Append vformatted output to a string.
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);
358 * Utilities for all format value specializations.
360 namespace format_value {
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.
368 template <class FormatCallback>
369 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
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
378 template <class FormatCallback>
386 * Format a Formatter object recursively. Behaves just like
387 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
388 * string if possible.
391 class FormatCallback,
395 void formatFormatter(
396 const BaseFormatter<Derived, containerMode, Args...>& formatter,
400 } // namespace format_value
403 * Specialize folly::FormatValue for your type.
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.
410 * template <class Callback>
411 * void format(FormatArg& arg, Callback& cb) const;
412 * with the following semantics: format the value using the given argument.
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)
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
426 template <class T, class Enable = void>
427 struct IsFormatter : public std::false_type {};
432 typename std::enable_if<
433 std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
434 type> : public std::true_type {};
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)...);
443 template <class... Args>
444 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
445 return formatChecked(fmt, std::forward<Args>(args)...).str();
447 template <class Container>
448 Formatter<true, Container> vformatChecked(
450 Container&& container) {
451 return vformat(fmt, std::forward<Container>(container));
453 template <class Container>
454 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
455 return vformatChecked(fmt, std::forward<Container>(container)).str();
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);
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);
470 #include <folly/Format-inl.h>