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"
39 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
40 #pragma GCC diagnostic push
41 #pragma GCC diagnostic ignored "-Wshadow"
45 // forward declarations
46 template <bool containerMode, class... Args> class Formatter;
47 template <class... Args>
48 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
50 Formatter<true, C> vformat(StringPiece fmt, C&& container);
51 template <class T, class Enable=void> class FormatValue;
56 * Note that this class is tricky, as it keeps *references* to its arguments
57 * (and doesn't copy the passed-in format string). Thankfully, you can't use
58 * this directly, you have to use format(...) below.
61 template <bool containerMode, class... Args>
64 friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
66 friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
69 * Append to output. out(StringPiece sp) may be called (more than once)
71 template <class Output>
72 void operator()(Output& out) const;
78 typename std::enable_if<detail::IsSomeString<Str>::value>::type
79 appendTo(Str& str) const {
80 auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
85 * Conversion to string
87 std::string str() const {
94 * Conversion to fbstring
96 fbstring fbstr() const {
103 explicit Formatter(StringPiece str, Args&&... args);
106 Formatter(const Formatter&) = delete;
107 Formatter& operator=(const Formatter&) = delete;
109 // Movable, but the move constructor and assignment operator are private,
110 // for the exclusive use of format() (below). This way, you can't create
111 // a Formatter object, but can handle references to it (for streaming,
112 // conversion to string, etc) -- which is good, as Formatter objects are
113 // dangerous (they hold references, possibly to temporaries)
114 Formatter(Formatter&&) = default;
115 Formatter& operator=(Formatter&&) = default;
117 typedef std::tuple<FormatValue<
118 typename std::decay<Args>::type>...> ValueTuple;
119 static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
121 template <size_t K, class Callback>
122 typename std::enable_if<K == valueCount>::type
123 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
124 arg.error("argument index out of range, max=", i);
127 template <size_t K, class Callback>
128 typename std::enable_if<(K < valueCount)>::type
129 doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
131 std::get<K>(values_).format(arg, cb);
133 doFormatFrom<K+1>(i, arg, cb);
137 template <class Callback>
138 void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
139 return doFormatFrom<0>(i, arg, cb);
147 * Formatter objects can be written to streams.
149 template<bool containerMode, class... Args>
150 std::ostream& operator<<(std::ostream& out,
151 const Formatter<containerMode, Args...>& formatter) {
152 auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
158 * Create a formatter object.
160 * std::string formatted = format("{} {}", 23, 42).str();
161 * LOG(INFO) << format("{} {}", 23, 42);
163 template <class... Args>
164 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
165 return Formatter<false, Args...>(
166 fmt, std::forward<Args>(args)...);
170 * Create a formatter object that takes one argument (of container type)
171 * and uses that container to get argument values from.
173 * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
175 * The following are equivalent:
176 * format("{0[hello]} {0[answer]}", map);
178 * vformat("{hello} {answer}", map);
180 * but the latter is cleaner.
182 template <class Container>
183 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
184 return Formatter<true, Container>(
185 fmt, std::forward<Container>(container));
189 * Append formatted output to a string.
192 * format(&foo, "{} {}", 42, 23);
194 * Shortcut for toAppend(format(...), &foo);
196 template <class Str, class... Args>
197 typename std::enable_if<detail::IsSomeString<Str>::value>::type
198 format(Str* out, StringPiece fmt, Args&&... args) {
199 format(fmt, std::forward<Args>(args)...).appendTo(*out);
203 * Append vformatted output to a string.
205 template <class Str, class Container>
206 typename std::enable_if<detail::IsSomeString<Str>::value>::type
207 vformat(Str* out, StringPiece fmt, Container&& container) {
208 vformat(fmt, std::forward<Container>(container)).appendTo(*out);
212 * Utilities for all format value specializations.
214 namespace format_value {
217 * Format a string in "val", obeying appropriate alignment, padding, width,
218 * and precision. Treats Align::DEFAULT as Align::LEFT, and
219 * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
220 * number-specific formatting.
222 template <class FormatCallback>
223 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
226 * Format a number in "val"; the first prefixLen characters form the prefix
227 * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
228 * is Align::PAD_AFTER_SIGN. Treats Align::DEFAULT as Align::LEFT. Ignores
229 * arg.precision, as that has a different meaning for numbers (not "maximum
232 template <class FormatCallback>
233 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
238 * Format a Formatter object recursively. Behaves just like
239 * formatString(fmt.str(), arg, cb); but avoids creating a temporary
240 * string if possible.
242 template <class FormatCallback, bool containerMode, class... Args>
243 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
247 } // namespace format_value
250 * Specialize folly::FormatValue for your type.
252 * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
253 * guaranteed to stay alive until the FormatValue object is destroyed, so you
254 * may keep a reference (or pointer) to it instead of making a copy.
257 * template <class Callback>
258 * void format(FormatArg& arg, Callback& cb) const;
259 * with the following semantics: format the value using the given argument.
261 * arg is given by non-const reference for convenience -- it won't be reused,
262 * so feel free to modify it in place if necessary. (For example, wrap an
263 * existing conversion but change the default, or remove the "key" when
264 * extracting an element from a container)
266 * Call the callback to append data to the output. You may call the callback
267 * as many times as you'd like (or not at all, if you want to output an
273 #include "folly/Format-inl.h"
275 #pragma GCC diagnostic pop
277 #endif /* FOLLY_FORMAT_H_ */