2 * Copyright 2012 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_
22 #include <type_traits>
26 #include <unordered_map>
28 #include <double-conversion.h>
30 #include "folly/FBVector.h"
31 #include "folly/Conv.h"
32 #include "folly/Range.h"
33 #include "folly/Likely.h"
34 #include "folly/String.h"
35 #include "folly/small_vector.h"
36 #include "folly/FormatArg.h"
40 // forward declarations
41 template <bool containerMode, class... Args> class Formatter;
42 template <class... Args>
43 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
45 Formatter<true, C> vformat(StringPiece fmt, C&& container);
46 template <class T, class Enable=void> class FormatValue;
51 * Note that this class is tricky, as it keeps *references* to its arguments
52 * (and doesn't copy the passed-in format string). Thankfully, you can't use
53 * this directly, you have to use format(...) below.
56 template <bool containerMode, class... Args>
59 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
61 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
64 * Append to output. out(StringPiece sp) may be called (more than once)
66 template <class Output>
67 void operator()(Output& out) const;
73 typename std::enable_if<detail::IsSomeString<Str>::value>::type
74 appendTo(Str& str) const {
75 auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
80 * Conversion to string
82 std::string str() const {
89 * Conversion to fbstring
91 fbstring fbstr() const {
98 explicit Formatter(StringPiece str, Args&&... args);
101 Formatter(const Formatter&) = delete;
102 Formatter& operator=(const Formatter&) = delete;
104 // Movable, but the move constructor and assignment operator are private,
105 // for the exclusive use of format() (below). This way, you can't create
106 // a Formatter object, but can handle references to it (for streaming,
107 // conversion to string, etc) -- which is good, as Formatter objects are
108 // dangerous (they hold references, possibly to temporaries)
109 Formatter(Formatter&&) = default;
110 Formatter& operator=(Formatter&&) = default;
112 typedef std::tuple<FormatValue<
113 typename std::decay<Args>::type>...> ValueTuple;
114 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
116 template <size_t K, class Callback>
117 typename std::enable_if<K == valueCount>::type
118 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
119 arg.error("argument index out of range, max=", i);
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 {
126 std::get<K>(values_).format(arg, cb);
128 doFormatFrom<K+1>(i, arg, cb);
132 template <class Callback>
133 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
134 return doFormatFrom<0>(i, arg, cb);
142 * Formatter objects can be written to streams.
144 template<bool containerMode, class... Args>
145 std::ostream& operator<<(std::ostream& out,
146 const Formatter<containerMode, Args...>& formatter) {
147 auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
153 * Create a formatter object.
155 * std::string formatted = format("{} {}", 23, 42).str();
156 * LOG(INFO) << format("{} {}", 23, 42);
158 template <class... Args>
159 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
160 return Formatter<false, Args...>(
161 fmt, std::forward<Args>(args)...);
165 * Create a formatter object that takes one argument (of container type)
166 * and uses that container to get argument values from.
168 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
170 * The following are equivalent:
171 * format("{0[hello]} {0[answer]}", map);
173 * vformat("{hello} {answer}", map);
175 * but the latter is cleaner.
177 template <class Container>
178 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
179 return Formatter<true, Container>(
180 fmt, std::forward<Container>(container));
184 * Append formatted output to a string.
187 * format(&foo, "{} {}", 42, 23);
189 * Shortcut for toAppend(format(...), &foo);
191 template <class Str, class... Args>
192 typename std::enable_if<detail::IsSomeString<Str>::value>::type
193 format(Str* out, StringPiece fmt, Args&&... args) {
194 format(fmt, std::forward<Args>(args)...).appendTo(*out);
198 * Append vformatted output to a string.
200 template <class Str, class Container>
201 typename std::enable_if<detail::IsSomeString<Str>::value>::type
202 vformat(Str* out, StringPiece fmt, Container&& container) {
203 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
207 * Utilities for all format value specializations.
209 namespace format_value {
212 * Format a string in "val", obeying appropriate alignment, padding, width,
213 * and precision. Treats Align::DEFAULT as Align::LEFT, and
214 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
215 * number-specific formatting.
217 template <class FormatCallback>
218 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
221 * Format a number in "val"; the first prefixLen characters form the prefix
222 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
223 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
224 * arg.precision, as that has a different meaning for numbers (not "maximum
227 template <class FormatCallback>
228 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
233 * Format a Formatter object recursively. Behaves just like
234 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
235 * string if possible.
237 template <class FormatCallback, bool containerMode, class... Args>
238 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
242 } // namespace format_value
245 * Specialize folly::FormatValue for your type.
247 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
248 * guaranteed to stay alive until the FormatValue object is destroyed, so you
249 * may keep a reference (or pointer) to it instead of making a copy.
252 * template <class Callback>
253 * void format(FormatArg& arg, Callback& cb) const;
254 * with the following semantics: format the value using the given argument.
256 * arg is given by non-const reference for convenience -- it won't be reused,
257 * so feel free to modify it in place if necessary. (For example, wrap an
258 * existing conversion but change the default, or remove the "key" when
259 * extracting an element from a container)
261 * Call the callback to append data to the output. You may call the callback
262 * as many times as you'd like (or not at all, if you want to output an
268 #include "folly/Format-inl.h"
270 #endif /* FOLLY_FORMAT_H_ */