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_
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/Traits.h"
34 #include "folly/Likely.h"
35 #include "folly/String.h"
36 #include "folly/small_vector.h"
37 #include "folly/FormatArg.h"
41 // forward declarations
42 template <bool containerMode, class... Args> class Formatter;
43 template <class... Args>
44 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
46 Formatter<true, C> vformat(StringPiece fmt, C&& container);
47 template <class T, class Enable=void> class FormatValue;
52 * Note that this class is tricky, as it keeps *references* to its arguments
53 * (and doesn't copy the passed-in format string). Thankfully, you can't use
54 * this directly, you have to use format(...) below.
57 template <bool containerMode, class... Args>
60 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
62 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
65 * Append to output. out(StringPiece sp) may be called (more than once)
67 template <class Output>
68 void operator()(Output& out) const;
74 typename std::enable_if<detail::IsSomeString<Str>::value>::type
75 appendTo(Str& str) const {
76 auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
81 * Conversion to string
83 std::string str() const {
90 * Conversion to fbstring
92 fbstring fbstr() const {
99 explicit Formatter(StringPiece str, Args&&... args);
102 Formatter(const Formatter&) = delete;
103 Formatter& operator=(const Formatter&) = delete;
105 // Movable, but the move constructor and assignment operator are private,
106 // for the exclusive use of format() (below). This way, you can't create
107 // a Formatter object, but can handle references to it (for streaming,
108 // conversion to string, etc) -- which is good, as Formatter objects are
109 // dangerous (they hold references, possibly to temporaries)
110 Formatter(Formatter&&) = default;
111 Formatter& operator=(Formatter&&) = default;
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 std::get<K>(values_).format(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);
143 * Formatter objects can be written to streams.
145 template<bool containerMode, class... Args>
146 std::ostream& operator<<(std::ostream& out,
147 const Formatter<containerMode, Args...>& formatter) {
148 auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
154 * Create a formatter object.
156 * std::string formatted = format("{} {}", 23, 42).str();
157 * LOG(INFO) << format("{} {}", 23, 42);
159 template <class... Args>
160 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
161 return Formatter<false, Args...>(
162 fmt, std::forward<Args>(args)...);
166 * Create a formatter object that takes one argument (of container type)
167 * and uses that container to get argument values from.
169 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
171 * The following are equivalent:
172 * format("{0[hello]} {0[answer]}", map);
174 * vformat("{hello} {answer}", map);
176 * but the latter is cleaner.
178 template <class Container>
179 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
180 return Formatter<true, Container>(
181 fmt, std::forward<Container>(container));
185 * Append formatted output to a string.
188 * format(&foo, "{} {}", 42, 23);
190 * Shortcut for toAppend(format(...), &foo);
192 template <class Str, class... Args>
193 typename std::enable_if<detail::IsSomeString<Str>::value>::type
194 format(Str* out, StringPiece fmt, Args&&... args) {
195 format(fmt, std::forward<Args>(args)...).appendTo(*out);
199 * Append vformatted output to a string.
201 template <class Str, class Container>
202 typename std::enable_if<detail::IsSomeString<Str>::value>::type
203 vformat(Str* out, StringPiece fmt, Container&& container) {
204 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
208 * Utilities for all format value specializations.
210 namespace format_value {
213 * Format a string in "val", obeying appropriate alignment, padding, width,
214 * and precision. Treats Align::DEFAULT as Align::LEFT, and
215 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
216 * number-specific formatting.
218 template <class FormatCallback>
219 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
222 * Format a number in "val"; the first prefixLen characters form the prefix
223 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
224 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
225 * arg.precision, as that has a different meaning for numbers (not "maximum
228 template <class FormatCallback>
229 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
234 * Format a Formatter object recursively. Behaves just like
235 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
236 * string if possible.
238 template <class FormatCallback, bool containerMode, class... Args>
239 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
243 } // namespace format_value
246 * Specialize folly::FormatValue for your type.
248 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
249 * guaranteed to stay alive until the FormatValue object is destroyed, so you
250 * may keep a reference (or pointer) to it instead of making a copy.
253 * template <class Callback>
254 * void format(FormatArg& arg, Callback& cb) const;
255 * with the following semantics: format the value using the given argument.
257 * arg is given by non-const reference for convenience -- it won't be reused,
258 * so feel free to modify it in place if necessary. (For example, wrap an
259 * existing conversion but change the default, or remove the "key" when
260 * extracting an element from a container)
262 * Call the callback to append data to the output. You may call the callback
263 * as many times as you'd like (or not at all, if you want to output an
269 #include "folly/Format-inl.h"
271 #endif /* FOLLY_FORMAT_H_ */