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/Range.h>
26 #include <folly/Traits.h>
27 #include <folly/String.h>
28 #include <folly/FormatArg.h>
30 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
31 #pragma GCC diagnostic push
32 #pragma GCC diagnostic ignored "-Wshadow"
36 // forward declarations
37 template <bool containerMode, class... Args> class Formatter;
38 template <class... Args>
39 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
41 Formatter<true, C> vformat(StringPiece fmt, C&& container);
42 template <class T, class Enable=void> class FormatValue;
44 // meta-attribute to identify formatters in this sea of template weirdness
46 class FormatterTag {};
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.
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.
61 template <class Derived, bool containerMode, class... Args>
65 * Append to output. out(StringPiece sp) may be called (more than once)
67 template <class Output>
68 void operator()(Output& out) const;
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()); };
81 * Conversion to string
83 std::string str() const {
90 * Conversion to fbstring
92 fbstring fbstr() const {
99 * metadata to identify generated children of BaseFormatter
101 typedef detail::FormatterTag IsFormatter;
102 typedef BaseFormatter BaseType;
105 typedef std::tuple<FormatValue<
106 typename std::decay<Args>::type>...> ValueTuple;
107 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
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);
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 {
119 static_cast<const Derived*>(this)->template doFormatArg<K>(arg, cb);
121 doFormatFrom<K+1>(i, arg, cb);
125 template <class Callback>
126 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
127 return doFormatFrom<0>(i, arg, cb);
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);
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());
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");
151 typename std::enable_if<K < valueCount, int>::type
152 getSizeArgFrom(size_t i, const FormatArg& arg) const {
154 return getValue(std::get<K>(values_), arg);
156 return getSizeArgFrom<K+1>(i, arg);
159 int getSizeArg(size_t i, const FormatArg& arg) const {
160 return getSizeArgFrom<0>(i, arg);
166 explicit BaseFormatter(StringPiece str, Args&&... args);
169 BaseFormatter(const BaseFormatter&) = delete;
170 BaseFormatter& operator=(const BaseFormatter&) = delete;
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;
183 template <bool containerMode, class... Args>
184 class Formatter : public BaseFormatter<Formatter<containerMode, Args...>,
188 explicit Formatter(StringPiece& str, Args&&... args)
189 : BaseFormatter<Formatter<containerMode, Args...>,
191 Args...>(str, std::forward<Args>(args)...) {}
193 template <size_t K, class Callback>
194 void doFormatArg(FormatArg& arg, Callback& cb) const {
195 std::get<K>(this->values_).format(arg, cb);
198 friend class BaseFormatter<Formatter<containerMode, Args...>,
202 template <class... A>
203 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
205 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
209 * Formatter objects can be written to streams.
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) {
215 out.write(sp.data(), std::streamsize(sp.size()));
222 * Formatter objects can be written to stdio FILEs.
224 template <class Derived, bool containerMode, class... Args>
225 void writeTo(FILE* fp,
226 const BaseFormatter<Derived, containerMode, Args...>& formatter);
229 * Create a formatter object.
231 * std::string formatted = format("{} {}", 23, 42).str();
232 * LOG(INFO) << format("{} {}", 23, 42);
233 * writeTo(stdout, format("{} {}", 23, 42));
235 template <class... Args>
236 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
237 return Formatter<false, Args...>(
238 fmt, std::forward<Args>(args)...);
242 * Like format(), but immediately returns the formatted string instead of an
243 * intermediate format object.
245 template <class... Args>
246 inline std::string sformat(StringPiece fmt, Args&&... args) {
247 return format(fmt, std::forward<Args>(args)...).str();
251 * Create a formatter object that takes one argument (of container type)
252 * and uses that container to get argument values from.
254 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
256 * The following are equivalent:
257 * format("{0[hello]} {0[answer]}", map);
259 * vformat("{hello} {answer}", map);
261 * but the latter is cleaner.
263 template <class Container>
264 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
265 return Formatter<true, Container>(
266 fmt, std::forward<Container>(container));
270 * Like vformat(), but immediately returns the formatted string instead of an
271 * intermediate format object.
273 template <class Container>
274 inline std::string svformat(StringPiece fmt, Container&& container) {
275 return vformat(fmt, std::forward<Container>(container)).str();
279 * Wrap a sequence or associative container so that out-of-range lookups
280 * return a default value rather than throwing an exception.
283 * format("[no_such_key"], defaulted(map, 42)) -> 42
286 template <class Container, class Value> struct DefaultValueWrapper {
287 DefaultValueWrapper(const Container& container, const Value& defaultValue)
288 : container(container),
289 defaultValue(defaultValue) {
292 const Container& container;
293 const Value& defaultValue;
297 template <class Container, class Value>
298 detail::DefaultValueWrapper<Container, Value>
299 defaulted(const Container& c, const Value& v) {
300 return detail::DefaultValueWrapper<Container, Value>(c, v);
304 * Append formatted output to a string.
307 * format(&foo, "{} {}", 42, 23);
309 * Shortcut for toAppend(format(...), &foo);
311 template <class Str, class... Args>
312 typename std::enable_if<IsSomeString<Str>::value>::type
313 format(Str* out, StringPiece fmt, Args&&... args) {
314 format(fmt, std::forward<Args>(args)...).appendTo(*out);
318 * Append vformatted output to a string.
320 template <class Str, class Container>
321 typename std::enable_if<IsSomeString<Str>::value>::type
322 vformat(Str* out, StringPiece fmt, Container&& container) {
323 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
327 * Utilities for all format value specializations.
329 namespace format_value {
332 * Format a string in "val", obeying appropriate alignment, padding, width,
333 * and precision. Treats Align::DEFAULT as Align::LEFT, and
334 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
335 * number-specific formatting.
337 template <class FormatCallback>
338 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
341 * Format a number in "val"; the first prefixLen characters form the prefix
342 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
343 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
344 * arg.precision, as that has a different meaning for numbers (not "maximum
347 template <class FormatCallback>
348 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
353 * Format a Formatter object recursively. Behaves just like
354 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
355 * string if possible.
357 template <class FormatCallback,
361 void formatFormatter(
362 const BaseFormatter<Derived, containerMode, Args...>& formatter,
366 } // namespace format_value
369 * Specialize folly::FormatValue for your type.
371 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
372 * guaranteed to stay alive until the FormatValue object is destroyed, so you
373 * may keep a reference (or pointer) to it instead of making a copy.
376 * template <class Callback>
377 * void format(FormatArg& arg, Callback& cb) const;
378 * with the following semantics: format the value using the given argument.
380 * arg is given by non-const reference for convenience -- it won't be reused,
381 * so feel free to modify it in place if necessary. (For example, wrap an
382 * existing conversion but change the default, or remove the "key" when
383 * extracting an element from a container)
385 * Call the callback to append data to the output. You may call the callback
386 * as many times as you'd like (or not at all, if you want to output an
392 template <class T, class Enable = void>
393 struct IsFormatter : public std::false_type {};
398 typename std::enable_if<
399 std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
400 type> : public std::true_type {};
403 // Deprecated API. formatChecked() et. al. now behave identically to their
404 // non-Checked counterparts.
405 template <class... Args>
406 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
407 return format(fmt, std::forward<Args>(args)...);
409 template <class... Args>
410 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
411 return formatChecked(fmt, std::forward<Args>(args)...).str();
413 template <class Container>
414 Formatter<true, Container> vformatChecked(StringPiece fmt,
415 Container&& container) {
416 return vformat(fmt, std::forward<Container>(container));
418 template <class Container>
419 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
420 return vformatChecked(fmt, std::forward<Container>(container)).str();
422 template <class Str, class... Args>
423 typename std::enable_if<IsSomeString<Str>::value>::type
424 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
425 formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
427 template <class Str, class Container>
428 typename std::enable_if<IsSomeString<Str>::value>::type
429 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
430 vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
435 #include <folly/Format-inl.h>
437 #pragma GCC diagnostic pop