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;
57 * Note that this class is tricky, as it keeps *references* to its arguments
58 * (and doesn't copy the passed-in format string). Thankfully, you can't use
59 * this directly, you have to use format(...) below.
62 template <bool containerMode, class... Args>
66 * Change whether or not Formatter should crash or throw exceptions if the
67 * format string is invalid.
69 * Crashing is desirable for literal format strings that are fixed at compile
70 * time. Errors in the format string are generally programmer bugs, and
71 * should be caught early on in development. Crashing helps ensure these
72 * problems are noticed.
74 void setCrashOnError(bool crash) {
75 crashOnError_ = crash;
79 * Append to output. out(StringPiece sp) may be called (more than once)
81 template <class Output>
82 void operator()(Output& out) const;
88 typename std::enable_if<IsSomeString<Str>::value>::type
89 appendTo(Str& str) const {
90 auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
95 * Conversion to string
97 std::string str() const {
104 * Conversion to fbstring
106 fbstring fbstr() const {
113 explicit Formatter(StringPiece str, Args&&... args);
116 Formatter(const Formatter&) = delete;
117 Formatter& operator=(const Formatter&) = delete;
119 // Movable, but the move constructor and assignment operator are private,
120 // for the exclusive use of format() (below). This way, you can't create
121 // a Formatter object, but can handle references to it (for streaming,
122 // conversion to string, etc) -- which is good, as Formatter objects are
123 // dangerous (they hold references, possibly to temporaries)
124 Formatter(Formatter&&) = default;
125 Formatter& operator=(Formatter&&) = default;
127 typedef std::tuple<FormatValue<
128 typename std::decay<Args>::type>...> ValueTuple;
129 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
131 FOLLY_NORETURN void handleFormatStrError() const;
132 template <class Output>
133 void appendOutput(Output& out) const;
135 template <size_t K, class Callback>
136 typename std::enable_if<K == valueCount>::type
137 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
138 arg.error("argument index out of range, max=", i);
141 template <size_t K, class Callback>
142 typename std::enable_if<(K < valueCount)>::type
143 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
145 std::get<K>(values_).format(arg, cb);
147 doFormatFrom<K+1>(i, arg, cb);
151 template <class Callback>
152 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
153 return doFormatFrom<0>(i, arg, cb);
158 bool crashOnError_{true};
160 template <class... A>
161 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
162 template <class... A>
163 friend Formatter<false, A...> formatChecked(StringPiece fmt, A&&... arg);
165 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
167 friend Formatter<true, C> vformatChecked(StringPiece fmt, C&& container);
171 * Formatter objects can be written to streams.
173 template<bool containerMode, class... Args>
174 std::ostream& operator<<(std::ostream& out,
175 const Formatter<containerMode, Args...>& formatter) {
176 auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
182 * Formatter objects can be written to stdio FILEs.
184 template<bool containerMode, class... Args>
185 void writeTo(FILE* fp, const Formatter<containerMode, Args...>& formatter);
188 * Create a formatter object.
190 * std::string formatted = format("{} {}", 23, 42).str();
191 * LOG(INFO) << format("{} {}", 23, 42);
192 * writeTo(stdout, format("{} {}", 23, 42));
194 * Note that format() will crash the program if the format string is invalid.
195 * Normally, the format string is a fixed string literal specified by the
196 * programmer. Invalid format strings are normally programmer bugs, and should
197 * be caught early on during development. Crashing helps ensure these bugs are
200 * Use formatChecked() if you have a dynamic format string (for example, a user
201 * supplied value). formatChecked() will throw an exception rather than
202 * crashing the program.
204 template <class... Args>
205 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
206 return Formatter<false, Args...>(
207 fmt, std::forward<Args>(args)...);
211 * Like format(), but immediately returns the formatted string instead of an
212 * intermediate format object.
214 template <class... Args>
215 inline std::string sformat(StringPiece fmt, Args&&... args) {
216 return format(fmt, std::forward<Args>(args)...).str();
220 * Create a formatter object from a dynamic format string.
222 * This is identical to format(), but throws an exception if the format string
223 * is invalid, rather than aborting the program. This allows it to be used
224 * with user-specified format strings which are not guaranteed to be well
227 template <class... Args>
228 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
229 Formatter<false, Args...> f(fmt, std::forward<Args>(args)...);
230 f.setCrashOnError(false);
235 * Like formatChecked(), but immediately returns the formatted string instead of
236 * an intermediate format object.
238 template <class... Args>
239 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
240 return formatChecked(fmt, std::forward<Args>(args)...).str();
244 * Create a formatter object that takes one argument (of container type)
245 * and uses that container to get argument values from.
247 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
249 * The following are equivalent:
250 * format("{0[hello]} {0[answer]}", map);
252 * vformat("{hello} {answer}", map);
254 * but the latter is cleaner.
256 template <class Container>
257 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
258 return Formatter<true, Container>(
259 fmt, std::forward<Container>(container));
263 * Like vformat(), but immediately returns the formatted string instead of an
264 * intermediate format object.
266 template <class Container>
267 inline std::string svformat(StringPiece fmt, Container&& container) {
268 return vformat(fmt, std::forward<Container>(container)).str();
272 * Create a formatter object from a dynamic format string.
274 * This is identical to vformat(), but throws an exception if the format string
275 * is invalid, rather than aborting the program. This allows it to be used
276 * with user-specified format strings which are not guaranteed to be well
279 template <class Container>
280 Formatter<true, Container> vformatChecked(StringPiece fmt,
281 Container&& container) {
282 Formatter<true, Container> f(fmt, std::forward<Container>(container));
283 f.setCrashOnError(false);
288 * Like vformatChecked(), but immediately returns the formatted string instead
289 * of an intermediate format object.
291 template <class Container>
292 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
293 return vformatChecked(fmt, std::forward<Container>(container)).str();
297 * Wrap a sequence or associative container so that out-of-range lookups
298 * return a default value rather than throwing an exception.
301 * format("[no_such_key"], defaulted(map, 42)) -> 42
304 template <class Container, class Value> struct DefaultValueWrapper {
305 DefaultValueWrapper(const Container& container, const Value& defaultValue)
306 : container(container),
307 defaultValue(defaultValue) {
310 const Container& container;
311 const Value& defaultValue;
315 template <class Container, class Value>
316 detail::DefaultValueWrapper<Container, Value>
317 defaulted(const Container& c, const Value& v) {
318 return detail::DefaultValueWrapper<Container, Value>(c, v);
322 * Append formatted output to a string.
325 * format(&foo, "{} {}", 42, 23);
327 * Shortcut for toAppend(format(...), &foo);
329 template <class Str, class... Args>
330 typename std::enable_if<IsSomeString<Str>::value>::type
331 format(Str* out, StringPiece fmt, Args&&... args) {
332 format(fmt, std::forward<Args>(args)...).appendTo(*out);
335 template <class Str, class... Args>
336 typename std::enable_if<IsSomeString<Str>::value>::type
337 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
338 formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
342 * Append vformatted output to a string.
344 template <class Str, class Container>
345 typename std::enable_if<IsSomeString<Str>::value>::type
346 vformat(Str* out, StringPiece fmt, Container&& container) {
347 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
350 template <class Str, class Container>
351 typename std::enable_if<IsSomeString<Str>::value>::type
352 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
353 vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
357 * Utilities for all format value specializations.
359 namespace format_value {
362 * Format a string in "val", obeying appropriate alignment, padding, width,
363 * and precision. Treats Align::DEFAULT as Align::LEFT, and
364 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
365 * number-specific formatting.
367 template <class FormatCallback>
368 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
371 * Format a number in "val"; the first prefixLen characters form the prefix
372 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
373 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
374 * arg.precision, as that has a different meaning for numbers (not "maximum
377 template <class FormatCallback>
378 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
383 * Format a Formatter object recursively. Behaves just like
384 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
385 * string if possible.
387 template <class FormatCallback, bool containerMode, class... Args>
388 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
392 } // namespace format_value
395 * Specialize folly::FormatValue for your type.
397 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
398 * guaranteed to stay alive until the FormatValue object is destroyed, so you
399 * may keep a reference (or pointer) to it instead of making a copy.
402 * template <class Callback>
403 * void format(FormatArg& arg, Callback& cb) const;
404 * with the following semantics: format the value using the given argument.
406 * arg is given by non-const reference for convenience -- it won't be reused,
407 * so feel free to modify it in place if necessary. (For example, wrap an
408 * existing conversion but change the default, or remove the "key" when
409 * extracting an element from a container)
411 * Call the callback to append data to the output. You may call the callback
412 * as many times as you'd like (or not at all, if you want to output an
418 #include <folly/Format-inl.h>
420 #pragma GCC diagnostic pop
422 #endif /* FOLLY_FORMAT_H_ */