Fix copy/pasta in docs
[folly.git] / folly / docs / Format.md
1 `folly/Format.h`
2 ----------------
3
4 `folly/Format.h` provides a fast, powerful, type-safe, flexible facility
5 for formatting text, using a specification language similar to Python's
6 [str.format](http://docs.python.org/library/string.html#formatstrings).
7 By default, it can format strings, numbers (integral and floating point),
8 and dynamically-typed `folly::dynamic` objects, and can extract values from
9 random-access containers and string-keyed maps.  In many cases, `format` is
10 faster than `sprintf` as well as being fully type-safe.
11
12 To use `format`, you need to be using gcc 4.6 or later.  You'll want to include
13 `folly/Format.h`.
14
15 ### Overview
16 ***
17
18 Here are some code samples to get started:
19
20 ``` Cpp
21 using folly::format;
22 using folly::sformat;
23 using folly::vformat;
24 using folly::svformat;
25
26 // Objects produced by format() can be streamed without creating
27 // an intermediary string; {} yields the next argument using default
28 // formatting.
29 std::cout << format("The answers are {} and {}", 23, 42);
30 // => "The answers are 23 and 42"
31
32 // If you just want the string, though, you're covered.
33 std::string result = sformat("The answers are {} and {}", 23, 42);
34 // => "The answers are 23 and 42"
35
36 // To insert a literal '{' or '}', just double it.
37 std::cout << format("{} {{}} {{{}}}", 23, 42);
38 // => "23 {} {42}"
39
40 // Arguments can be referenced out of order, even multiple times
41 std::cout << format("The answers are {1}, {0}, and {1} again", 23, 42);
42 // => "The answers are 42, 23, and 42 again"
43
44 // It's perfectly fine to not reference all arguments
45 std::cout << format("The only answer is {1}", 23, 42);
46 // => "The only answer is 42"
47
48 // Values can be extracted from indexable containers
49 // (random-access sequences and integral-keyed maps), and also from
50 // string-keyed maps
51 std::vector<int> v {23, 42};
52 std::map<std::string, std::string> m { {"what", "answer"} };
53 std::cout << format("The only {1[what]} is {0[1]}", v, m);
54 // => "The only answer is 42"
55
56 // If you only have one container argument, vformat makes the syntax simpler
57 std::map<std::string, std::string> m { {"what", "answer"}, {"value", "42"} };
58 std::cout << vformat("The only {what} is {value}", m);
59 // => "The only answer is 42"
60 // same as
61 std::cout << format("The only {0[what]} is {0[value]}", m);
62 // => "The only answer is 42"
63 // And if you just want the string,
64 std::string result = svformat("The only {what} is {value}", m);
65 // => "The only answer is 42"
66 std::string result = sformat("The only {0[what]} is {0[value]}", m);
67 // => "The only answer is 42"
68
69 // {} works for vformat too
70 std::vector<int> v {42, 23};
71 std::cout << vformat("{} {}", v);
72 // => "42 23"
73
74 // format and vformat work with pairs and tuples
75 std::tuple<int, std::string, int> t {42, "hello", 23};
76 std::cout << vformat("{0} {2} {1}", t);
77 // => "42 23 hello"
78
79 // Format supports width, alignment, arbitrary fill, and various
80 // format specifiers, with meanings similar to printf
81 // "X<10": fill with 'X', left-align ('<'), width 10
82 std::cout << format("{:X<10} {}", "hello", "world");
83 // => "helloXXXXX world"
84
85 // Format supports printf-style format specifiers
86 std::cout << format("{0:05d} decimal = {0:04x} hex", 42);
87 // => "00042 decimal = 002a hex"
88
89 // Formatter objects may be written to a string using folly::to or
90 // folly::toAppend (see folly/Conv.h), or by calling their appendTo(),
91 // str(), and fbstr() methods
92 std::string s = format("The only answer is {}", 42).str();
93 std::cout << s;
94 // => "The only answer is 42"
95 ```
96
97
98 ### Format string syntax
99 ***
100
101 Format string (`format`):
102 `"{" [arg_index] ["[" key "]"] [":" format_spec] "}"`
103
104 - `arg_index`: index of argument to format; default = next argument.  Note
105   that a format string may have either default argument indexes or
106   non-default argument indexes, but not both (to avoid confusion).
107 - `key`: if the argument is a container (C-style array or pointer,
108   `std::array`, vector, deque, map), you may use this
109   to select the element to format; works with random-access sequences and
110   integer- and string-keyed maps.  Multiple level keys work as well, with
111   components separated with "."; for example, given
112   `map<string, map<string, string>> m`, `{[foo.bar]}` selects
113   `m["foo"]["bar"]`.
114 - `format_spec`: format specification, see below
115
116 Format string (`vformat`):
117 `"{" [ key ] [":" format_spec] "}"`
118
119 - `key`: select the argument to format from the container argument;
120   works with random-access sequences and integer- and string-keyed maps.
121   Multiple level keys work as well, with components separated with "."; for
122   example, given `map<string, map<string, string>> m`, `{foo.bar}` selects
123   `m["foo"]["bar"]`.
124 - `format_spec`: format specification, see below
125
126 Format specification:
127 `[[fill] align] [sign] ["#"] ["0"] [width] [","] ["." precision] ["."] [type]`
128
129 - `fill` (may only be specified if `align` is also specified): pad with this
130   character ('` `' (space) or '`0`' (zero) might be useful; space is default)
131 - `align`: one of '`<`', '`>`', '`=`', '`^`':
132     - '`<`': left-align (default for most objects)
133     - '`>`': right-align (default for numbers)
134     - '`=`': pad after sign, but before significant digits; used to print
135             `-0000120`; only valid for numbers
136     - '`^`': center
137 - `sign`: one of '`+`', '`-`', ' ' (space) (only valid for numbers)
138     - '`+`': output '`+`' if positive or zero, '`-`' if negative
139     - '`-`': output '`-`' if negative, nothing otherwise (default)
140     - '` `' (space): output '` `' (space) if positive or zero, '`-`' if negative
141 - '`#`': output base prefix (`0` for octal, `0b` or `0B` for binary, `0x` or
142   `0X` for hexadecimal; only valid for integers)
143 - '`0`': 0-pad after sign, same as specifying "`0=`" as the `fill` and
144   `align` parameters (only valid for numbers)
145 - `width`: minimum field width
146 - '`,`' (comma): output comma as thousands' separator (only valid for integers,
147   and only for decimal output)
148 - `precision` (not allowed for integers):
149     - for floating point values, number of digits after decimal point ('`f`' or
150       '`F`' presentation) or number of significant digits ('`g`' or '`G`')
151     - for others, maximum field size (truncate subsequent characters)
152 - '`.`' (when used after precision or in lieu of precison): Forces a trailing
153   decimal point to make it clear this is a floating point value.
154 - `type`: presentation format, see below
155
156 Presentation formats:
157
158 - Strings (`folly::StringPiece`, `std::string`, `folly::fbstring`,
159   `const char*`):
160     - '`s`' (default)
161 - Integers:
162     - '`b`': output in binary (base 2) ("`0b`" prefix if '`#`' specified)
163     - '`B`': output in binary (base 2) ("`0B`" prefix if '`#`' specified)
164     - '`c`': output as a character (cast to `char`)
165     - '`d`': output in decimal (base 10) (default)
166     - '`o`': output in octal (base 8)
167     - '`O`': output in octal (base 8) (same as '`o`')
168     - '`x`': output in hexadecimal (base 16) (lower-case digits above 9)
169     - '`X`': output in hexadecimal (base 16) (upper-case digits above 9)
170     - '`n`': locale-aware output (currently same as '`d`')
171 - `bool`:
172     - default: output "`true`" or "`false`" as strings
173     - integer presentations allowed as well
174 - `char`:
175     - same as other integers, but default is '`c`' instead of '`d`'
176 - Floating point (`float`, `double`; `long double` is not implemented):
177     - '`e`': scientific notation using '`e`' as exponent character
178     - '`E`': scientific notation using '`E`' as exponent character
179     - '`f`': fixed point
180     - '`F`': fixed point (same as '`f`')
181     - '`g`': general; use either '`f`' or '`e`' depending on magnitude (default)
182     - '`G`': general; use either '`f`' or '`E`' depending on magnitude
183     - '`n`': locale-aware version of '`g`' (currently same as '`g`')
184     - '`%`': percentage: multiply by 100 then display as '`f`'
185
186
187 ### Extension
188 ***
189
190 You can extend `format` for your own class by providing a specialization for
191 `folly::FormatValue`.  See `folly/Format.h` and `folly/FormatArg.h` for
192 details, and the existing specialization for `folly::dynamic` in
193 `folly/dynamic-inl.h` for an implementation example.