2 * Copyright 2015 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 <folly/FBVector.h>
30 #include <folly/Conv.h>
31 #include <folly/Range.h>
32 #include <folly/Traits.h>
33 #include <folly/Likely.h>
34 #include <folly/String.h>
35 #include <folly/small_vector.h>
36 #include <folly/FormatArg.h>
38 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
39 #pragma GCC diagnostic push
40 #pragma GCC diagnostic ignored "-Wshadow"
44 // forward declarations
45 template <bool containerMode, class... Args> class Formatter;
46 template <class... Args>
47 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
49 Formatter<true, C> vformat(StringPiece fmt, C&& container);
50 template <class T, class Enable=void> class FormatValue;
52 // meta-attribute to identify formatters in this sea of template weirdness
54 class FormatterTag {};
60 * Note that this class is tricky, as it keeps *references* to its arguments
61 * (and doesn't copy the passed-in format string). Thankfully, you can't use
62 * this directly, you have to use format(...) below.
65 /* BaseFormatter class. Currently, the only behavior that can be
66 * overridden is the actual formatting of positional parameters in
67 * `doFormatArg`. The Formatter class provides the default implementation.
69 template <class Derived, bool containerMode, class... Args>
73 * Append to output. out(StringPiece sp) may be called (more than once)
75 template <class Output>
76 void operator()(Output& out) const;
82 typename std::enable_if<IsSomeString<Str>::value>::type
83 appendTo(Str& str) const {
84 auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
89 * Conversion to string
91 std::string str() const {
98 * Conversion to fbstring
100 fbstring fbstr() const {
107 * metadata to identify generated children of BaseFormatter
109 typedef detail::FormatterTag IsFormatter;
110 typedef BaseFormatter BaseType;
113 typedef std::tuple<FormatValue<
114 typename std::decay<Args>::type>...> ValueTuple;
115 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
117 template <size_t K, class Callback>
118 typename std::enable_if<K == valueCount>::type
119 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
120 arg.error("argument index out of range, max=", i);
123 template <size_t K, class Callback>
124 typename std::enable_if<(K < valueCount)>::type
125 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
127 static_cast<const Derived*>(this)->template doFormatArg<K>(arg, cb);
129 doFormatFrom<K+1>(i, arg, cb);
133 template <class Callback>
134 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
135 return doFormatFrom<0>(i, arg, cb);
141 explicit BaseFormatter(StringPiece str, Args&&... args);
144 BaseFormatter(const BaseFormatter&) = delete;
145 BaseFormatter& operator=(const BaseFormatter&) = delete;
147 // Movable, but the move constructor and assignment operator are private,
148 // for the exclusive use of format() (below). This way, you can't create
149 // a Formatter object, but can handle references to it (for streaming,
150 // conversion to string, etc) -- which is good, as Formatter objects are
151 // dangerous (they hold references, possibly to temporaries)
152 BaseFormatter(BaseFormatter&&) = default;
153 BaseFormatter& operator=(BaseFormatter&&) = default;
158 template <bool containerMode, class... Args>
159 class Formatter : public BaseFormatter<Formatter<containerMode, Args...>,
163 explicit Formatter(StringPiece& str, Args&&... args)
164 : BaseFormatter<Formatter<containerMode, Args...>,
166 Args...>(str, std::forward<Args>(args)...) {}
168 template <size_t K, class Callback>
169 void doFormatArg(FormatArg& arg, Callback& cb) const {
170 std::get<K>(this->values_).format(arg, cb);
173 friend class BaseFormatter<Formatter<containerMode, Args...>,
177 template <class... A>
178 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
180 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
184 * Formatter objects can be written to streams.
186 template<bool containerMode, class... Args>
187 std::ostream& operator<<(std::ostream& out,
188 const Formatter<containerMode, Args...>& formatter) {
189 auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
195 * Formatter objects can be written to stdio FILEs.
197 template <class Derived, bool containerMode, class... Args>
198 void writeTo(FILE* fp,
199 const BaseFormatter<Derived, containerMode, Args...>& formatter);
202 * Create a formatter object.
204 * std::string formatted = format("{} {}", 23, 42).str();
205 * LOG(INFO) << format("{} {}", 23, 42);
206 * writeTo(stdout, format("{} {}", 23, 42));
208 template <class... Args>
209 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
210 return Formatter<false, Args...>(
211 fmt, std::forward<Args>(args)...);
215 * Like format(), but immediately returns the formatted string instead of an
216 * intermediate format object.
218 template <class... Args>
219 inline std::string sformat(StringPiece fmt, Args&&... args) {
220 return format(fmt, std::forward<Args>(args)...).str();
224 * Create a formatter object that takes one argument (of container type)
225 * and uses that container to get argument values from.
227 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
229 * The following are equivalent:
230 * format("{0[hello]} {0[answer]}", map);
232 * vformat("{hello} {answer}", map);
234 * but the latter is cleaner.
236 template <class Container>
237 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
238 return Formatter<true, Container>(
239 fmt, std::forward<Container>(container));
243 * Like vformat(), but immediately returns the formatted string instead of an
244 * intermediate format object.
246 template <class Container>
247 inline std::string svformat(StringPiece fmt, Container&& container) {
248 return vformat(fmt, std::forward<Container>(container)).str();
252 * Wrap a sequence or associative container so that out-of-range lookups
253 * return a default value rather than throwing an exception.
256 * format("[no_such_key"], defaulted(map, 42)) -> 42
259 template <class Container, class Value> struct DefaultValueWrapper {
260 DefaultValueWrapper(const Container& container, const Value& defaultValue)
261 : container(container),
262 defaultValue(defaultValue) {
265 const Container& container;
266 const Value& defaultValue;
270 template <class Container, class Value>
271 detail::DefaultValueWrapper<Container, Value>
272 defaulted(const Container& c, const Value& v) {
273 return detail::DefaultValueWrapper<Container, Value>(c, v);
277 * Append formatted output to a string.
280 * format(&foo, "{} {}", 42, 23);
282 * Shortcut for toAppend(format(...), &foo);
284 template <class Str, class... Args>
285 typename std::enable_if<IsSomeString<Str>::value>::type
286 format(Str* out, StringPiece fmt, Args&&... args) {
287 format(fmt, std::forward<Args>(args)...).appendTo(*out);
291 * Append vformatted output to a string.
293 template <class Str, class Container>
294 typename std::enable_if<IsSomeString<Str>::value>::type
295 vformat(Str* out, StringPiece fmt, Container&& container) {
296 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
300 * Utilities for all format value specializations.
302 namespace format_value {
305 * Format a string in "val", obeying appropriate alignment, padding, width,
306 * and precision. Treats Align::DEFAULT as Align::LEFT, and
307 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
308 * number-specific formatting.
310 template <class FormatCallback>
311 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
314 * Format a number in "val"; the first prefixLen characters form the prefix
315 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
316 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
317 * arg.precision, as that has a different meaning for numbers (not "maximum
320 template <class FormatCallback>
321 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
326 * Format a Formatter object recursively. Behaves just like
327 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
328 * string if possible.
330 template <class FormatCallback,
334 void formatFormatter(
335 const BaseFormatter<Derived, containerMode, Args...>& formatter,
339 } // namespace format_value
342 * Specialize folly::FormatValue for your type.
344 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
345 * guaranteed to stay alive until the FormatValue object is destroyed, so you
346 * may keep a reference (or pointer) to it instead of making a copy.
349 * template <class Callback>
350 * void format(FormatArg& arg, Callback& cb) const;
351 * with the following semantics: format the value using the given argument.
353 * arg is given by non-const reference for convenience -- it won't be reused,
354 * so feel free to modify it in place if necessary. (For example, wrap an
355 * existing conversion but change the default, or remove the "key" when
356 * extracting an element from a container)
358 * Call the callback to append data to the output. You may call the callback
359 * as many times as you'd like (or not at all, if you want to output an
365 template <class T, class Enable = void>
366 struct IsFormatter : public std::false_type {};
371 typename std::enable_if<
372 std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
373 type> : public std::true_type {};
376 // Deprecated API. formatChecked() et. al. now behave identically to their
377 // non-Checked counterparts.
378 template <class... Args>
379 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
380 return format(fmt, std::forward<Args>(args)...);
382 template <class... Args>
383 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
384 return formatChecked(fmt, std::forward<Args>(args)...).str();
386 template <class Container>
387 Formatter<true, Container> vformatChecked(StringPiece fmt,
388 Container&& container) {
389 return vformat(fmt, std::forward<Container>(container));
391 template <class Container>
392 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
393 return vformatChecked(fmt, std::forward<Container>(container)).str();
395 template <class Str, class... Args>
396 typename std::enable_if<IsSomeString<Str>::value>::type
397 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
398 formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
400 template <class Str, class Container>
401 typename std::enable_if<IsSomeString<Str>::value>::type
402 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
403 vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
408 #include <folly/Format-inl.h>
410 #pragma GCC diagnostic pop
412 #endif /* FOLLY_FORMAT_H_ */