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