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