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