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