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.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 void handleFormatStrError() const FOLLY_NORETURN;
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 * Create a formatter object from a dynamic format string.
213 * This is identical to format(), but throws an exception if the format string
214 * is invalid, rather than aborting the program. This allows it to be used
215 * with user-specified format strings which are not guaranteed to be well
218 template <class... Args>
219 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
220 Formatter<false, Args...> f(fmt, std::forward<Args>(args)...);
221 f.setCrashOnError(false);
226 * Create a formatter object that takes one argument (of container type)
227 * and uses that container to get argument values from.
229 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
231 * The following are equivalent:
232 * format("{0[hello]} {0[answer]}", map);
234 * vformat("{hello} {answer}", map);
236 * but the latter is cleaner.
238 template <class Container>
239 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
240 return Formatter<true, Container>(
241 fmt, std::forward<Container>(container));
245 * Create a formatter object from a dynamic format string.
247 * This is identical to vformat(), but throws an exception if the format string
248 * is invalid, rather than aborting the program. This allows it to be used
249 * with user-specified format strings which are not guaranteed to be well
252 template <class Container>
253 Formatter<true, Container> vformatChecked(StringPiece fmt,
254 Container&& container) {
255 Formatter<true, Container> f(fmt, std::forward<Container>(container));
256 f.setCrashOnError(false);
261 * Append formatted output to a string.
264 * format(&foo, "{} {}", 42, 23);
266 * Shortcut for toAppend(format(...), &foo);
268 template <class Str, class... Args>
269 typename std::enable_if<IsSomeString<Str>::value>::type
270 format(Str* out, StringPiece fmt, Args&&... args) {
271 format(fmt, std::forward<Args>(args)...).appendTo(*out);
274 template <class Str, class... Args>
275 typename std::enable_if<IsSomeString<Str>::value>::type
276 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
277 formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
281 * Append vformatted output to a string.
283 template <class Str, class Container>
284 typename std::enable_if<IsSomeString<Str>::value>::type
285 vformat(Str* out, StringPiece fmt, Container&& container) {
286 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
289 template <class Str, class Container>
290 typename std::enable_if<IsSomeString<Str>::value>::type
291 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
292 vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
296 * Utilities for all format value specializations.
298 namespace format_value {
301 * Format a string in "val", obeying appropriate alignment, padding, width,
302 * and precision. Treats Align::DEFAULT as Align::LEFT, and
303 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
304 * number-specific formatting.
306 template <class FormatCallback>
307 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
310 * Format a number in "val"; the first prefixLen characters form the prefix
311 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
312 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
313 * arg.precision, as that has a different meaning for numbers (not "maximum
316 template <class FormatCallback>
317 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
322 * Format a Formatter object recursively. Behaves just like
323 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
324 * string if possible.
326 template <class FormatCallback, bool containerMode, class... Args>
327 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
331 } // namespace format_value
334 * Specialize folly::FormatValue for your type.
336 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
337 * guaranteed to stay alive until the FormatValue object is destroyed, so you
338 * may keep a reference (or pointer) to it instead of making a copy.
341 * template <class Callback>
342 * void format(FormatArg& arg, Callback& cb) const;
343 * with the following semantics: format the value using the given argument.
345 * arg is given by non-const reference for convenience -- it won't be reused,
346 * so feel free to modify it in place if necessary. (For example, wrap an
347 * existing conversion but change the default, or remove the "key" when
348 * extracting an element from a container)
350 * Call the callback to append data to the output. You may call the callback
351 * as many times as you'd like (or not at all, if you want to output an
357 #include "folly/Format-inl.h"
359 #pragma GCC diagnostic pop
361 #endif /* FOLLY_FORMAT_H_ */