Re-work the OpenSSL portability header to be a portability header
[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 // Field width may be a runtime value rather than part of the format string
86 int x = 6;
87 std::cout << format("{:-^*}", x, "hi");
88 // => "--hi--"
89
90 // Explicit arguments work with dynamic field width, as long as indexes are
91 // given for both the value and the field width.
92 std::cout << format("{2:+^*0}",
93 9, "unused", 456); // => "+++456+++"
94
95 // Format supports printf-style format specifiers
96 std::cout << format("{0:05d} decimal = {0:04x} hex", 42);
97 // => "00042 decimal = 002a hex"
98
99 // Formatter objects may be written to a string using folly::to or
100 // folly::toAppend (see folly/Conv.h), or by calling their appendTo(),
101 // str(), and fbstr() methods
102 std::string s = format("The only answer is {}", 42).str();
103 std::cout << s;
104 // => "The only answer is 42"
105 ```
106
107
108 ### Format string syntax
109 ***
110
111 Format string (`format`):
112 `"{" [arg_index] ["[" key "]"] [":" format_spec] "}"`
113
114 - `arg_index`: index of argument to format; default = next argument.  Note
115   that a format string may have either default argument indexes or
116   non-default argument indexes, but not both (to avoid confusion).
117 - `key`: if the argument is a container (C-style array or pointer,
118   `std::array`, vector, deque, map), you may use this
119   to select the element to format; works with random-access sequences and
120   integer- and string-keyed maps.  Multiple level keys work as well, with
121   components separated with "."; for example, given
122   `map<string, map<string, string>> m`, `{[foo.bar]}` selects
123   `m["foo"]["bar"]`.
124 - `format_spec`: format specification, see below
125
126 Format string (`vformat`):
127 `"{" [ key ] [":" format_spec] "}"`
128
129 - `key`: select the argument to format from the container argument;
130   works with random-access sequences and integer- and string-keyed maps.
131   Multiple level keys work as well, with components separated with "."; for
132   example, given `map<string, map<string, string>> m`, `{foo.bar}` selects
133   `m["foo"]["bar"]`.
134 - `format_spec`: format specification, see below
135
136 Format specification:
137 `[[fill] align] [sign] ["#"] ["0"] [width] [","] ["." precision] ["."] [type]`
138
139 - `fill` (may only be specified if `align` is also specified): pad with this
140   character ('` `' (space) or '`0`' (zero) might be useful; space is default)
141 - `align`: one of '`<`', '`>`', '`=`', '`^`':
142     - '`<`': left-align (default for most objects)
143     - '`>`': right-align (default for numbers)
144     - '`=`': pad after sign, but before significant digits; used to print
145             `-0000120`; only valid for numbers
146     - '`^`': center
147 - `sign`: one of '`+`', '`-`', ' ' (space) (only valid for numbers)
148     - '`+`': output '`+`' if positive or zero, '`-`' if negative
149     - '`-`': output '`-`' if negative, nothing otherwise (default)
150     - '` `' (space): output '` `' (space) if positive or zero, '`-`' if negative
151 - '`#`': output base prefix (`0` for octal, `0b` or `0B` for binary, `0x` or
152   `0X` for hexadecimal; only valid for integers)
153 - '`0`': 0-pad after sign, same as specifying "`0=`" as the `fill` and
154   `align` parameters (only valid for numbers)
155 - `width`: minimum field width. May be '`*`' to indicate that the field width
156   is given by an argument. Defaults to the next argument (preceding the value
157   to be formatted) but an explicit argument index may be given following the
158   '`*`'. Not supported in `vformat()`.
159 - '`,`' (comma): output comma as thousands' separator (only valid for integers,
160   and only for decimal output)
161 - `precision` (not allowed for integers):
162     - for floating point values, number of digits after decimal point ('`f`' or
163       '`F`' presentation) or number of significant digits ('`g`' or '`G`')
164     - for others, maximum field size (truncate subsequent characters)
165 - '`.`' (when used after precision or in lieu of precison): Forces a trailing
166   decimal point to make it clear this is a floating point value.
167 - `type`: presentation format, see below
168
169 Presentation formats:
170
171 - Strings (`folly::StringPiece`, `std::string`, `folly::fbstring`,
172   `const char*`):
173     - '`s`' (default)
174 - Integers:
175     - '`b`': output in binary (base 2) ("`0b`" prefix if '`#`' specified)
176     - '`B`': output in binary (base 2) ("`0B`" prefix if '`#`' specified)
177     - '`c`': output as a character (cast to `char`)
178     - '`d`': output in decimal (base 10) (default)
179     - '`o`': output in octal (base 8)
180     - '`O`': output in octal (base 8) (same as '`o`')
181     - '`x`': output in hexadecimal (base 16) (lower-case digits above 9)
182     - '`X`': output in hexadecimal (base 16) (upper-case digits above 9)
183     - '`n`': locale-aware output (currently same as '`d`')
184 - `bool`:
185     - default: output "`true`" or "`false`" as strings
186     - integer presentations allowed as well
187 - `char`:
188     - same as other integers, but default is '`c`' instead of '`d`'
189 - Floating point (`float`, `double`; `long double` is not implemented):
190     - '`e`': scientific notation using '`e`' as exponent character
191     - '`E`': scientific notation using '`E`' as exponent character
192     - '`f`': fixed point
193     - '`F`': fixed point (same as '`f`')
194     - '`g`': general; use either '`f`' or '`e`' depending on magnitude (default)
195     - '`G`': general; use either '`f`' or '`E`' depending on magnitude
196     - '`n`': locale-aware version of '`g`' (currently same as '`g`')
197     - '`%`': percentage: multiply by 100 then display as '`f`'
198
199
200 ### Extension
201 ***
202
203 You can extend `format` for your own class by providing a specialization for
204 `folly::FormatValue`.  See `folly/Format.h` and `folly/FormatArg.h` for
205 details, and the existing specialization for `folly::dynamic` in
206 `folly/dynamic-inl.h` for an implementation example.