Skip to main content

alloc/
fmt.rs

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