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.
31 #pragma GCC diagnostic push
32 #pragma GCC diagnostic ignored "-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. Currently, the only behavior that can be
60 * overridden is the actual formatting of positional parameters in
61 * `doFormatArg`. The Formatter class provides the default implementation.
63 template <class Derived, bool containerMode, class... Args>
67 * Append to output. out(StringPiece sp) may be called (more than once)
69 template <class Output>
70 void operator()(Output& out) const;
76 typename std::enable_if<IsSomeString<Str>::value>::type appendTo(
78 auto appender = [&str](StringPiece s) { str.append(s.data(), s.size()); };
83 * Conversion to string
85 std::string str() const {
92 * Conversion to fbstring
94 fbstring fbstr() const {
101 * metadata to identify generated children of BaseFormatter
103 typedef detail::FormatterTag IsFormatter;
104 typedef BaseFormatter BaseType;
107 typedef std::tuple<FormatValue<typename std::decay<Args>::type>...>
109 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
111 template <size_t K, class Callback>
112 typename std::enable_if<K == valueCount>::type
113 doFormatFrom(size_t i, FormatArg& arg, Callback& /*cb*/) const {
114 arg.error("argument index out of range, max=", i);
117 template <size_t K, class Callback>
118 typename std::enable_if<(K < valueCount)>::type
119 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
121 static_cast<const Derived*>(this)->template doFormatArg<K>(arg, cb);
123 doFormatFrom<K + 1>(i, arg, cb);
127 template <class Callback>
128 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
129 return doFormatFrom<0>(i, arg, cb);
133 typename std::enable_if<K == valueCount, int>::type getSizeArgFrom(
135 const FormatArg& arg) const {
136 arg.error("argument index out of range, max=", i);
140 typename std::enable_if<
141 std::is_integral<T>::value && !std::is_same<T, bool>::value,
143 getValue(const FormatValue<T>& format, const FormatArg&) const {
144 return static_cast<int>(format.getValue());
148 typename std::enable_if<
149 !std::is_integral<T>::value || std::is_same<T, bool>::value,
151 getValue(const FormatValue<T>&, const FormatArg& arg) const {
152 arg.error("dynamic field width argument must be integral");
156 typename std::enable_if <
157 K<valueCount, int>::type getSizeArgFrom(size_t i, const FormatArg& arg)
160 return getValue(std::get<K>(values_), arg);
162 return getSizeArgFrom<K + 1>(i, arg);
165 int getSizeArg(size_t i, const FormatArg& arg) const {
166 return getSizeArgFrom<0>(i, arg);
172 explicit BaseFormatter(StringPiece str, Args&&... args);
175 BaseFormatter(const BaseFormatter&) = delete;
176 BaseFormatter& operator=(const BaseFormatter&) = delete;
178 // Movable, but the move constructor and assignment operator are private,
179 // for the exclusive use of format() (below). This way, you can't create
180 // a Formatter object, but can handle references to it (for streaming,
181 // conversion to string, etc) -- which is good, as Formatter objects are
182 // dangerous (they hold references, possibly to temporaries)
183 BaseFormatter(BaseFormatter&&) = default;
184 BaseFormatter& operator=(BaseFormatter&&) = default;
189 template <bool containerMode, class... Args>
190 class Formatter : public BaseFormatter<
191 Formatter<containerMode, Args...>,
195 explicit Formatter(StringPiece& str, Args&&... args)
197 Formatter<containerMode, Args...>,
199 Args...>(str, std::forward<Args>(args)...) {}
201 template <size_t K, class Callback>
202 void doFormatArg(FormatArg& arg, Callback& cb) const {
203 std::get<K>(this->values_).format(arg, cb);
206 friend class BaseFormatter<
207 Formatter<containerMode, Args...>,
211 template <class... A>
212 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
214 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
218 * Formatter objects can be written to streams.
220 template <bool containerMode, class... Args>
221 std::ostream& operator<<(
223 const Formatter<containerMode, Args...>& formatter) {
224 auto writer = [&out](StringPiece sp) {
225 out.write(sp.data(), std::streamsize(sp.size()));
232 * Formatter objects can be written to stdio FILEs.
234 template <class Derived, bool containerMode, class... Args>
237 const BaseFormatter<Derived, containerMode, Args...>& formatter);
240 * Create a formatter object.
242 * std::string formatted = format("{} {}", 23, 42).str();
243 * LOG(INFO) << format("{} {}", 23, 42);
244 * writeTo(stdout, format("{} {}", 23, 42));
246 template <class... Args>
247 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
248 return Formatter<false, Args...>(fmt, std::forward<Args>(args)...);
252 * Like format(), but immediately returns the formatted string instead of an
253 * intermediate format object.
255 template <class... Args>
256 inline std::string sformat(StringPiece fmt, Args&&... args) {
257 return format(fmt, std::forward<Args>(args)...).str();
261 * Create a formatter object that takes one argument (of container type)
262 * and uses that container to get argument values from.
264 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
266 * The following are equivalent:
267 * format("{0[hello]} {0[answer]}", map);
269 * vformat("{hello} {answer}", map);
271 * but the latter is cleaner.
273 template <class Container>
274 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
275 return Formatter<true, Container>(fmt, std::forward<Container>(container));
279 * Like vformat(), but immediately returns the formatted string instead of an
280 * intermediate format object.
282 template <class Container>
283 inline std::string svformat(StringPiece fmt, Container&& container) {
284 return vformat(fmt, std::forward<Container>(container)).str();
288 * Wrap a sequence or associative container so that out-of-range lookups
289 * return a default value rather than throwing an exception.
292 * format("[no_such_key"], defaulted(map, 42)) -> 42
295 template <class Container, class Value>
296 struct DefaultValueWrapper {
297 DefaultValueWrapper(const Container& container, const Value& defaultValue)
298 : container(container), defaultValue(defaultValue) {}
300 const Container& container;
301 const Value& defaultValue;
305 template <class Container, class Value>
306 detail::DefaultValueWrapper<Container, Value> defaulted(
309 return detail::DefaultValueWrapper<Container, Value>(c, v);
313 * Append formatted output to a string.
316 * format(&foo, "{} {}", 42, 23);
318 * Shortcut for toAppend(format(...), &foo);
320 template <class Str, class... Args>
321 typename std::enable_if<IsSomeString<Str>::value>::type
322 format(Str* out, StringPiece fmt, Args&&... args) {
323 format(fmt, std::forward<Args>(args)...).appendTo(*out);
327 * Append vformatted output to a string.
329 template <class Str, class Container>
330 typename std::enable_if<IsSomeString<Str>::value>::type
331 vformat(Str* out, StringPiece fmt, Container&& container) {
332 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
336 * Utilities for all format value specializations.
338 namespace format_value {
341 * Format a string in "val", obeying appropriate alignment, padding, width,
342 * and precision. Treats Align::DEFAULT as Align::LEFT, and
343 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
344 * number-specific formatting.
346 template <class FormatCallback>
347 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
350 * Format a number in "val"; the first prefixLen characters form the prefix
351 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
352 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
353 * arg.precision, as that has a different meaning for numbers (not "maximum
356 template <class FormatCallback>
364 * Format a Formatter object recursively. Behaves just like
365 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
366 * string if possible.
369 class FormatCallback,
373 void formatFormatter(
374 const BaseFormatter<Derived, containerMode, Args...>& formatter,
378 } // namespace format_value
381 * Specialize folly::FormatValue for your type.
383 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
384 * guaranteed to stay alive until the FormatValue object is destroyed, so you
385 * may keep a reference (or pointer) to it instead of making a copy.
388 * template <class Callback>
389 * void format(FormatArg& arg, Callback& cb) const;
390 * with the following semantics: format the value using the given argument.
392 * arg is given by non-const reference for convenience -- it won't be reused,
393 * so feel free to modify it in place if necessary. (For example, wrap an
394 * existing conversion but change the default, or remove the "key" when
395 * extracting an element from a container)
397 * Call the callback to append data to the output. You may call the callback
398 * as many times as you'd like (or not at all, if you want to output an
404 template <class T, class Enable = void>
405 struct IsFormatter : public std::false_type {};
410 typename std::enable_if<
411 std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
412 type> : public std::true_type {};
415 // Deprecated API. formatChecked() et. al. now behave identically to their
416 // non-Checked counterparts.
417 template <class... Args>
418 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
419 return format(fmt, std::forward<Args>(args)...);
421 template <class... Args>
422 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
423 return formatChecked(fmt, std::forward<Args>(args)...).str();
425 template <class Container>
426 Formatter<true, Container> vformatChecked(
428 Container&& container) {
429 return vformat(fmt, std::forward<Container>(container));
431 template <class Container>
432 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
433 return vformatChecked(fmt, std::forward<Container>(container)).str();
435 template <class Str, class... Args>
436 typename std::enable_if<IsSomeString<Str>::value>::type
437 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
438 formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
440 template <class Str, class Container>
441 typename std::enable_if<IsSomeString<Str>::value>::type
442 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
443 vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
448 #include <folly/Format-inl.h>
450 #pragma GCC diagnostic pop