]> git.lizzy.rs Git - rust.git/blob - src/libcollections/fmt.rs
80fa6d397c82911852f24658c2ae572cbc80cb6f
[rust.git] / src / libcollections / fmt.rs
1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
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.
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 //!
17 //! # Usage
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 //!
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"
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 //!
42 //! ## Positional parameters
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 //!
55 //! ```
56 //! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
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 //!
69 //! ## Named parameters
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 //!
82 //! ```
83 //! format!("{argument}", argument = "test");   // => "test"
84 //! format!("{name} {}", 1, name = 2);        // => "2 1"
85 //! format!("{a} {c} {b}", a="a", b='b', c=3);  // => "a 3 b"
86 //! ```
87 //!
88 //! It is illegal to put positional parameters (those without names) after
89 //! arguments which have names. Like with positional parameters, it is illegal
90 //! to provide named parameters that are unused by the format string.
91 //!
92 //! ## Argument types
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 //!
106 //! There are various parameters which do require a particular type, however. Namely, the `{:.*}`
107 //! syntax, which sets the number of numbers after the decimal in floating-point types:
108 //!
109 //! ```
110 //! let formatted_number = format!("{:.*}", 2, 1.234567);
111 //!
112 //! assert_eq!("1.23", formatted_number)
113 //! ```
114 //!
115 //! If this syntax is used, then the number of characters to print precedes the actual object being
116 //! formatted, and the number of characters must have the type `usize`. Although a `usize` can be
117 //! printed with `{}`, it is illegal to reference an argument as such. For example this is another
118 //! invalid format string:
119 //!
120 //! ```text
121 //! {:.*} {0}
122 //! ```
123 //!
124 //! ## Formatting traits
125 //!
126 //! When requesting that an argument be formatted with a particular type, you
127 //! are actually requesting that an argument ascribes to a particular trait.
128 //! This allows multiple actual types to be formatted via `{:x}` (like `i8` as
129 //! well as `isize`).  The current mapping of types to traits is:
130 //!
131 //! * *nothing* ⇒ `Display`
132 //! * `?` ⇒ `Debug`
133 //! * `o` ⇒ `Octal`
134 //! * `x` ⇒ `LowerHex`
135 //! * `X` ⇒ `UpperHex`
136 //! * `p` ⇒ `Pointer`
137 //! * `b` ⇒ `Binary`
138 //! * `e` ⇒ `LowerExp`
139 //! * `E` ⇒ `UpperExp`
140 //!
141 //! What this means is that any type of argument which implements the
142 //! `fmt::Binary` trait can then be formatted with `{:b}`. Implementations
143 //! are provided for these traits for a number of primitive types by the
144 //! standard library as well. If no format is specified (as in `{}` or `{:6}`),
145 //! then the format trait used is the `Display` trait.
146 //!
147 //! When implementing a format trait for your own type, you will have to
148 //! implement a method of the signature:
149 //!
150 //! ```
151 //! # use std::fmt;
152 //! # struct Foo; // our custom type
153 //! # impl fmt::Display for Foo {
154 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
155 //! # write!(f, "testing, testing")
156 //! # } }
157 //! ```
158 //!
159 //! Your type will be passed as `self` by-reference, and then the function
160 //! should emit output into the `f.buf` stream. It is up to each format trait
161 //! implementation to correctly adhere to the requested formatting parameters.
162 //! The values of these parameters will be listed in the fields of the
163 //! `Formatter` struct. In order to help with this, the `Formatter` struct also
164 //! provides some helper methods.
165 //!
166 //! Additionally, the return value of this function is `fmt::Result` which is a
167 //! typedef to `Result<(), IoError>` (also known as `IoResult<()>`). Formatting
168 //! implementations should ensure that they return errors from `write!`
169 //! correctly (propagating errors upward).
170 //!
171 //! An example of implementing the formatting traits would look
172 //! like:
173 //!
174 //! ```
175 //! # #![feature(core, std_misc)]
176 //! use std::fmt;
177 //! use std::f64;
178 //!
179 //! #[derive(Debug)]
180 //! struct Vector2D {
181 //!     x: isize,
182 //!     y: isize,
183 //! }
184 //!
185 //! impl fmt::Display for Vector2D {
186 //!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
187 //!         // The `f` value implements the `Write` trait, which is what the
188 //!         // write! macro is expecting. Note that this formatting ignores the
189 //!         // various flags provided to format strings.
190 //!         write!(f, "({}, {})", self.x, self.y)
191 //!     }
192 //! }
193 //!
194 //! // Different traits allow different forms of output of a type. The meaning
195 //! // of this format is to print the magnitude of a vector.
196 //! impl fmt::Binary for Vector2D {
197 //!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
198 //!         let magnitude = (self.x * self.x + self.y * self.y) as f64;
199 //!         let magnitude = magnitude.sqrt();
200 //!
201 //!         // Respect the formatting flags by using the helper method
202 //!         // `pad_integral` on the Formatter object. See the method
203 //!         // documentation for details, and the function `pad` can be used
204 //!         // to pad strings.
205 //!         let decimals = f.precision().unwrap_or(3);
206 //!         let string = format!("{:.*}", decimals, magnitude);
207 //!         f.pad_integral(true, "", &string)
208 //!     }
209 //! }
210 //!
211 //! fn main() {
212 //!     let myvector = Vector2D { x: 3, y: 4 };
213 //!
214 //!     println!("{}", myvector);       // => "(3, 4)"
215 //!     println!("{:?}", myvector);     // => "Vector2D {x: 3, y:4}"
216 //!     println!("{:10.3b}", myvector); // => "     5.000"
217 //! }
218 //! ```
219 //!
220 //! ### fmt::Display vs fmt::Debug
221 //!
222 //! These two formatting traits have distinct purposes:
223 //!
224 //! - `fmt::Display` implementations assert that the type can be faithfully
225 //!   represented as a UTF-8 string at all times. It is **not** expected that
226 //!   all types implement the `Display` trait.
227 //! - `fmt::Debug` implementations should be implemented for **all** public types.
228 //!   Output will typically represent the internal state as faithfully as possible.
229 //!   The purpose of the `Debug` trait is to facilitate debugging Rust code. In
230 //!   most cases, using `#[derive(Debug)]` is sufficient and recommended.
231 //!
232 //! Some examples of the output from both traits:
233 //!
234 //! ```
235 //! assert_eq!(format!("{} {:?}", 3, 4), "3 4");
236 //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
237 //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
238 //! ```
239 //!
240 //! ## Related macros
241 //!
242 //! There are a number of related macros in the `format!` family. The ones that
243 //! are currently implemented are:
244 //!
245 //! ```ignore
246 //! format!      // described above
247 //! write!       // first argument is a &mut io::Write, the destination
248 //! writeln!     // same as write but appends a newline
249 //! print!       // the format string is printed to the standard output
250 //! println!     // same as print but appends a newline
251 //! format_args! // described below.
252 //! ```
253 //!
254 //! ### `write!`
255 //!
256 //! This and `writeln` are two macros which are used to emit the format string
257 //! to a specified stream. This is used to prevent intermediate allocations of
258 //! format strings and instead directly write the output. Under the hood, this
259 //! function is actually invoking the `write` function defined in this module.
260 //! Example usage is:
261 //!
262 //! ```
263 //! # #![allow(unused_must_use)]
264 //! use std::io::Write;
265 //! let mut w = Vec::new();
266 //! write!(&mut w, "Hello {}!", "world");
267 //! ```
268 //!
269 //! ### `print!`
270 //!
271 //! This and `println` emit their output to stdout. Similarly to the `write!`
272 //! macro, the goal of these macros is to avoid intermediate allocations when
273 //! printing output. Example usage is:
274 //!
275 //! ```
276 //! print!("Hello {}!", "world");
277 //! println!("I have a newline {}", "character at the end");
278 //! ```
279 //!
280 //! ### `format_args!`
281 //!
282 //! This is a curious macro which is used to safely pass around
283 //! an opaque object describing the format string. This object
284 //! does not require any heap allocations to create, and it only
285 //! references information on the stack. Under the hood, all of
286 //! the related macros are implemented in terms of this. First
287 //! off, some example usage is:
288 //!
289 //! ```
290 //! use std::fmt;
291 //! use std::io::{self, Write};
292 //!
293 //! fmt::format(format_args!("this returns {}", "String"));
294 //!
295 //! let mut some_writer = io::stdout();
296 //! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro"));
297 //!
298 //! fn my_fmt_fn(args: fmt::Arguments) {
299 //!     write!(&mut io::stdout(), "{}", args);
300 //! }
301 //! my_fmt_fn(format_args!("or a {} too", "function"));
302 //! ```
303 //!
304 //! The result of the `format_args!` macro is a value of type `fmt::Arguments`.
305 //! This structure can then be passed to the `write` and `format` functions
306 //! inside this module in order to process the format string.
307 //! The goal of this macro is to even further prevent intermediate allocations
308 //! when dealing formatting strings.
309 //!
310 //! For example, a logging library could use the standard formatting syntax, but
311 //! it would internally pass around this structure until it has been determined
312 //! where output should go to.
313 //!
314 //! # Syntax
315 //!
316 //! The syntax for the formatting language used is drawn from other languages,
317 //! so it should not be too alien. Arguments are formatted with python-like
318 //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
319 //! `%`. The actual grammar for the formatting syntax is:
320 //!
321 //! ```text
322 //! format_string := <text> [ format <text> ] *
323 //! format := '{' [ argument ] [ ':' format_spec ] '}'
324 //! argument := integer | identifier
325 //!
326 //! format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
327 //! fill := character
328 //! align := '<' | '^' | '>'
329 //! sign := '+' | '-'
330 //! width := count
331 //! precision := count | '*'
332 //! type := identifier | ''
333 //! count := parameter | integer
334 //! parameter := integer '$'
335 //! ```
336 //!
337 //! # Formatting Parameters
338 //!
339 //! Each argument being formatted can be transformed by a number of formatting
340 //! parameters (corresponding to `format_spec` in the syntax above). These
341 //! parameters affect the string representation of what's being formatted. This
342 //! syntax draws heavily from Python's, so it may seem a bit familiar.
343 //!
344 //! ## Fill/Alignment
345 //!
346 //! The fill character is provided normally in conjunction with the `width`
347 //! parameter. This indicates that if the value being formatted is smaller than
348 //! `width` some extra characters will be printed around it. The extra
349 //! characters are specified by `fill`, and the alignment can be one of two
350 //! options:
351 //!
352 //! * `<` - the argument is left-aligned in `width` columns
353 //! * `^` - the argument is center-aligned in `width` columns
354 //! * `>` - the argument is right-aligned in `width` columns
355 //!
356 //! ## Sign/#/0
357 //!
358 //! These can all be interpreted as flags for a particular formatter.
359 //!
360 //! * '+' - This is intended for numeric types and indicates that the sign
361 //!         should always be printed. Positive signs are never printed by
362 //!         default, and the negative sign is only printed by default for the
363 //!         `Signed` trait. This flag indicates that the correct sign (+ or -)
364 //!         should always be printed.
365 //! * '-' - Currently not used
366 //! * '#' - This flag is indicates that the "alternate" form of printing should
367 //!         be used.  For array slices, the alternate form omits the brackets.
368 //!         For the integer formatting traits, the alternate forms are:
369 //!     * `#x` - precedes the argument with a "0x"
370 //!     * `#X` - precedes the argument with a "0x"
371 //!     * `#t` - precedes the argument with a "0b"
372 //!     * `#o` - precedes the argument with a "0o"
373 //! * '0' - This is used to indicate for integer formats that the padding should
374 //!         both be done with a `0` character as well as be sign-aware. A format
375 //!         like `{:08}` would yield `00000001` for the integer `1`, while the
376 //!         same format would yield `-0000001` for the integer `-1`. Notice that
377 //!         the negative version has one fewer zero than the positive version.
378 //!
379 //! ## Width
380 //!
381 //! This is a parameter for the "minimum width" that the format should take up.
382 //! If the value's string does not fill up this many characters, then the
383 //! padding specified by fill/alignment will be used to take up the required
384 //! space.
385 //!
386 //! The default fill/alignment for non-numerics is a space and left-aligned. The
387 //! defaults for numeric formatters is also a space but with right-alignment. If
388 //! the '0' flag is specified for numerics, then the implicit fill character is
389 //! '0'.
390 //!
391 //! The value for the width can also be provided as a `usize` in the list of
392 //! parameters by using the `2$` syntax indicating that the second argument is a
393 //! `usize` specifying the width.
394 //!
395 //! ## Precision
396 //!
397 //! For non-numeric types, this can be considered a "maximum width". If the resulting string is
398 //! longer than this width, then it is truncated down to this many characters and only those are
399 //! emitted.
400 //!
401 //! For integral types, this is ignored.
402 //!
403 //! For floating-point types, this indicates how many digits after the decimal point should be
404 //! printed.
405 //!
406 //! There are three possible ways to specify the desired `precision`:
407 //!
408 //! There are three possible ways to specify the desired `precision`:
409 //! 1. An integer `.N`,
410 //! 2. an integer followed by dollar sign `.N$`, or
411 //! 3. an asterisk `.*`.
412 //!
413 //! The first specification, `.N`, means the integer `N` itself is the precision.
414 //!
415 //! The second, `.N$`, means use format *argument* `N` (which must be a `usize`) as the precision.
416 //!
417 //! Finally,  `.*` means that this `{...}` is associated with *two* format inputs rather than one:
418 //! the first input holds the `usize` precision, and the second holds the value to print.  Note
419 //! that in this case, if one uses the format string `{<arg>:<spec>.*}`, then the `<arg>` part
420 //! refers to the *value* to print, and the `precision` must come in the input preceding `<arg>`.
421 //!
422 //! For example, these:
423 //!
424 //! ```
425 //! // Hello {arg 0 (x)} is {arg 1 (0.01} with precision specified inline (5)}
426 //! println!("Hello {0} is {1:.5}", "x", 0.01);
427 //!
428 //! // Hello {arg 1 (x)} is {arg 2 (0.01} with precision specified in arg 0 (5)}
429 //! println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
430 //!
431 //! // Hello {arg 0 (x)} is {arg 2 (0.01} with precision specified in arg 1 (5)}
432 //! println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
433 //!
434 //! // Hello {next arg (x)} is {second of next two args (0.01} with precision
435 //! //                          specified in first of next two args (5)}
436 //! println!("Hello {} is {:.*}",    "x", 5, 0.01);
437 //!
438 //! // Hello {next arg (x)} is {arg 2 (0.01} with precision
439 //! //                          specified in its predecessor (5)}
440 //! println!("Hello {} is {2:.*}",   "x", 5, 0.01);
441 //! ```
442 //!
443 //! All print the same thing:
444 //!
445 //! ```text
446 //! Hello x is 0.01000
447 //! ```
448 //!
449 //! While these:
450 //!
451 //! ```
452 //! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56);
453 //! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56");
454 //! ```
455 //!
456 //! print two significantly different things:
457 //!
458 //! ```text
459 //! Hello, `1234.560` has 3 fractional digits
460 //! Hello, `123` has 3 characters
461 //! ```
462 //!
463 //! # Escaping
464 //!
465 //! The literal characters `{` and `}` may be included in a string by preceding
466 //! them with the same character. For example, the `{` character is escaped with
467 //! `{{` and the `}` character is escaped with `}}`.
468
469 #![stable(feature = "rust1", since = "1.0.0")]
470
471 pub use core::fmt::{Formatter, Result, Write, rt};
472 pub use core::fmt::{Octal, Binary};
473 pub use core::fmt::{Display, Debug};
474 pub use core::fmt::{LowerHex, UpperHex, Pointer};
475 pub use core::fmt::{LowerExp, UpperExp};
476 pub use core::fmt::Error;
477 pub use core::fmt::{ArgumentV1, Arguments, write, radix, Radix, RadixFmt};
478
479 use string;
480
481 /// The format function takes a precompiled format string and a list of
482 /// arguments, to return the resulting formatted string.
483 ///
484 /// # Arguments
485 ///
486 ///   * args - a structure of arguments generated via the `format_args!` macro.
487 ///
488 /// # Examples
489 ///
490 /// ```
491 /// use std::fmt;
492 ///
493 /// let s = fmt::format(format_args!("Hello, {}!", "world"));
494 /// assert_eq!(s, "Hello, world!".to_string());
495 /// ```
496 #[stable(feature = "rust1", since = "1.0.0")]
497 pub fn format(args: Arguments) -> string::String {
498     let mut output = string::String::new();
499     let _ = output.write_fmt(args);
500     output
501 }