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_
23 #include <type_traits>
25 #include <folly/Conv.h>
26 #include <folly/FormatArg.h>
27 #include <folly/Range.h>
28 #include <folly/String.h>
29 #include <folly/Traits.h>
31 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
33 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
37 // forward declarations
38 template <bool containerMode, class... Args>
40 template <class... Args>
41 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
43 Formatter<true, C> vformat(StringPiece fmt, C&& container);
44 template <class T, class Enable = void>
47 // meta-attribute to identify formatters in this sea of template weirdness
49 class FormatterTag {};
55 * Note that this class is tricky, as it keeps *references* to its lvalue
56 * arguments (while it takes ownership of the temporaries), and it doesn't
57 * copy the passed-in format string. Thankfully, you can't use this
58 * directly, you have to use format(...) below.
61 /* BaseFormatter class.
62 * Overridable behaviours:
63 * You may override the actual formatting of positional parameters in
64 * `doFormatArg`. The Formatter class provides the default implementation.
66 * You may also override `doFormat` and `getSizeArg`. These override points were
67 * added to permit static analysis of format strings, when it is inconvenient
68 * or impossible to instantiate a BaseFormatter with the correct storage
70 template <class Derived, bool containerMode, class... Args>
74 * Append to output. out(StringPiece sp) may be called (more than once)
76 template <class Output>
77 void operator()(Output& out) const;
83 typename std::enable_if<IsSomeString<Str>::value>::type appendTo(
85 auto appender = [&str](StringPiece s) { str.append(s.data(), s.size()); };
90 * Conversion to string
92 std::string str() const {
99 * Conversion to fbstring
101 fbstring fbstr() const {
108 * Metadata to identify generated children of BaseFormatter
110 typedef detail::FormatterTag IsFormatter;
111 typedef BaseFormatter BaseType;
114 typedef std::tuple<Args...> ValueTuple;
115 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
117 Derived const& asDerived() const {
118 return *static_cast<const Derived*>(this);
121 template <size_t K, class Callback>
122 typename std::enable_if<K == valueCount>::type
123 doFormatFrom(size_t i, FormatArg& arg, Callback& /*cb*/) const {
124 arg.error("argument index out of range, max=", i);
127 template <size_t K, class Callback>
128 typename std::enable_if<(K < valueCount)>::type
129 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
131 asDerived().template doFormatArg<K>(arg, cb);
133 doFormatFrom<K + 1>(i, arg, cb);
137 template <class Callback>
138 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
139 return doFormatFrom<0>(i, arg, cb);
143 typename std::enable_if<K == valueCount, int>::type getSizeArgFrom(
145 const FormatArg& arg) const {
146 arg.error("argument index out of range, max=", i);
150 typename std::enable_if<
151 std::is_integral<T>::value && !std::is_same<T, bool>::value,
153 getValue(const FormatValue<T>& format, const FormatArg&) const {
154 return static_cast<int>(format.getValue());
158 typename std::enable_if<
159 !std::is_integral<T>::value || std::is_same<T, bool>::value,
161 getValue(const FormatValue<T>&, const FormatArg& arg) const {
162 arg.error("dynamic field width argument must be integral");
166 typename std::enable_if <
167 K<valueCount, int>::type getSizeArgFrom(size_t i, const FormatArg& arg)
170 return getValue(getFormatValue<K>(), arg);
172 return getSizeArgFrom<K + 1>(i, arg);
175 int getSizeArg(size_t i, const FormatArg& arg) const {
176 return getSizeArgFrom<0>(i, arg);
182 explicit BaseFormatter(StringPiece str, Args&&... args);
185 BaseFormatter(const BaseFormatter&) = delete;
186 BaseFormatter& operator=(const BaseFormatter&) = delete;
188 // Movable, but the move constructor and assignment operator are private,
189 // for the exclusive use of format() (below). This way, you can't create
190 // a Formatter object, but can handle references to it (for streaming,
191 // conversion to string, etc) -- which is good, as Formatter objects are
192 // dangerous (they may hold references).
193 BaseFormatter(BaseFormatter&&) = default;
194 BaseFormatter& operator=(BaseFormatter&&) = default;
197 using ArgType = typename std::tuple_element<K, ValueTuple>::type;
200 FormatValue<typename std::decay<ArgType<K>>::type> getFormatValue() const {
201 return FormatValue<typename std::decay<ArgType<K>>::type>(
202 std::get<K>(values_));
208 template <bool containerMode, class... Args>
209 class Formatter : public BaseFormatter<
210 Formatter<containerMode, Args...>,
214 explicit Formatter(StringPiece& str, Args&&... args)
216 Formatter<containerMode, Args...>,
218 Args...>(str, std::forward<Args>(args)...) {
220 !containerMode || sizeof...(Args) == 1,
221 "Exactly one argument required in container mode");
224 template <size_t K, class Callback>
225 void doFormatArg(FormatArg& arg, Callback& cb) const {
226 this->template getFormatValue<K>().format(arg, cb);
229 friend class BaseFormatter<
230 Formatter<containerMode, Args...>,
234 template <class... A>
235 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
237 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
241 * Formatter objects can be written to streams.
243 template <bool containerMode, class... Args>
244 std::ostream& operator<<(
246 const Formatter<containerMode, Args...>& formatter) {
247 auto writer = [&out](StringPiece sp) {
248 out.write(sp.data(), std::streamsize(sp.size()));
255 * Formatter objects can be written to stdio FILEs.
257 template <class Derived, bool containerMode, class... Args>
260 const BaseFormatter<Derived, containerMode, Args...>& formatter);
263 * Create a formatter object.
265 * std::string formatted = format("{} {}", 23, 42).str();
266 * LOG(INFO) << format("{} {}", 23, 42);
267 * writeTo(stdout, format("{} {}", 23, 42));
269 template <class... Args>
270 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
271 return Formatter<false, Args...>(fmt, std::forward<Args>(args)...);
275 * Like format(), but immediately returns the formatted string instead of an
276 * intermediate format object.
278 template <class... Args>
279 inline std::string sformat(StringPiece fmt, Args&&... args) {
280 return format(fmt, std::forward<Args>(args)...).str();
284 * Create a formatter object that takes one argument (of container type)
285 * and uses that container to get argument values from.
287 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
289 * The following are equivalent:
290 * format("{0[hello]} {0[answer]}", map);
292 * vformat("{hello} {answer}", map);
294 * but the latter is cleaner.
296 template <class Container>
297 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
298 return Formatter<true, Container>(fmt, std::forward<Container>(container));
302 * Like vformat(), but immediately returns the formatted string instead of an
303 * intermediate format object.
305 template <class Container>
306 inline std::string svformat(StringPiece fmt, Container&& container) {
307 return vformat(fmt, std::forward<Container>(container)).str();
311 * Exception class thrown when a format key is not found in the given
312 * associative container keyed by strings. We inherit std::out_of_range for
313 * compatibility with callers that expect exception to be thrown directly
314 * by std::map or std::unordered_map.
316 * Having the key be at the end of the message string, we can access it by
317 * simply adding its offset to what(). Not storing separate std::string key
318 * makes the exception type small and noexcept-copyable like std::out_of_range,
319 * and therefore able to fit in-situ in exception_wrapper.
321 class FormatKeyNotFoundException : public std::out_of_range {
323 explicit FormatKeyNotFoundException(StringPiece key);
325 char const* key() const noexcept {
326 return what() + kMessagePrefix.size();
330 static constexpr StringPiece const kMessagePrefix = "format key not found: ";
334 [[noreturn]] void throwFormatKeyNotFoundException(StringPiece key);
335 } // namespace detail
338 * Wrap a sequence or associative container so that out-of-range lookups
339 * return a default value rather than throwing an exception.
342 * format("[no_such_key"], defaulted(map, 42)) -> 42
345 template <class Container, class Value>
346 struct DefaultValueWrapper {
347 DefaultValueWrapper(const Container& container, const Value& defaultValue)
348 : container(container), defaultValue(defaultValue) {}
350 const Container& container;
351 const Value& defaultValue;
353 } // namespace detail
355 template <class Container, class Value>
356 detail::DefaultValueWrapper<Container, Value> defaulted(
359 return detail::DefaultValueWrapper<Container, Value>(c, v);
363 * Append formatted output to a string.
366 * format(&foo, "{} {}", 42, 23);
368 * Shortcut for toAppend(format(...), &foo);
370 template <class Str, class... Args>
371 typename std::enable_if<IsSomeString<Str>::value>::type
372 format(Str* out, StringPiece fmt, Args&&... args) {
373 format(fmt, std::forward<Args>(args)...).appendTo(*out);
377 * Append vformatted output to a string.
379 template <class Str, class Container>
380 typename std::enable_if<IsSomeString<Str>::value>::type
381 vformat(Str* out, StringPiece fmt, Container&& container) {
382 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
386 * Utilities for all format value specializations.
388 namespace format_value {
391 * Format a string in "val", obeying appropriate alignment, padding, width,
392 * and precision. Treats Align::DEFAULT as Align::LEFT, and
393 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
394 * number-specific formatting.
396 template <class FormatCallback>
397 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
400 * Format a number in "val"; the first prefixLen characters form the prefix
401 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
402 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
403 * arg.precision, as that has a different meaning for numbers (not "maximum
406 template <class FormatCallback>
414 * Format a Formatter object recursively. Behaves just like
415 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
416 * string if possible.
419 class FormatCallback,
423 void formatFormatter(
424 const BaseFormatter<Derived, containerMode, Args...>& formatter,
428 } // namespace format_value
431 * Specialize folly::FormatValue for your type.
433 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
434 * guaranteed to stay alive until the FormatValue object is destroyed, so you
435 * may keep a reference (or pointer) to it instead of making a copy.
438 * template <class Callback>
439 * void format(FormatArg& arg, Callback& cb) const;
440 * with the following semantics: format the value using the given argument.
442 * arg is given by non-const reference for convenience -- it won't be reused,
443 * so feel free to modify it in place if necessary. (For example, wrap an
444 * existing conversion but change the default, or remove the "key" when
445 * extracting an element from a container)
447 * Call the callback to append data to the output. You may call the callback
448 * as many times as you'd like (or not at all, if you want to output an
454 template <class T, class Enable = void>
455 struct IsFormatter : public std::false_type {};
460 typename std::enable_if<
461 std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
462 type> : public std::true_type {};
463 } // namespace detail
465 // Deprecated API. formatChecked() et. al. now behave identically to their
466 // non-Checked counterparts.
467 template <class... Args>
468 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
469 return format(fmt, std::forward<Args>(args)...);
471 template <class... Args>
472 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
473 return formatChecked(fmt, std::forward<Args>(args)...).str();
475 template <class Container>
476 Formatter<true, Container> vformatChecked(
478 Container&& container) {
479 return vformat(fmt, std::forward<Container>(container));
481 template <class Container>
482 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
483 return vformatChecked(fmt, std::forward<Container>(container)).str();
485 template <class Str, class... Args>
486 typename std::enable_if<IsSomeString<Str>::value>::type
487 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
488 formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
490 template <class Str, class Container>
491 typename std::enable_if<IsSomeString<Str>::value>::type
492 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
493 vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
498 #include <folly/Format-inl.h>