2 * Copyright 2012-present 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/CPortability.h>
26 #include <folly/Conv.h>
27 #include <folly/FormatArg.h>
28 #include <folly/Range.h>
29 #include <folly/String.h>
30 #include <folly/Traits.h>
32 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
34 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
38 // forward declarations
39 template <bool containerMode, class... Args>
41 template <class... Args>
42 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
44 Formatter<true, C> vformat(StringPiece fmt, C&& container);
45 template <class T, class Enable = void>
48 // meta-attribute to identify formatters in this sea of template weirdness
50 class FormatterTag {};
56 * Note that this class is tricky, as it keeps *references* to its lvalue
57 * arguments (while it takes ownership of the temporaries), and it doesn't
58 * copy the passed-in format string. Thankfully, you can't use this
59 * directly, you have to use format(...) below.
62 /* BaseFormatter class.
63 * Overridable behaviours:
64 * You may override the actual formatting of positional parameters in
65 * `doFormatArg`. The Formatter class provides the default implementation.
67 * You may also override `doFormat` and `getSizeArg`. These override points were
68 * added to permit static analysis of format strings, when it is inconvenient
69 * or impossible to instantiate a BaseFormatter with the correct storage
71 template <class Derived, bool containerMode, class... Args>
75 * Append to output. out(StringPiece sp) may be called (more than once)
77 template <class Output>
78 void operator()(Output& out) const;
84 typename std::enable_if<IsSomeString<Str>::value>::type appendTo(
86 auto appender = [&str](StringPiece s) { str.append(s.data(), s.size()); };
91 * Conversion to string
93 std::string str() const {
100 * Conversion to fbstring
102 fbstring fbstr() const {
109 * Metadata to identify generated children of BaseFormatter
111 typedef detail::FormatterTag IsFormatter;
112 typedef BaseFormatter BaseType;
115 typedef std::tuple<Args...> ValueTuple;
116 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
118 Derived const& asDerived() const {
119 return *static_cast<const Derived*>(this);
122 template <size_t K, class Callback>
123 typename std::enable_if<K == valueCount>::type
124 doFormatFrom(size_t i, FormatArg& arg, Callback& /*cb*/) const {
125 arg.error("argument index out of range, max=", i);
128 template <size_t K, class Callback>
129 typename std::enable_if<(K < valueCount)>::type
130 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
132 asDerived().template doFormatArg<K>(arg, cb);
134 doFormatFrom<K + 1>(i, arg, cb);
138 template <class Callback>
139 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
140 return doFormatFrom<0>(i, arg, cb);
144 typename std::enable_if<K == valueCount, int>::type getSizeArgFrom(
146 const FormatArg& arg) const {
147 arg.error("argument index out of range, max=", i);
151 typename std::enable_if<
152 std::is_integral<T>::value && !std::is_same<T, bool>::value,
154 getValue(const FormatValue<T>& format, const FormatArg&) const {
155 return static_cast<int>(format.getValue());
159 typename std::enable_if<
160 !std::is_integral<T>::value || std::is_same<T, bool>::value,
162 getValue(const FormatValue<T>&, const FormatArg& arg) const {
163 arg.error("dynamic field width argument must be integral");
167 typename std::enable_if <
168 K<valueCount, int>::type getSizeArgFrom(size_t i, const FormatArg& arg)
171 return getValue(getFormatValue<K>(), arg);
173 return getSizeArgFrom<K + 1>(i, arg);
176 int getSizeArg(size_t i, const FormatArg& arg) const {
177 return getSizeArgFrom<0>(i, arg);
183 explicit BaseFormatter(StringPiece str, Args&&... args);
186 BaseFormatter(const BaseFormatter&) = delete;
187 BaseFormatter& operator=(const BaseFormatter&) = delete;
189 // Movable, but the move constructor and assignment operator are private,
190 // for the exclusive use of format() (below). This way, you can't create
191 // a Formatter object, but can handle references to it (for streaming,
192 // conversion to string, etc) -- which is good, as Formatter objects are
193 // dangerous (they may hold references).
194 BaseFormatter(BaseFormatter&&) = default;
195 BaseFormatter& operator=(BaseFormatter&&) = default;
198 using ArgType = typename std::tuple_element<K, ValueTuple>::type;
201 FormatValue<typename std::decay<ArgType<K>>::type> getFormatValue() const {
202 return FormatValue<typename std::decay<ArgType<K>>::type>(
203 std::get<K>(values_));
209 template <bool containerMode, class... Args>
210 class Formatter : public BaseFormatter<
211 Formatter<containerMode, Args...>,
215 explicit Formatter(StringPiece& str, Args&&... args)
217 Formatter<containerMode, Args...>,
219 Args...>(str, std::forward<Args>(args)...) {
221 !containerMode || sizeof...(Args) == 1,
222 "Exactly one argument required in container mode");
225 template <size_t K, class Callback>
226 void doFormatArg(FormatArg& arg, Callback& cb) const {
227 this->template getFormatValue<K>().format(arg, cb);
230 friend class BaseFormatter<
231 Formatter<containerMode, Args...>,
235 template <class... A>
236 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
238 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
242 * Formatter objects can be written to streams.
244 template <bool containerMode, class... Args>
245 std::ostream& operator<<(
247 const Formatter<containerMode, Args...>& formatter) {
248 auto writer = [&out](StringPiece sp) {
249 out.write(sp.data(), std::streamsize(sp.size()));
256 * Formatter objects can be written to stdio FILEs.
258 template <class Derived, bool containerMode, class... Args>
261 const BaseFormatter<Derived, containerMode, Args...>& formatter);
264 * Create a formatter object.
266 * std::string formatted = format("{} {}", 23, 42).str();
267 * LOG(INFO) << format("{} {}", 23, 42);
268 * writeTo(stdout, format("{} {}", 23, 42));
270 template <class... Args>
271 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
272 return Formatter<false, Args...>(fmt, std::forward<Args>(args)...);
276 * Like format(), but immediately returns the formatted string instead of an
277 * intermediate format object.
279 template <class... Args>
280 inline std::string sformat(StringPiece fmt, Args&&... args) {
281 return format(fmt, std::forward<Args>(args)...).str();
285 * Create a formatter object that takes one argument (of container type)
286 * and uses that container to get argument values from.
288 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
290 * The following are equivalent:
291 * format("{0[hello]} {0[answer]}", map);
293 * vformat("{hello} {answer}", map);
295 * but the latter is cleaner.
297 template <class Container>
298 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
299 return Formatter<true, Container>(fmt, std::forward<Container>(container));
303 * Like vformat(), but immediately returns the formatted string instead of an
304 * intermediate format object.
306 template <class Container>
307 inline std::string svformat(StringPiece fmt, Container&& container) {
308 return vformat(fmt, std::forward<Container>(container)).str();
312 * Exception class thrown when a format key is not found in the given
313 * associative container keyed by strings. We inherit std::out_of_range for
314 * compatibility with callers that expect exception to be thrown directly
315 * by std::map or std::unordered_map.
317 * Having the key be at the end of the message string, we can access it by
318 * simply adding its offset to what(). Not storing separate std::string key
319 * makes the exception type small and noexcept-copyable like std::out_of_range,
320 * and therefore able to fit in-situ in exception_wrapper.
322 class FOLLY_EXPORT FormatKeyNotFoundException : public std::out_of_range {
324 explicit FormatKeyNotFoundException(StringPiece key);
326 char const* key() const noexcept {
327 return what() + kMessagePrefix.size();
331 static constexpr StringPiece const kMessagePrefix = "format key not found: ";
335 [[noreturn]] void throwFormatKeyNotFoundException(StringPiece key);
336 } // namespace detail
339 * Wrap a sequence or associative container so that out-of-range lookups
340 * return a default value rather than throwing an exception.
343 * format("[no_such_key"], defaulted(map, 42)) -> 42
346 template <class Container, class Value>
347 struct DefaultValueWrapper {
348 DefaultValueWrapper(const Container& container, const Value& defaultValue)
349 : container(container), defaultValue(defaultValue) {}
351 const Container& container;
352 const Value& defaultValue;
354 } // namespace detail
356 template <class Container, class Value>
357 detail::DefaultValueWrapper<Container, Value> defaulted(
360 return detail::DefaultValueWrapper<Container, Value>(c, v);
364 * Append formatted output to a string.
367 * format(&foo, "{} {}", 42, 23);
369 * Shortcut for toAppend(format(...), &foo);
371 template <class Str, class... Args>
372 typename std::enable_if<IsSomeString<Str>::value>::type
373 format(Str* out, StringPiece fmt, Args&&... args) {
374 format(fmt, std::forward<Args>(args)...).appendTo(*out);
378 * Append vformatted output to a string.
380 template <class Str, class Container>
381 typename std::enable_if<IsSomeString<Str>::value>::type
382 vformat(Str* out, StringPiece fmt, Container&& container) {
383 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
387 * Utilities for all format value specializations.
389 namespace format_value {
392 * Format a string in "val", obeying appropriate alignment, padding, width,
393 * and precision. Treats Align::DEFAULT as Align::LEFT, and
394 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
395 * number-specific formatting.
397 template <class FormatCallback>
398 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
401 * Format a number in "val"; the first prefixLen characters form the prefix
402 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
403 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
404 * arg.precision, as that has a different meaning for numbers (not "maximum
407 template <class FormatCallback>
415 * Format a Formatter object recursively. Behaves just like
416 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
417 * string if possible.
420 class FormatCallback,
424 void formatFormatter(
425 const BaseFormatter<Derived, containerMode, Args...>& formatter,
429 } // namespace format_value
432 * Specialize folly::FormatValue for your type.
434 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
435 * guaranteed to stay alive until the FormatValue object is destroyed, so you
436 * may keep a reference (or pointer) to it instead of making a copy.
439 * template <class Callback>
440 * void format(FormatArg& arg, Callback& cb) const;
441 * with the following semantics: format the value using the given argument.
443 * arg is given by non-const reference for convenience -- it won't be reused,
444 * so feel free to modify it in place if necessary. (For example, wrap an
445 * existing conversion but change the default, or remove the "key" when
446 * extracting an element from a container)
448 * Call the callback to append data to the output. You may call the callback
449 * as many times as you'd like (or not at all, if you want to output an
455 template <class T, class Enable = void>
456 struct IsFormatter : public std::false_type {};
461 typename std::enable_if<
462 std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
463 type> : public std::true_type {};
464 } // namespace detail
466 // Deprecated API. formatChecked() et. al. now behave identically to their
467 // non-Checked counterparts.
468 template <class... Args>
469 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
470 return format(fmt, std::forward<Args>(args)...);
472 template <class... Args>
473 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
474 return formatChecked(fmt, std::forward<Args>(args)...).str();
476 template <class Container>
477 Formatter<true, Container> vformatChecked(
479 Container&& container) {
480 return vformat(fmt, std::forward<Container>(container));
482 template <class Container>
483 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
484 return vformatChecked(fmt, std::forward<Container>(container)).str();
486 template <class Str, class... Args>
487 typename std::enable_if<IsSomeString<Str>::value>::type
488 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
489 formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
491 template <class Str, class Container>
492 typename std::enable_if<IsSomeString<Str>::value>::type
493 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
494 vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
499 #include <folly/Format-inl.h>