2 * Copyright 2014 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.
17 #ifndef FOLLY_FORMAT_H_
18 #define FOLLY_FORMAT_H_
23 #include <type_traits>
27 #include <unordered_map>
29 #include <double-conversion/double-conversion.h>
31 #include <folly/FBVector.h>
32 #include <folly/Conv.h>
33 #include <folly/Range.h>
34 #include <folly/Traits.h>
35 #include <folly/Likely.h>
36 #include <folly/String.h>
37 #include <folly/small_vector.h>
38 #include <folly/FormatArg.h>
40 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
41 #pragma GCC diagnostic push
42 #pragma GCC diagnostic ignored "-Wshadow"
46 // forward declarations
47 template <bool containerMode, class... Args> class Formatter;
48 template <class... Args>
49 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
51 Formatter<true, C> vformat(StringPiece fmt, C&& container);
52 template <class T, class Enable=void> class FormatValue;
54 // meta-attribute to identify formatters in this sea of template weirdness
56 class FormatterTag {};
62 * Note that this class is tricky, as it keeps *references* to its arguments
63 * (and doesn't copy the passed-in format string). Thankfully, you can't use
64 * this directly, you have to use format(...) below.
67 /* BaseFormatter class. Currently, the only behavior that can be
68 * overridden is the actual formatting of positional parameters in
69 * `doFormatArg`. The Formatter class provides the default implementation.
71 template <class Derived, bool containerMode, class... Args>
75 * Change whether or not Formatter should crash or throw exceptions if the
76 * format string is invalid.
78 * Crashing is desirable for literal format strings that are fixed at compile
79 * time. Errors in the format string are generally programmer bugs, and
80 * should be caught early on in development. Crashing helps ensure these
81 * problems are noticed.
83 void setCrashOnError(bool crash) {
84 crashOnError_ = crash;
88 * Append to output. out(StringPiece sp) may be called (more than once)
90 template <class Output>
91 void operator()(Output& out) const;
97 typename std::enable_if<IsSomeString<Str>::value>::type
98 appendTo(Str& str) const {
99 auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
104 * Conversion to string
106 std::string str() const {
113 * Conversion to fbstring
115 fbstring fbstr() const {
122 * metadata to identify generated children of BaseFormatter
124 typedef detail::FormatterTag IsFormatter;
125 typedef BaseFormatter BaseType;
128 typedef std::tuple<FormatValue<
129 typename std::decay<Args>::type>...> ValueTuple;
130 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
132 FOLLY_NORETURN void handleFormatStrError() const;
133 template <class Output>
134 void appendOutput(Output& out) const;
136 template <size_t K, class Callback>
137 typename std::enable_if<K == valueCount>::type
138 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
139 arg.error("argument index out of range, max=", i);
142 template <size_t K, class Callback>
143 typename std::enable_if<(K < valueCount)>::type
144 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
146 static_cast<const Derived*>(this)->template doFormatArg<K>(arg, cb);
148 doFormatFrom<K+1>(i, arg, cb);
152 template <class Callback>
153 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
154 return doFormatFrom<0>(i, arg, cb);
158 bool crashOnError_{true};
161 explicit BaseFormatter(StringPiece str, Args&&... args);
164 BaseFormatter(const BaseFormatter&) = delete;
165 BaseFormatter& operator=(const BaseFormatter&) = delete;
167 // Movable, but the move constructor and assignment operator are private,
168 // for the exclusive use of format() (below). This way, you can't create
169 // a Formatter object, but can handle references to it (for streaming,
170 // conversion to string, etc) -- which is good, as Formatter objects are
171 // dangerous (they hold references, possibly to temporaries)
172 BaseFormatter(BaseFormatter&&) = default;
173 BaseFormatter& operator=(BaseFormatter&&) = default;
178 template <bool containerMode, class... Args>
179 class Formatter : public BaseFormatter<Formatter<containerMode, Args...>,
183 explicit Formatter(StringPiece& str, Args&&... args)
184 : BaseFormatter<Formatter<containerMode, Args...>,
186 Args...>(str, std::forward<Args>(args)...) {}
188 template <size_t K, class Callback>
189 void doFormatArg(FormatArg& arg, Callback& cb) const {
190 std::get<K>(this->values_).format(arg, cb);
193 friend class BaseFormatter<Formatter<containerMode, Args...>,
197 template <class... A>
198 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
199 template <class... A>
200 friend Formatter<false, A...> formatChecked(StringPiece fmt, A&&... arg);
202 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
204 friend Formatter<true, C> vformatChecked(StringPiece fmt, C&& container);
208 * Formatter objects can be written to streams.
210 template<bool containerMode, class... Args>
211 std::ostream& operator<<(std::ostream& out,
212 const Formatter<containerMode, Args...>& formatter) {
213 auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
219 * Formatter objects can be written to stdio FILEs.
221 template <class Derived, bool containerMode, class... Args>
222 void writeTo(FILE* fp,
223 const BaseFormatter<Derived, containerMode, Args...>& formatter);
226 * Create a formatter object.
228 * std::string formatted = format("{} {}", 23, 42).str();
229 * LOG(INFO) << format("{} {}", 23, 42);
230 * writeTo(stdout, format("{} {}", 23, 42));
232 * Note that format() will crash the program if the format string is invalid.
233 * Normally, the format string is a fixed string literal specified by the
234 * programmer. Invalid format strings are normally programmer bugs, and should
235 * be caught early on during development. Crashing helps ensure these bugs are
238 * Use formatChecked() if you have a dynamic format string (for example, a user
239 * supplied value). formatChecked() will throw an exception rather than
240 * crashing the program.
242 template <class... Args>
243 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
244 return Formatter<false, Args...>(
245 fmt, std::forward<Args>(args)...);
249 * Like format(), but immediately returns the formatted string instead of an
250 * intermediate format object.
252 template <class... Args>
253 inline std::string sformat(StringPiece fmt, Args&&... args) {
254 return format(fmt, std::forward<Args>(args)...).str();
258 * Create a formatter object from a dynamic format string.
260 * This is identical to format(), but throws an exception if the format string
261 * is invalid, rather than aborting the program. This allows it to be used
262 * with user-specified format strings which are not guaranteed to be well
265 template <class... Args>
266 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
267 Formatter<false, Args...> f(fmt, std::forward<Args>(args)...);
268 f.setCrashOnError(false);
273 * Like formatChecked(), but immediately returns the formatted string instead of
274 * an intermediate format object.
276 template <class... Args>
277 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
278 return formatChecked(fmt, std::forward<Args>(args)...).str();
282 * Create a formatter object that takes one argument (of container type)
283 * and uses that container to get argument values from.
285 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
287 * The following are equivalent:
288 * format("{0[hello]} {0[answer]}", map);
290 * vformat("{hello} {answer}", map);
292 * but the latter is cleaner.
294 template <class Container>
295 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
296 return Formatter<true, Container>(
297 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 * Create a formatter object from a dynamic format string.
312 * This is identical to vformat(), but throws an exception if the format string
313 * is invalid, rather than aborting the program. This allows it to be used
314 * with user-specified format strings which are not guaranteed to be well
317 template <class Container>
318 Formatter<true, Container> vformatChecked(StringPiece fmt,
319 Container&& container) {
320 Formatter<true, Container> f(fmt, std::forward<Container>(container));
321 f.setCrashOnError(false);
326 * Like vformatChecked(), but immediately returns the formatted string instead
327 * of an intermediate format object.
329 template <class Container>
330 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
331 return vformatChecked(fmt, std::forward<Container>(container)).str();
335 * Wrap a sequence or associative container so that out-of-range lookups
336 * return a default value rather than throwing an exception.
339 * format("[no_such_key"], defaulted(map, 42)) -> 42
342 template <class Container, class Value> struct DefaultValueWrapper {
343 DefaultValueWrapper(const Container& container, const Value& defaultValue)
344 : container(container),
345 defaultValue(defaultValue) {
348 const Container& container;
349 const Value& defaultValue;
353 template <class Container, class Value>
354 detail::DefaultValueWrapper<Container, Value>
355 defaulted(const Container& c, const Value& v) {
356 return detail::DefaultValueWrapper<Container, Value>(c, v);
360 * Append formatted output to a string.
363 * format(&foo, "{} {}", 42, 23);
365 * Shortcut for toAppend(format(...), &foo);
367 template <class Str, class... Args>
368 typename std::enable_if<IsSomeString<Str>::value>::type
369 format(Str* out, StringPiece fmt, Args&&... args) {
370 format(fmt, std::forward<Args>(args)...).appendTo(*out);
373 template <class Str, class... Args>
374 typename std::enable_if<IsSomeString<Str>::value>::type
375 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
376 formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
380 * Append vformatted output to a string.
382 template <class Str, class Container>
383 typename std::enable_if<IsSomeString<Str>::value>::type
384 vformat(Str* out, StringPiece fmt, Container&& container) {
385 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
388 template <class Str, class Container>
389 typename std::enable_if<IsSomeString<Str>::value>::type
390 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
391 vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
395 * Utilities for all format value specializations.
397 namespace format_value {
400 * Format a string in "val", obeying appropriate alignment, padding, width,
401 * and precision. Treats Align::DEFAULT as Align::LEFT, and
402 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
403 * number-specific formatting.
405 template <class FormatCallback>
406 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
409 * Format a number in "val"; the first prefixLen characters form the prefix
410 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
411 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
412 * arg.precision, as that has a different meaning for numbers (not "maximum
415 template <class FormatCallback>
416 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
421 * Format a Formatter object recursively. Behaves just like
422 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
423 * string if possible.
425 template <class FormatCallback,
429 void formatFormatter(
430 const BaseFormatter<Derived, containerMode, Args...>& formatter,
434 } // namespace format_value
437 * Specialize folly::FormatValue for your type.
439 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
440 * guaranteed to stay alive until the FormatValue object is destroyed, so you
441 * may keep a reference (or pointer) to it instead of making a copy.
444 * template <class Callback>
445 * void format(FormatArg& arg, Callback& cb) const;
446 * with the following semantics: format the value using the given argument.
448 * arg is given by non-const reference for convenience -- it won't be reused,
449 * so feel free to modify it in place if necessary. (For example, wrap an
450 * existing conversion but change the default, or remove the "key" when
451 * extracting an element from a container)
453 * Call the callback to append data to the output. You may call the callback
454 * as many times as you'd like (or not at all, if you want to output an
460 template <class T, class Enable = void>
461 struct IsFormatter : public std::false_type {};
466 typename std::enable_if<
467 std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
468 type> : public std::true_type {};
473 #include <folly/Format-inl.h>
475 #pragma GCC diagnostic pop
477 #endif /* FOLLY_FORMAT_H_ */