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 <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 * 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
85 appendTo(Str& str) const {
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<FormatValue<
116 typename std::decay<Args>::type>...> ValueTuple;
117 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
119 template <size_t K, class Callback>
120 typename std::enable_if<K == valueCount>::type
121 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
122 arg.error("argument index out of range, max=", i);
125 template <size_t K, class Callback>
126 typename std::enable_if<(K < valueCount)>::type
127 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
129 static_cast<const Derived*>(this)->template doFormatArg<K>(arg, cb);
131 doFormatFrom<K+1>(i, arg, cb);
135 template <class Callback>
136 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
137 return doFormatFrom<0>(i, arg, cb);
143 explicit BaseFormatter(StringPiece str, Args&&... args);
146 BaseFormatter(const BaseFormatter&) = delete;
147 BaseFormatter& operator=(const BaseFormatter&) = delete;
149 // Movable, but the move constructor and assignment operator are private,
150 // for the exclusive use of format() (below). This way, you can't create
151 // a Formatter object, but can handle references to it (for streaming,
152 // conversion to string, etc) -- which is good, as Formatter objects are
153 // dangerous (they hold references, possibly to temporaries)
154 BaseFormatter(BaseFormatter&&) = default;
155 BaseFormatter& operator=(BaseFormatter&&) = default;
160 template <bool containerMode, class... Args>
161 class Formatter : public BaseFormatter<Formatter<containerMode, Args...>,
165 explicit Formatter(StringPiece& str, Args&&... args)
166 : BaseFormatter<Formatter<containerMode, Args...>,
168 Args...>(str, std::forward<Args>(args)...) {}
170 template <size_t K, class Callback>
171 void doFormatArg(FormatArg& arg, Callback& cb) const {
172 std::get<K>(this->values_).format(arg, cb);
175 friend class BaseFormatter<Formatter<containerMode, Args...>,
179 template <class... A>
180 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
182 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
186 * Formatter objects can be written to streams.
188 template<bool containerMode, class... Args>
189 std::ostream& operator<<(std::ostream& out,
190 const Formatter<containerMode, Args...>& formatter) {
191 auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
197 * Formatter objects can be written to stdio FILEs.
199 template <class Derived, bool containerMode, class... Args>
200 void writeTo(FILE* fp,
201 const BaseFormatter<Derived, containerMode, Args...>& formatter);
204 * Create a formatter object.
206 * std::string formatted = format("{} {}", 23, 42).str();
207 * LOG(INFO) << format("{} {}", 23, 42);
208 * writeTo(stdout, format("{} {}", 23, 42));
210 template <class... Args>
211 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
212 return Formatter<false, Args...>(
213 fmt, std::forward<Args>(args)...);
217 * Like format(), but immediately returns the formatted string instead of an
218 * intermediate format object.
220 template <class... Args>
221 inline std::string sformat(StringPiece fmt, Args&&... args) {
222 return format(fmt, std::forward<Args>(args)...).str();
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 * Like vformat(), but immediately returns the formatted string instead of an
246 * intermediate format object.
248 template <class Container>
249 inline std::string svformat(StringPiece fmt, Container&& container) {
250 return vformat(fmt, std::forward<Container>(container)).str();
254 * Wrap a sequence or associative container so that out-of-range lookups
255 * return a default value rather than throwing an exception.
258 * format("[no_such_key"], defaulted(map, 42)) -> 42
261 template <class Container, class Value> struct DefaultValueWrapper {
262 DefaultValueWrapper(const Container& container, const Value& defaultValue)
263 : container(container),
264 defaultValue(defaultValue) {
267 const Container& container;
268 const Value& defaultValue;
272 template <class Container, class Value>
273 detail::DefaultValueWrapper<Container, Value>
274 defaulted(const Container& c, const Value& v) {
275 return detail::DefaultValueWrapper<Container, Value>(c, v);
279 * Append formatted output to a string.
282 * format(&foo, "{} {}", 42, 23);
284 * Shortcut for toAppend(format(...), &foo);
286 template <class Str, class... Args>
287 typename std::enable_if<IsSomeString<Str>::value>::type
288 format(Str* out, StringPiece fmt, Args&&... args) {
289 format(fmt, std::forward<Args>(args)...).appendTo(*out);
293 * Append vformatted output to a string.
295 template <class Str, class Container>
296 typename std::enable_if<IsSomeString<Str>::value>::type
297 vformat(Str* out, StringPiece fmt, Container&& container) {
298 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
302 * Utilities for all format value specializations.
304 namespace format_value {
307 * Format a string in "val", obeying appropriate alignment, padding, width,
308 * and precision. Treats Align::DEFAULT as Align::LEFT, and
309 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
310 * number-specific formatting.
312 template <class FormatCallback>
313 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
316 * Format a number in "val"; the first prefixLen characters form the prefix
317 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
318 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
319 * arg.precision, as that has a different meaning for numbers (not "maximum
322 template <class FormatCallback>
323 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
328 * Format a Formatter object recursively. Behaves just like
329 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
330 * string if possible.
332 template <class FormatCallback,
336 void formatFormatter(
337 const BaseFormatter<Derived, containerMode, Args...>& formatter,
341 } // namespace format_value
344 * Specialize folly::FormatValue for your type.
346 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
347 * guaranteed to stay alive until the FormatValue object is destroyed, so you
348 * may keep a reference (or pointer) to it instead of making a copy.
351 * template <class Callback>
352 * void format(FormatArg& arg, Callback& cb) const;
353 * with the following semantics: format the value using the given argument.
355 * arg is given by non-const reference for convenience -- it won't be reused,
356 * so feel free to modify it in place if necessary. (For example, wrap an
357 * existing conversion but change the default, or remove the "key" when
358 * extracting an element from a container)
360 * Call the callback to append data to the output. You may call the callback
361 * as many times as you'd like (or not at all, if you want to output an
367 template <class T, class Enable = void>
368 struct IsFormatter : public std::false_type {};
373 typename std::enable_if<
374 std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
375 type> : public std::true_type {};
378 // Deprecated API. formatChecked() et. al. now behave identically to their
379 // non-Checked counterparts.
380 template <class... Args>
381 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
382 return format(fmt, std::forward<Args>(args)...);
384 template <class... Args>
385 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
386 return formatChecked(fmt, std::forward<Args>(args)...).str();
388 template <class Container>
389 Formatter<true, Container> vformatChecked(StringPiece fmt,
390 Container&& container) {
391 return vformat(fmt, std::forward<Container>(container));
393 template <class Container>
394 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
395 return vformatChecked(fmt, std::forward<Container>(container)).str();
397 template <class Str, class... Args>
398 typename std::enable_if<IsSomeString<Str>::value>::type
399 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
400 formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
402 template <class Str, class Container>
403 typename std::enable_if<IsSomeString<Str>::value>::type
404 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
405 vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
410 #include <folly/Format-inl.h>
412 #pragma GCC diagnostic pop
414 #endif /* FOLLY_FORMAT_H_ */