1 | //! Utilities for formatting and printing `String`s. |
2 | //! |
3 | //! This module contains the runtime support for the [`format!`] syntax extension. |
4 | //! This macro is implemented in the compiler to emit calls to this module in |
5 | //! order to format arguments at runtime into strings. |
6 | //! |
7 | //! # Usage |
8 | //! |
9 | //! The [`format!`] macro is intended to be familiar to those coming from C's |
10 | //! `printf`/`fprintf` functions or Python's `str.format` function. |
11 | //! |
12 | //! Some examples of the [`format!`] extension are: |
13 | //! |
14 | //! ``` |
15 | //! format!("Hello" ); // => "Hello" |
16 | //! format!("Hello, {}!" , "world" ); // => "Hello, world!" |
17 | //! format!("The number is {}" , 1); // => "The number is 1" |
18 | //! format!("{:?}" , (3, 4)); // => "(3, 4)" |
19 | //! format!("{value}" , value=4); // => "4" |
20 | //! let people = "Rustaceans" ; |
21 | //! format!("Hello {people}!" ); // => "Hello Rustaceans!" |
22 | //! format!("{} {}" , 1, 2); // => "1 2" |
23 | //! format!("{:04}" , 42); // => "0042" with leading zeros |
24 | //! format!("{:#?}" , (100, 200)); // => "( |
25 | //! // 100, |
26 | //! // 200, |
27 | //! // )" |
28 | //! ``` |
29 | //! |
30 | //! From these, you can see that the first argument is a format string. It is |
31 | //! required by the compiler for this to be a string literal; it cannot be a |
32 | //! variable passed in (in order to perform validity checking). The compiler |
33 | //! will then parse the format string and determine if the list of arguments |
34 | //! provided is suitable to pass to this format string. |
35 | //! |
36 | //! To convert a single value to a string, use the [`to_string`] method. This |
37 | //! will use the [`Display`] formatting trait. |
38 | //! |
39 | //! ## Positional parameters |
40 | //! |
41 | //! Each formatting argument is allowed to specify which value argument it's |
42 | //! referencing, and if omitted it is assumed to be "the next argument". For |
43 | //! example, the format string `{} {} {}` would take three parameters, and they |
44 | //! would be formatted in the same order as they're given. The format string |
45 | //! `{2} {1} {0}`, however, would format arguments in reverse order. |
46 | //! |
47 | //! Things can get a little tricky once you start intermingling the two types of |
48 | //! positional specifiers. The "next argument" specifier can be thought of as an |
49 | //! iterator over the argument. Each time a "next argument" specifier is seen, |
50 | //! the iterator advances. This leads to behavior like this: |
51 | //! |
52 | //! ``` |
53 | //! format!("{1} {} {0} {}" , 1, 2); // => "2 1 1 2" |
54 | //! ``` |
55 | //! |
56 | //! The internal iterator over the argument has not been advanced by the time |
57 | //! the first `{}` is seen, so it prints the first argument. Then upon reaching |
58 | //! the second `{}`, the iterator has advanced forward to the second argument. |
59 | //! Essentially, parameters that explicitly name their argument do not affect |
60 | //! parameters that do not name an argument in terms of positional specifiers. |
61 | //! |
62 | //! A format string is required to use all of its arguments, otherwise it is a |
63 | //! compile-time error. You may refer to the same argument more than once in the |
64 | //! format string. |
65 | //! |
66 | //! ## Named parameters |
67 | //! |
68 | //! Rust itself does not have a Python-like equivalent of named parameters to a |
69 | //! function, but the [`format!`] macro is a syntax extension that allows it to |
70 | //! leverage named parameters. Named parameters are listed at the end of the |
71 | //! argument list and have the syntax: |
72 | //! |
73 | //! ```text |
74 | //! identifier '=' expression |
75 | //! ``` |
76 | //! |
77 | //! For example, the following [`format!`] expressions all use named arguments: |
78 | //! |
79 | //! ``` |
80 | //! format!("{argument}" , argument = "test" ); // => "test" |
81 | //! format!("{name} {}" , 1, name = 2); // => "2 1" |
82 | //! format!("{a} {c} {b}" , a="a" , b='b' , c=3); // => "a 3 b" |
83 | //! ``` |
84 | //! |
85 | //! If a named parameter does not appear in the argument list, `format!` will |
86 | //! reference a variable with that name in the current scope. |
87 | //! |
88 | //! ``` |
89 | //! let argument = 2 + 2; |
90 | //! format!("{argument}" ); // => "4" |
91 | //! |
92 | //! fn make_string(a: u32, b: &str) -> String { |
93 | //! format!("{b} {a}" ) |
94 | //! } |
95 | //! make_string(927, "label" ); // => "label 927" |
96 | //! ``` |
97 | //! |
98 | //! It is not valid to put positional parameters (those without names) after |
99 | //! arguments that have names. Like with positional parameters, it is not |
100 | //! valid to provide named parameters that are unused by the format string. |
101 | //! |
102 | //! # Formatting Parameters |
103 | //! |
104 | //! Each argument being formatted can be transformed by a number of formatting |
105 | //! parameters (corresponding to `format_spec` in [the syntax](#syntax)). These |
106 | //! parameters affect the string representation of what's being formatted. |
107 | //! |
108 | //! ## Width |
109 | //! |
110 | //! ``` |
111 | //! // All of these print "Hello x !" |
112 | //! println!("Hello {:5}!" , "x" ); |
113 | //! println!("Hello {:1$}!" , "x" , 5); |
114 | //! println!("Hello {1:0$}!" , 5, "x" ); |
115 | //! println!("Hello {:width$}!" , "x" , width = 5); |
116 | //! let width = 5; |
117 | //! println!("Hello {:width$}!" , "x" ); |
118 | //! ``` |
119 | //! |
120 | //! This is a parameter for the "minimum width" that the format should take up. |
121 | //! If the value's string does not fill up this many characters, then the |
122 | //! padding specified by fill/alignment will be used to take up the required |
123 | //! space (see below). |
124 | //! |
125 | //! The value for the width can also be provided as a [`usize`] in the list of |
126 | //! parameters by adding a postfix `$`, indicating that the second argument is |
127 | //! a [`usize`] specifying the width. |
128 | //! |
129 | //! Referring to an argument with the dollar syntax does not affect the "next |
130 | //! argument" counter, so it's usually a good idea to refer to arguments by |
131 | //! position, or use named arguments. |
132 | //! |
133 | //! ## Fill/Alignment |
134 | //! |
135 | //! ``` |
136 | //! assert_eq!(format!("Hello {:<5}!" , "x" ), "Hello x !" ); |
137 | //! assert_eq!(format!("Hello {:-<5}!" , "x" ), "Hello x----!" ); |
138 | //! assert_eq!(format!("Hello {:^5}!" , "x" ), "Hello x !" ); |
139 | //! assert_eq!(format!("Hello {:>5}!" , "x" ), "Hello x!" ); |
140 | //! ``` |
141 | //! |
142 | //! The optional fill character and alignment is provided normally in conjunction with the |
143 | //! [`width`](#width) parameter. It must be defined before `width`, right after the `:`. |
144 | //! This indicates that if the value being formatted is smaller than |
145 | //! `width` some extra characters will be printed around it. |
146 | //! Filling comes in the following variants for different alignments: |
147 | //! |
148 | //! * `[fill]<` - the argument is left-aligned in `width` columns |
149 | //! * `[fill]^` - the argument is center-aligned in `width` columns |
150 | //! * `[fill]>` - the argument is right-aligned in `width` columns |
151 | //! |
152 | //! The default [fill/alignment](#fillalignment) for non-numerics is a space and |
153 | //! left-aligned. The |
154 | //! default for numeric formatters is also a space character but with right-alignment. If |
155 | //! the `0` flag (see below) is specified for numerics, then the implicit fill character is |
156 | //! `0`. |
157 | //! |
158 | //! Note that alignment might not be implemented by some types. In particular, it |
159 | //! is not generally implemented for the `Debug` trait. A good way to ensure |
160 | //! padding is applied is to format your input, then pad this resulting string |
161 | //! to obtain your output: |
162 | //! |
163 | //! ``` |
164 | //! println!("Hello {:^15}!" , format!("{:?}" , Some("hi" ))); // => "Hello Some("hi") !" |
165 | //! ``` |
166 | //! |
167 | //! ## Sign/`#`/`0` |
168 | //! |
169 | //! ``` |
170 | //! assert_eq!(format!("Hello {:+}!" , 5), "Hello +5!" ); |
171 | //! assert_eq!(format!("{:#x}!" , 27), "0x1b!" ); |
172 | //! assert_eq!(format!("Hello {:05}!" , 5), "Hello 00005!" ); |
173 | //! assert_eq!(format!("Hello {:05}!" , -5), "Hello -0005!" ); |
174 | //! assert_eq!(format!("{:#010x}!" , 27), "0x0000001b!" ); |
175 | //! ``` |
176 | //! |
177 | //! These are all flags altering the behavior of the formatter. |
178 | //! |
179 | //! * `+` - This is intended for numeric types and indicates that the sign |
180 | //! should always be printed. By default only the negative sign of signed values |
181 | //! is printed, and the sign of positive or unsigned values is omitted. |
182 | //! This flag indicates that the correct sign (`+` or `-`) should always be printed. |
183 | //! * `-` - Currently not used |
184 | //! * `#` - This flag indicates that the "alternate" form of printing should |
185 | //! be used. The alternate forms are: |
186 | //! * `#?` - pretty-print the [`Debug`] formatting (adds linebreaks and indentation) |
187 | //! * `#x` - precedes the argument with a `0x` |
188 | //! * `#X` - precedes the argument with a `0x` |
189 | //! * `#b` - precedes the argument with a `0b` |
190 | //! * `#o` - precedes the argument with a `0o` |
191 | //! |
192 | //! See [Formatting traits](#formatting-traits) for a description of what the `?`, `x`, `X`, |
193 | //! `b`, and `o` flags do. |
194 | //! |
195 | //! * `0` - This is used to indicate for integer formats that the padding to `width` should |
196 | //! both be done with a `0` character as well as be sign-aware. A format |
197 | //! like `{:08}` would yield `00000001` for the integer `1`, while the |
198 | //! same format would yield `-0000001` for the integer `-1`. Notice that |
199 | //! the negative version has one fewer zero than the positive version. |
200 | //! Note that padding zeros are always placed after the sign (if any) |
201 | //! and before the digits. When used together with the `#` flag, a similar |
202 | //! rule applies: padding zeros are inserted after the prefix but before |
203 | //! the digits. The prefix is included in the total width. |
204 | //! This flag overrides the [fill character and alignment flag](#fillalignment). |
205 | //! |
206 | //! ## Precision |
207 | //! |
208 | //! For non-numeric types, this can be considered a "maximum width". If the resulting string is |
209 | //! longer than this width, then it is truncated down to this many characters and that truncated |
210 | //! value is emitted with proper `fill`, `alignment` and `width` if those parameters are set. |
211 | //! |
212 | //! For integral types, this is ignored. |
213 | //! |
214 | //! For floating-point types, this indicates how many digits after the decimal point should be |
215 | //! printed. |
216 | //! |
217 | //! There are three possible ways to specify the desired `precision`: |
218 | //! |
219 | //! 1. An integer `.N`: |
220 | //! |
221 | //! the integer `N` itself is the precision. |
222 | //! |
223 | //! 2. An integer or name followed by dollar sign `.N$`: |
224 | //! |
225 | //! use format *argument* `N` (which must be a `usize`) as the precision. |
226 | //! |
227 | //! 3. An asterisk `.*`: |
228 | //! |
229 | //! `.*` means that this `{...}` is associated with *two* format inputs rather than one: |
230 | //! - If a format string in the fashion of `{:<spec>.*}` is used, then the first input holds |
231 | //! the `usize` precision, and the second holds the value to print. |
232 | //! - If a format string in the fashion of `{<arg>:<spec>.*}` is used, then the `<arg>` part |
233 | //! refers to the value to print, and the `precision` is taken like it was specified with an |
234 | //! omitted positional parameter (`{}` instead of `{<arg>:}`). |
235 | //! |
236 | //! For example, the following calls all print the same thing `Hello x is 0.01000`: |
237 | //! |
238 | //! ``` |
239 | //! // Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)} |
240 | //! println!("Hello {0} is {1:.5}" , "x" , 0.01); |
241 | //! |
242 | //! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)} |
243 | //! println!("Hello {1} is {2:.0$}" , 5, "x" , 0.01); |
244 | //! |
245 | //! // Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)} |
246 | //! println!("Hello {0} is {2:.1$}" , "x" , 5, 0.01); |
247 | //! |
248 | //! // Hello {next arg -> arg 0 ("x")} is {second of next two args -> arg 2 (0.01) with precision |
249 | //! // specified in first of next two args -> arg 1 (5)} |
250 | //! println!("Hello {} is {:.*}" , "x" , 5, 0.01); |
251 | //! |
252 | //! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision |
253 | //! // specified in next arg -> arg 0 (5)} |
254 | //! println!("Hello {1} is {2:.*}" , 5, "x" , 0.01); |
255 | //! |
256 | //! // Hello {next arg -> arg 0 ("x")} is {arg 2 (0.01) with precision |
257 | //! // specified in next arg -> arg 1 (5)} |
258 | //! println!("Hello {} is {2:.*}" , "x" , 5, 0.01); |
259 | //! |
260 | //! // Hello {next arg -> arg 0 ("x")} is {arg "number" (0.01) with precision specified |
261 | //! // in arg "prec" (5)} |
262 | //! println!("Hello {} is {number:.prec$}" , "x" , prec = 5, number = 0.01); |
263 | //! ``` |
264 | //! |
265 | //! While these: |
266 | //! |
267 | //! ``` |
268 | //! println!("{}, `{name:.*}` has 3 fractional digits" , "Hello" , 3, name=1234.56); |
269 | //! println!("{}, `{name:.*}` has 3 characters" , "Hello" , 3, name="1234.56" ); |
270 | //! println!("{}, `{name:>8.*}` has 3 right-aligned characters" , "Hello" , 3, name="1234.56" ); |
271 | //! ``` |
272 | //! |
273 | //! print three significantly different things: |
274 | //! |
275 | //! ```text |
276 | //! Hello, `1234.560` has 3 fractional digits |
277 | //! Hello, `123` has 3 characters |
278 | //! Hello, ` 123` has 3 right-aligned characters |
279 | //! ``` |
280 | //! |
281 | //! When truncating these values, Rust uses [round half-to-even](https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even), |
282 | //! which is the default rounding mode in IEEE 754. |
283 | //! For example, |
284 | //! |
285 | //! ``` |
286 | //! print!("{0:.1$e}" , 12345, 3); |
287 | //! print!("{0:.1$e}" , 12355, 3); |
288 | //! ``` |
289 | //! |
290 | //! Would return: |
291 | //! |
292 | //! ```text |
293 | //! 1.234e4 |
294 | //! 1.236e4 |
295 | //! ``` |
296 | //! |
297 | //! ## Localization |
298 | //! |
299 | //! In some programming languages, the behavior of string formatting functions |
300 | //! depends on the operating system's locale setting. The format functions |
301 | //! provided by Rust's standard library do not have any concept of locale and |
302 | //! will produce the same results on all systems regardless of user |
303 | //! configuration. |
304 | //! |
305 | //! For example, the following code will always print `1.5` even if the system |
306 | //! locale uses a decimal separator other than a dot. |
307 | //! |
308 | //! ``` |
309 | //! println!("The value is {}" , 1.5); |
310 | //! ``` |
311 | //! |
312 | //! # Escaping |
313 | //! |
314 | //! The literal characters `{` and `}` may be included in a string by preceding |
315 | //! them with the same character. For example, the `{` character is escaped with |
316 | //! `{{` and the `}` character is escaped with `}}`. |
317 | //! |
318 | //! ``` |
319 | //! assert_eq!(format!("Hello {{}}" ), "Hello {}" ); |
320 | //! assert_eq!(format!("{{ Hello" ), "{ Hello" ); |
321 | //! ``` |
322 | //! |
323 | //! # Syntax |
324 | //! |
325 | //! To summarize, here you can find the full grammar of format strings. |
326 | //! The syntax for the formatting language used is drawn from other languages, |
327 | //! so it should not be too alien. Arguments are formatted with Python-like |
328 | //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like |
329 | //! `%`. The actual grammar for the formatting syntax is: |
330 | //! |
331 | //! ```text |
332 | //! format_string := text [ maybe_format text ] * |
333 | //! maybe_format := '{' '{' | '}' '}' | format |
334 | //! format := '{' [ argument ] [ ':' format_spec ] [ ws ] * '}' |
335 | //! argument := integer | identifier |
336 | //! |
337 | //! format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type |
338 | //! fill := character |
339 | //! align := '<' | '^' | '>' |
340 | //! sign := '+' | '-' |
341 | //! width := count |
342 | //! precision := count | '*' |
343 | //! type := '' | '?' | 'x?' | 'X?' | identifier |
344 | //! count := parameter | integer |
345 | //! parameter := argument '$' |
346 | //! ``` |
347 | //! In the above grammar, |
348 | //! - `text` must not contain any `'{'` or `'}'` characters, |
349 | //! - `ws` is any character for which [`char::is_whitespace`] returns `true`, has no semantic |
350 | //! meaning and is completely optional, |
351 | //! - `integer` is a decimal integer that may contain leading zeroes and must fit into an `usize` and |
352 | //! - `identifier` is an `IDENTIFIER_OR_KEYWORD` (not an `IDENTIFIER`) as defined by the [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html). |
353 | //! |
354 | //! # Formatting traits |
355 | //! |
356 | //! When requesting that an argument be formatted with a particular type, you |
357 | //! are actually requesting that an argument ascribes to a particular trait. |
358 | //! This allows multiple actual types to be formatted via `{:x}` (like [`i8`] as |
359 | //! well as [`isize`]). The current mapping of types to traits is: |
360 | //! |
361 | //! * *nothing* ⇒ [`Display`] |
362 | //! * `?` ⇒ [`Debug`] |
363 | //! * `x?` ⇒ [`Debug`] with lower-case hexadecimal integers |
364 | //! * `X?` ⇒ [`Debug`] with upper-case hexadecimal integers |
365 | //! * `o` ⇒ [`Octal`] |
366 | //! * `x` ⇒ [`LowerHex`] |
367 | //! * `X` ⇒ [`UpperHex`] |
368 | //! * `p` ⇒ [`Pointer`] |
369 | //! * `b` ⇒ [`Binary`] |
370 | //! * `e` ⇒ [`LowerExp`] |
371 | //! * `E` ⇒ [`UpperExp`] |
372 | //! |
373 | //! What this means is that any type of argument which implements the |
374 | //! [`fmt::Binary`][`Binary`] trait can then be formatted with `{:b}`. Implementations |
375 | //! are provided for these traits for a number of primitive types by the |
376 | //! standard library as well. If no format is specified (as in `{}` or `{:6}`), |
377 | //! then the format trait used is the [`Display`] trait. |
378 | //! |
379 | //! When implementing a format trait for your own type, you will have to |
380 | //! implement a method of the signature: |
381 | //! |
382 | //! ``` |
383 | //! # #![allow(dead_code)] |
384 | //! # use std::fmt; |
385 | //! # struct Foo; // our custom type |
386 | //! # impl fmt::Display for Foo { |
387 | //! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
388 | //! # write!(f, "testing, testing" ) |
389 | //! # } } |
390 | //! ``` |
391 | //! |
392 | //! Your type will be passed as `self` by-reference, and then the function |
393 | //! should emit output into the Formatter `f` which implements `fmt::Write`. It is up to each |
394 | //! format trait implementation to correctly adhere to the requested formatting parameters. |
395 | //! The values of these parameters can be accessed with methods of the |
396 | //! [`Formatter`] struct. In order to help with this, the [`Formatter`] struct also |
397 | //! provides some helper methods. |
398 | //! |
399 | //! Additionally, the return value of this function is [`fmt::Result`] which is a |
400 | //! type alias of <code>[Result]<(), [std::fmt::Error]></code>. Formatting implementations |
401 | //! should ensure that they propagate errors from the [`Formatter`] (e.g., when |
402 | //! calling [`write!`]). However, they should never return errors spuriously. That |
403 | //! is, a formatting implementation must and may only return an error if the |
404 | //! passed-in [`Formatter`] returns an error. This is because, contrary to what |
405 | //! the function signature might suggest, string formatting is an infallible |
406 | //! operation. This function only returns a result because writing to the |
407 | //! underlying stream might fail and it must provide a way to propagate the fact |
408 | //! that an error has occurred back up the stack. |
409 | //! |
410 | //! An example of implementing the formatting traits would look |
411 | //! like: |
412 | //! |
413 | //! ``` |
414 | //! use std::fmt; |
415 | //! |
416 | //! #[derive(Debug)] |
417 | //! struct Vector2D { |
418 | //! x: isize, |
419 | //! y: isize, |
420 | //! } |
421 | //! |
422 | //! impl fmt::Display for Vector2D { |
423 | //! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
424 | //! // The `f` value implements the `Write` trait, which is what the |
425 | //! // write! macro is expecting. Note that this formatting ignores the |
426 | //! // various flags provided to format strings. |
427 | //! write!(f, "({}, {})" , self.x, self.y) |
428 | //! } |
429 | //! } |
430 | //! |
431 | //! // Different traits allow different forms of output of a type. The meaning |
432 | //! // of this format is to print the magnitude of a vector. |
433 | //! impl fmt::Binary for Vector2D { |
434 | //! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
435 | //! let magnitude = (self.x * self.x + self.y * self.y) as f64; |
436 | //! let magnitude = magnitude.sqrt(); |
437 | //! |
438 | //! // Respect the formatting flags by using the helper method |
439 | //! // `pad_integral` on the Formatter object. See the method |
440 | //! // documentation for details, and the function `pad` can be used |
441 | //! // to pad strings. |
442 | //! let decimals = f.precision().unwrap_or(3); |
443 | //! let string = format!("{magnitude:.decimals$}" ); |
444 | //! f.pad_integral(true, "" , &string) |
445 | //! } |
446 | //! } |
447 | //! |
448 | //! fn main() { |
449 | //! let myvector = Vector2D { x: 3, y: 4 }; |
450 | //! |
451 | //! println!("{myvector}" ); // => "(3, 4)" |
452 | //! println!("{myvector:?}" ); // => "Vector2D {x: 3, y:4}" |
453 | //! println!("{myvector:10.3b}" ); // => " 5.000" |
454 | //! } |
455 | //! ``` |
456 | //! |
457 | //! ### `fmt::Display` vs `fmt::Debug` |
458 | //! |
459 | //! These two formatting traits have distinct purposes: |
460 | //! |
461 | //! - [`fmt::Display`][`Display`] implementations assert that the type can be faithfully |
462 | //! represented as a UTF-8 string at all times. It is **not** expected that |
463 | //! all types implement the [`Display`] trait. |
464 | //! - [`fmt::Debug`][`Debug`] implementations should be implemented for **all** public types. |
465 | //! Output will typically represent the internal state as faithfully as possible. |
466 | //! The purpose of the [`Debug`] trait is to facilitate debugging Rust code. In |
467 | //! most cases, using `#[derive(Debug)]` is sufficient and recommended. |
468 | //! |
469 | //! Some examples of the output from both traits: |
470 | //! |
471 | //! ``` |
472 | //! assert_eq!(format!("{} {:?}" , 3, 4), "3 4" ); |
473 | //! assert_eq!(format!("{} {:?}" , 'a' , 'b' ), "a 'b'" ); |
474 | //! assert_eq!(format!("{} {:?}" , "foo \n" , "bar \n" ), "foo \n \"bar \\n \"" ); |
475 | //! ``` |
476 | //! |
477 | //! # Related macros |
478 | //! |
479 | //! There are a number of related macros in the [`format!`] family. The ones that |
480 | //! are currently implemented are: |
481 | //! |
482 | //! ```ignore (only-for-syntax-highlight) |
483 | //! format! // described above |
484 | //! write! // first argument is either a &mut io::Write or a &mut fmt::Write, the destination |
485 | //! writeln! // same as write but appends a newline |
486 | //! print! // the format string is printed to the standard output |
487 | //! println! // same as print but appends a newline |
488 | //! eprint! // the format string is printed to the standard error |
489 | //! eprintln! // same as eprint but appends a newline |
490 | //! format_args! // described below. |
491 | //! ``` |
492 | //! |
493 | //! ### `write!` |
494 | //! |
495 | //! [`write!`] and [`writeln!`] are two macros which are used to emit the format string |
496 | //! to a specified stream. This is used to prevent intermediate allocations of |
497 | //! format strings and instead directly write the output. Under the hood, this |
498 | //! function is actually invoking the [`write_fmt`] function defined on the |
499 | //! [`std::io::Write`] and the [`std::fmt::Write`] trait. Example usage is: |
500 | //! |
501 | //! ``` |
502 | //! # #![allow(unused_must_use)] |
503 | //! use std::io::Write; |
504 | //! let mut w = Vec::new(); |
505 | //! write!(&mut w, "Hello {}!" , "world" ); |
506 | //! ``` |
507 | //! |
508 | //! ### `print!` |
509 | //! |
510 | //! This and [`println!`] emit their output to stdout. Similarly to the [`write!`] |
511 | //! macro, the goal of these macros is to avoid intermediate allocations when |
512 | //! printing output. Example usage is: |
513 | //! |
514 | //! ``` |
515 | //! print!("Hello {}!" , "world" ); |
516 | //! println!("I have a newline {}" , "character at the end" ); |
517 | //! ``` |
518 | //! ### `eprint!` |
519 | //! |
520 | //! The [`eprint!`] and [`eprintln!`] macros are identical to |
521 | //! [`print!`] and [`println!`], respectively, except they emit their |
522 | //! output to stderr. |
523 | //! |
524 | //! ### `format_args!` |
525 | //! |
526 | //! [`format_args!`] is a curious macro used to safely pass around |
527 | //! an opaque object describing the format string. This object |
528 | //! does not require any heap allocations to create, and it only |
529 | //! references information on the stack. Under the hood, all of |
530 | //! the related macros are implemented in terms of this. First |
531 | //! off, some example usage is: |
532 | //! |
533 | //! ``` |
534 | //! # #![allow(unused_must_use)] |
535 | //! use std::fmt; |
536 | //! use std::io::{self, Write}; |
537 | //! |
538 | //! let mut some_writer = io::stdout(); |
539 | //! write!(&mut some_writer, "{}" , format_args!("print with a {}" , "macro" )); |
540 | //! |
541 | //! fn my_fmt_fn(args: fmt::Arguments<'_>) { |
542 | //! write!(&mut io::stdout(), "{args}" ); |
543 | //! } |
544 | //! my_fmt_fn(format_args!(", or a {} too" , "function" )); |
545 | //! ``` |
546 | //! |
547 | //! The result of the [`format_args!`] macro is a value of type [`fmt::Arguments`]. |
548 | //! This structure can then be passed to the [`write`] and [`format`] functions |
549 | //! inside this module in order to process the format string. |
550 | //! The goal of this macro is to even further prevent intermediate allocations |
551 | //! when dealing with formatting strings. |
552 | //! |
553 | //! For example, a logging library could use the standard formatting syntax, but |
554 | //! it would internally pass around this structure until it has been determined |
555 | //! where output should go to. |
556 | //! |
557 | //! [`fmt::Result`]: Result "fmt::Result" |
558 | //! [Result]: core::result::Result "std::result::Result" |
559 | //! [std::fmt::Error]: Error "fmt::Error" |
560 | //! [`write`]: write() "fmt::write" |
561 | //! [`to_string`]: crate::string::ToString::to_string "ToString::to_string" |
562 | //! [`write_fmt`]: ../../std/io/trait.Write.html#method.write_fmt |
563 | //! [`std::io::Write`]: ../../std/io/trait.Write.html |
564 | //! [`std::fmt::Write`]: ../../std/fmt/trait.Write.html |
565 | //! [`print!`]: ../../std/macro.print.html "print!" |
566 | //! [`println!`]: ../../std/macro.println.html "println!" |
567 | //! [`eprint!`]: ../../std/macro.eprint.html "eprint!" |
568 | //! [`eprintln!`]: ../../std/macro.eprintln.html "eprintln!" |
569 | //! [`format_args!`]: ../../std/macro.format_args.html "format_args!" |
570 | //! [`fmt::Arguments`]: Arguments "fmt::Arguments" |
571 | //! [`format`]: format() "fmt::format" |
572 | |
573 | #![stable (feature = "rust1" , since = "1.0.0" )] |
574 | |
575 | #[stable (feature = "fmt_flags_align" , since = "1.28.0" )] |
576 | pub use core::fmt::Alignment; |
577 | #[stable (feature = "rust1" , since = "1.0.0" )] |
578 | pub use core::fmt::Error; |
579 | #[unstable (feature = "debug_closure_helpers" , issue = "117729" )] |
580 | pub use core::fmt::FormatterFn; |
581 | #[stable (feature = "rust1" , since = "1.0.0" )] |
582 | pub use core::fmt::{write, Arguments}; |
583 | #[stable (feature = "rust1" , since = "1.0.0" )] |
584 | pub use core::fmt::{Binary, Octal}; |
585 | #[stable (feature = "rust1" , since = "1.0.0" )] |
586 | pub use core::fmt::{Debug, Display}; |
587 | #[stable (feature = "rust1" , since = "1.0.0" )] |
588 | pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; |
589 | #[stable (feature = "rust1" , since = "1.0.0" )] |
590 | pub use core::fmt::{Formatter, Result, Write}; |
591 | #[stable (feature = "rust1" , since = "1.0.0" )] |
592 | pub use core::fmt::{LowerExp, UpperExp}; |
593 | #[stable (feature = "rust1" , since = "1.0.0" )] |
594 | pub use core::fmt::{LowerHex, Pointer, UpperHex}; |
595 | |
596 | #[cfg (not(no_global_oom_handling))] |
597 | use crate::string; |
598 | |
599 | /// The `format` function takes an [`Arguments`] struct and returns the resulting |
600 | /// formatted string. |
601 | /// |
602 | /// The [`Arguments`] instance can be created with the [`format_args!`] macro. |
603 | /// |
604 | /// # Examples |
605 | /// |
606 | /// Basic usage: |
607 | /// |
608 | /// ``` |
609 | /// use std::fmt; |
610 | /// |
611 | /// let s = fmt::format(format_args!("Hello, {}!" , "world" )); |
612 | /// assert_eq!(s, "Hello, world!" ); |
613 | /// ``` |
614 | /// |
615 | /// Please note that using [`format!`] might be preferable. |
616 | /// Example: |
617 | /// |
618 | /// ``` |
619 | /// let s = format!("Hello, {}!" , "world" ); |
620 | /// assert_eq!(s, "Hello, world!" ); |
621 | /// ``` |
622 | /// |
623 | /// [`format_args!`]: core::format_args |
624 | /// [`format!`]: crate::format |
625 | #[cfg (not(no_global_oom_handling))] |
626 | #[must_use ] |
627 | #[stable (feature = "rust1" , since = "1.0.0" )] |
628 | #[inline ] |
629 | pub fn format(args: Arguments<'_>) -> string::String { |
630 | fn format_inner(args: Arguments<'_>) -> string::String { |
631 | let capacity: usize = args.estimated_capacity(); |
632 | let mut output: String = string::String::with_capacity(capacity); |
633 | output.write_fmt(args).expect(msg:"a formatting trait implementation returned an error" ); |
634 | output |
635 | } |
636 | |
637 | args.as_str().map_or_else(|| format_inner(args), f:crate::borrow::ToOwned::to_owned) |
638 | } |
639 | |