]> git.proxmox.com Git - rustc.git/blob - src/libcollections/fmt.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.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 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.
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.
107 //! Namely, the `{:.*}` syntax, which sets the number of numbers after the
108 //! decimal in floating-point types:
109 //!
110 //! ```
111 //! let formatted_number = format!("{:.*}", 2, 1.234567);
112 //!
113 //! assert_eq!("1.23", formatted_number)
114 //! ```
115 //!
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:
121 //!
122 //! ```text
123 //! {:.*} {0}
124 //! ```
125 //!
126 //! ## Formatting traits
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
131 //! well as `isize`). The current mapping of types to traits is:
132 //!
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)
142 //!
143 //! What this means is that any type of argument which implements the
144 //! `fmt::Binary` trait can then be formatted with `{:b}`. Implementations
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}`),
147 //! then the format trait used is the `Display` trait.
148 //!
149 //! When implementing a format trait for your own type, you will have to
150 //! implement a method of the signature:
151 //!
152 //! ```
153 //! # #![allow(dead_code)]
154 //! # use std::fmt;
155 //! # struct Foo; // our custom type
156 //! # impl fmt::Display for Foo {
157 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
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
170 //! typedef to `Result<(), std::io::Error>` (also known as `std::io::Result<()>`).
171 //! Formatting implementations should ensure that they return errors from `write!`
172 //! correctly (propagating errors upward).
173 //!
174 //! An example of implementing the formatting traits would look
175 //! like:
176 //!
177 //! ```
178 //! use std::fmt;
179 //!
180 //! #[derive(Debug)]
181 //! struct Vector2D {
182 //! x: isize,
183 //! y: isize,
184 //! }
185 //!
186 //! impl fmt::Display for Vector2D {
187 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188 //! // The `f` value implements the `Write` trait, which is what the
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
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.
206 //! let decimals = f.precision().unwrap_or(3);
207 //! let string = format!("{:.*}", decimals, magnitude);
208 //! f.pad_integral(true, "", &string)
209 //! }
210 //! }
211 //!
212 //! fn main() {
213 //! let myvector = Vector2D { x: 3, y: 4 };
214 //!
215 //! println!("{}", myvector); // => "(3, 4)"
216 //! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}"
217 //! println!("{:10.3b}", myvector); // => " 5.000"
218 //! }
219 //! ```
220 //!
221 //! ### `fmt::Display` vs `fmt::Debug`
222 //!
223 //! These two formatting traits have distinct purposes:
224 //!
225 //! - `fmt::Display` implementations assert that the type can be faithfully
226 //! represented as a UTF-8 string at all times. It is **not** expected that
227 //! all types implement the `Display` trait.
228 //! - `fmt::Debug` implementations should be implemented for **all** public types.
229 //! Output will typically represent the internal state as faithfully as possible.
230 //! The purpose of the `Debug` trait is to facilitate debugging Rust code. In
231 //! most cases, using `#[derive(Debug)]` is sufficient and recommended.
232 //!
233 //! Some examples of the output from both traits:
234 //!
235 //! ```
236 //! assert_eq!(format!("{} {:?}", 3, 4), "3 4");
237 //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
238 //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
239 //! ```
240 //!
241 //! ## Related macros
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
248 //! write! // first argument is a &mut io::Write, the destination
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 //!
255 //! ### `write!`
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 //!
263 //! ```
264 //! # #![allow(unused_must_use)]
265 //! use std::io::Write;
266 //! let mut w = Vec::new();
267 //! write!(&mut w, "Hello {}!", "world");
268 //! ```
269 //!
270 //! ### `print!`
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 //!
276 //! ```
277 //! print!("Hello {}!", "world");
278 //! println!("I have a newline {}", "character at the end");
279 //! ```
280 //!
281 //! ### `format_args!`
282 //!
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 //! ```
291 //! # #![allow(unused_must_use)]
292 //! use std::fmt;
293 //! use std::io::{self, Write};
294 //!
295 //! fmt::format(format_args!("this returns {}", "String"));
296 //!
297 //! let mut some_writer = io::stdout();
298 //! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro"));
299 //!
300 //! fn my_fmt_fn(args: fmt::Arguments) {
301 //! write!(&mut io::stdout(), "{}", args);
302 //! }
303 //! my_fmt_fn(format_args!("or a {} too", "function"));
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 //!
316 //! # Syntax
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 //!
339 //! # Formatting Parameters
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 //!
346 //! ## Fill/Alignment
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 the
352 //! following 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 //!
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 //!
362 //! ## Sign/`#`/`0`
363 //!
364 //! These can all be interpreted as flags for a particular formatter.
365 //!
366 //! * `+` - This is intended for numeric types and indicates that the sign
367 //! should always be printed. Positive signs are never printed by
368 //! default, and the negative sign is only printed by default for the
369 //! `Signed` trait. This flag indicates that the correct sign (`+` or `-`)
370 //! should always be printed.
371 //! * `-` - Currently not used
372 //! * `#` - This flag is indicates that the "alternate" form of printing should
373 //! be used. The alternate forms are:
374 //! * `#?` - pretty-print the `Debug` formatting
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
380 //! both be done with a `0` character as well as be sign-aware. A format
381 //! like `{:08}` would yield `00000001` for the integer `1`, while the
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 //!
385 //! ## Width
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
394 //! the `0` flag is specified for numerics, then the implicit fill character is
395 //! `0`.
396 //!
397 //! The value for the width can also be provided as a `usize` in the list of
398 //! parameters by using the `2$` syntax indicating that the second argument is a
399 //! `usize` specifying the width.
400 //!
401 //! ## Precision
402 //!
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.
406 //!
407 //! For integral types, this is ignored.
408 //!
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 //!
414 //! 1. An integer `.N`:
415 //!
416 //! the integer `N` itself is the precision.
417 //!
418 //! 2. An integer followed by dollar sign `.N$`:
419 //!
420 //! use format *argument* `N` (which must be a `usize`) as the precision.
421 //!
422 //! 3. An asterisk `.*`:
423 //!
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>`.
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 //! ```
469 //!
470 //! # Escaping
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
476 #![stable(feature = "rust1", since = "1.0.0")]
477
478 #[unstable(feature = "fmt_internals", issue = "0")]
479 pub use core::fmt::rt;
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub use core::fmt::{Formatter, Result, Write};
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub use core::fmt::{Octal, Binary};
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub use core::fmt::{Display, Debug};
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub use core::fmt::{LowerHex, UpperHex, Pointer};
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub use core::fmt::{LowerExp, UpperExp};
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub use core::fmt::Error;
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub use core::fmt::{ArgumentV1, Arguments, write};
494 #[stable(feature = "rust1", since = "1.0.0")]
495 pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
496
497 use string;
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 ///
506 /// # Examples
507 ///
508 /// ```
509 /// use std::fmt;
510 ///
511 /// let s = fmt::format(format_args!("Hello, {}!", "world"));
512 /// assert_eq!(s, "Hello, world!".to_string());
513 /// ```
514 #[stable(feature = "rust1", since = "1.0.0")]
515 pub fn format(args: Arguments) -> string::String {
516 let mut output = string::String::new();
517 let _ = output.write_fmt(args);
518 output
519 }