2 * Copyright 2013 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>
65 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
67 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
70 * Append to output. out(StringPiece sp) may be called (more than once)
72 template <class Output>
73 void operator()(Output& out) const;
79 typename std::enable_if<detail::IsSomeString<Str>::value>::type
80 appendTo(Str& str) const {
81 auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
86 * Conversion to string
88 std::string str() const {
95 * Conversion to fbstring
97 fbstring fbstr() const {
104 explicit Formatter(StringPiece str, Args&&... args);
107 Formatter(const Formatter&) = delete;
108 Formatter& operator=(const Formatter&) = delete;
110 // Movable, but the move constructor and assignment operator are private,
111 // for the exclusive use of format() (below). This way, you can't create
112 // a Formatter object, but can handle references to it (for streaming,
113 // conversion to string, etc) -- which is good, as Formatter objects are
114 // dangerous (they hold references, possibly to temporaries)
115 Formatter(Formatter&&) = default;
116 Formatter& operator=(Formatter&&) = default;
118 typedef std::tuple<FormatValue<
119 typename std::decay<Args>::type>...> ValueTuple;
120 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
122 template <size_t K, class Callback>
123 typename std::enable_if<K == valueCount>::type
124 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
125 LOG(FATAL) << arg.errorStr("argument index out of range, max=", i);
128 template <size_t K, class Callback>
129 typename std::enable_if<(K < valueCount)>::type
130 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
132 std::get<K>(values_).format(arg, cb);
134 doFormatFrom<K+1>(i, arg, cb);
138 template <class Callback>
139 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
140 return doFormatFrom<0>(i, arg, cb);
148 * Formatter objects can be written to streams.
150 template<bool containerMode, class... Args>
151 std::ostream& operator<<(std::ostream& out,
152 const Formatter<containerMode, Args...>& formatter) {
153 auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
159 * Formatter objects can be written to stdio FILEs.
161 template<bool containerMode, class... Args>
162 void writeTo(FILE* fp, const Formatter<containerMode, Args...>& formatter);
165 * Create a formatter object.
167 * std::string formatted = format("{} {}", 23, 42).str();
168 * LOG(INFO) << format("{} {}", 23, 42);
169 * writeTo(stdout, format("{} {}", 23, 42));
171 template <class... Args>
172 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
173 return Formatter<false, Args...>(
174 fmt, std::forward<Args>(args)...);
178 * Create a formatter object that takes one argument (of container type)
179 * and uses that container to get argument values from.
181 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
183 * The following are equivalent:
184 * format("{0[hello]} {0[answer]}", map);
186 * vformat("{hello} {answer}", map);
188 * but the latter is cleaner.
190 template <class Container>
191 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
192 return Formatter<true, Container>(
193 fmt, std::forward<Container>(container));
197 * Append formatted output to a string.
200 * format(&foo, "{} {}", 42, 23);
202 * Shortcut for toAppend(format(...), &foo);
204 template <class Str, class... Args>
205 typename std::enable_if<detail::IsSomeString<Str>::value>::type
206 format(Str* out, StringPiece fmt, Args&&... args) {
207 format(fmt, std::forward<Args>(args)...).appendTo(*out);
211 * Append vformatted output to a string.
213 template <class Str, class Container>
214 typename std::enable_if<detail::IsSomeString<Str>::value>::type
215 vformat(Str* out, StringPiece fmt, Container&& container) {
216 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
220 * Utilities for all format value specializations.
222 namespace format_value {
225 * Format a string in "val", obeying appropriate alignment, padding, width,
226 * and precision. Treats Align::DEFAULT as Align::LEFT, and
227 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
228 * number-specific formatting.
230 template <class FormatCallback>
231 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
234 * Format a number in "val"; the first prefixLen characters form the prefix
235 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
236 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
237 * arg.precision, as that has a different meaning for numbers (not "maximum
240 template <class FormatCallback>
241 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
246 * Format a Formatter object recursively. Behaves just like
247 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
248 * string if possible.
250 template <class FormatCallback, bool containerMode, class... Args>
251 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
255 } // namespace format_value
258 * Specialize folly::FormatValue for your type.
260 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
261 * guaranteed to stay alive until the FormatValue object is destroyed, so you
262 * may keep a reference (or pointer) to it instead of making a copy.
265 * template <class Callback>
266 * void format(FormatArg& arg, Callback& cb) const;
267 * with the following semantics: format the value using the given argument.
269 * arg is given by non-const reference for convenience -- it won't be reused,
270 * so feel free to modify it in place if necessary. (For example, wrap an
271 * existing conversion but change the default, or remove the "key" when
272 * extracting an element from a container)
274 * Call the callback to append data to the output. You may call the callback
275 * as many times as you'd like (or not at all, if you want to output an
281 #include "folly/Format-inl.h"
283 #pragma GCC diagnostic pop
285 #endif /* FOLLY_FORMAT_H_ */