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