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

527
#![stable(feature = "rust1", since = "1.0.0")]
528

529
#[unstable(feature = "fmt_internals", issue = "none")]
V
Vadim Petrochenkov 已提交
530
pub use core::fmt::rt;
D
David Tolnay 已提交
531 532
#[stable(feature = "fmt_flags_align", since = "1.28.0")]
pub use core::fmt::Alignment;
533
#[stable(feature = "rust1", since = "1.0.0")]
D
David Tolnay 已提交
534 535 536
pub use core::fmt::Error;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{write, ArgumentV1, Arguments};
537 538 539 540 541
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Binary, Octal};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{Debug, Display};
#[stable(feature = "rust1", since = "1.0.0")]
D
David Tolnay 已提交
542
pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
543
#[stable(feature = "rust1", since = "1.0.0")]
D
David Tolnay 已提交
544
pub use core::fmt::{Formatter, Result, Write};
545
#[stable(feature = "rust1", since = "1.0.0")]
D
David Tolnay 已提交
546
pub use core::fmt::{LowerExp, UpperExp};
547
#[stable(feature = "rust1", since = "1.0.0")]
D
David Tolnay 已提交
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
///
S
Steve Klabnik 已提交
557
/// # Examples
558
///
559 560
/// Basic usage:
///
561
/// ```
562 563 564
/// use std::fmt;
///
/// let s = fmt::format(format_args!("Hello, {}!", "world"));
565
/// assert_eq!(s, "Hello, world!");
566
/// ```
567
///
M
Martin Lindhe 已提交
568
/// Please note that using [`format!`] might be preferable.
569 570 571 572
/// Example:
///
/// ```
/// let s = format!("Hello, {}!", "world");
573
/// assert_eq!(s, "Hello, world!");
574 575
/// ```
///
L
LeSeulArtichaut 已提交
576 577
/// [`format_args!`]: core::format_args
/// [`format!`]: crate::format
578
#[stable(feature = "rust1", since = "1.0.0")]
579
pub fn format(args: Arguments<'_>) -> string::String {
580 581
    let capacity = args.estimated_capacity();
    let mut output = string::String::with_capacity(capacity);
D
David Tolnay 已提交
582
    output.write_fmt(args).expect("a formatting trait implementation returned an error");
583 584
    output
}