(index<- ) ./libstd/fmt/mod.rs
git branch: * master 5200215 auto merge of #14035 : alexcrichton/rust/experimental, r=huonw
modified: Fri May 9 13:02:28 2014
1 // Copyright 2013-2014 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 /*!
12
13 Utilities for formatting and printing strings
14
15 This module contains the runtime support for the `format!` syntax extension.
16 This macro is implemented in the compiler to emit calls to this module in order
17 to format arguments at runtime into strings and streams.
18
19 The functions contained in this module should not normally be used in everyday
20 use cases of `format!`. The assumptions made by these functions are unsafe for
21 all inputs, and the compiler performs a large amount of validation on the
22 arguments to `format!` in order to ensure safety at runtime. While it is
23 possible to call these functions directly, it is not recommended to do so in the
24 general case.
25
26 ## Usage
27
28 The `format!` macro is intended to be familiar to those coming from C's
29 printf/fprintf functions or Python's `str.format` function. In its current
30 revision, the `format!` macro returns a `~str` type which is the result of the
31 formatting. In the future it will also be able to pass in a stream to format
32 arguments directly while performing minimal allocations.
33
34 Some examples of the `format!` extension are:
35
36 ```rust
37 format!("Hello"); // => "Hello".to_owned()
38 format!("Hello, {:s}!", "world"); // => "Hello, world!".to_owned()
39 format!("The number is {:d}", 1); // => "The number is 1".to_owned()
40 format!("{:?}", ~[3, 4]); // => "~[3, 4]".to_owned()
41 format!("{value}", value=4); // => "4".to_owned()
42 format!("{} {}", 1, 2); // => "1 2".to_owned()
43 ```
44
45 From these, you can see that the first argument is a format string. It is
46 required by the compiler for this to be a string literal; it cannot be a
47 variable passed in (in order to perform validity checking). The compiler will
48 then parse the format string and determine if the list of arguments provided is
49 suitable to pass to this format string.
50
51 ### Positional parameters
52
53 Each formatting argument is allowed to specify which value argument it's
54 referencing, and if omitted it is assumed to be "the next argument". For
55 example, the format string `{} {} {}` would take three parameters, and they
56 would be formatted in the same order as they're given. The format string
57 `{2} {1} {0}`, however, would format arguments in reverse order.
58
59 Things can get a little tricky once you start intermingling the two types of
60 positional specifiers. The "next argument" specifier can be thought of as an
61 iterator over the argument. Each time a "next argument" specifier is seen, the
62 iterator advances. This leads to behavior like this:
63
64 ```rust
65 format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2".to_owned()
66 ```
67
68 The internal iterator over the argument has not been advanced by the time the
69 first `{}` is seen, so it prints the first argument. Then upon reaching the
70 second `{}`, the iterator has advanced forward to the second argument.
71 Essentially, parameters which explicitly name their argument do not affect
72 parameters which do not name an argument in terms of positional specifiers.
73
74 A format string is required to use all of its arguments, otherwise it is a
75 compile-time error. You may refer to the same argument more than once in the
76 format string, although it must always be referred to with the same type.
77
78 ### Named parameters
79
80 Rust itself does not have a Python-like equivalent of named parameters to a
81 function, but the `format!` macro is a syntax extension which allows it to
82 leverage named parameters. Named parameters are listed at the end of the
83 argument list and have the syntax:
84
85 ```notrust
86 identifier '=' expression
87 ```
88
89 For example, the following `format!` expressions all use named argument:
90
91 ```rust
92 format!("{argument}", argument = "test"); // => "test".to_owned()
93 format!("{name} {}", 1, name = 2); // => "2 1".to_owned()
94 format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3); // => "a 3 ()".to_owned()
95 ```
96
97 It is illegal to put positional parameters (those without names) after arguments
98 which have names. Like positional parameters, it is illegal to provided named
99 parameters that are unused by the format string.
100
101 ### Argument types
102
103 Each argument's type is dictated by the format string. It is a requirement that
104 every argument is only ever referred to by one type. When specifying the format
105 of an argument, however, a string like `{}` indicates no type. This is allowed,
106 and if all references to one argument do not provide a type, then the format `?`
107 is used (the type's rust-representation is printed). For example, this is an
108 invalid format string:
109
110 ```notrust
111 {0:d} {0:s}
112 ```
113
114 Because the first argument is both referred to as an integer as well as a
115 string.
116
117 Because formatting is done via traits, there is no requirement that the
118 `d` format actually takes an `int`, but rather it simply requires a type which
119 ascribes to the `Signed` formatting trait. There are various parameters which do
120 require a particular type, however. Namely if the syntax `{:.*s}` is used, then
121 the number of characters to print from the string precedes the actual string and
122 must have the type `uint`. Although a `uint` can be printed with `{:u}`, it is
123 illegal to reference an argument as such. For example, this is another invalid
124 format string:
125
126 ```notrust
127 {:.*s} {0:u}
128 ```
129
130 ### Formatting traits
131
132 When requesting that an argument be formatted with a particular type, you are
133 actually requesting that an argument ascribes to a particular trait. This allows
134 multiple actual types to be formatted via `{:d}` (like `i8` as well as `int`).
135 The current mapping of types to traits is:
136
137 * `?` â `Poly`
138 * `d` â `Signed`
139 * `i` â `Signed`
140 * `u` â `Unsigned`
141 * `b` â `Bool`
142 * `c` â `Char`
143 * `o` â `Octal`
144 * `x` â `LowerHex`
145 * `X` â `UpperHex`
146 * `s` â `String`
147 * `p` â `Pointer`
148 * `t` â `Binary`
149 * `f` â `Float`
150 * `e` â `LowerExp`
151 * `E` â `UpperExp`
152 * *nothing* â `Show`
153
154 What this means is that any type of argument which implements the
155 `std::fmt::Binary` trait can then be formatted with `{:t}`. Implementations are
156 provided for these traits for a number of primitive types by the standard
157 library as well. If no format is specified (as in `{}` or `{:6}`), then the
158 format trait used is the `Show` trait. This is one of the more commonly
159 implemented traits when formatting a custom type.
160
161 When implementing a format trait for your own type, you will have to implement a
162 method of the signature:
163
164 ```rust
165 # use std;
166 # mod fmt { pub type Result = (); }
167 # struct T;
168 # trait SomeName<T> {
169 fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result;
170 # }
171 ```
172
173 Your type will be passed as `self` by-reference, and then the function should
174 emit output into the `f.buf` stream. It is up to each format trait
175 implementation to correctly adhere to the requested formatting parameters. The
176 values of these parameters will be listed in the fields of the `Formatter`
177 struct. In order to help with this, the `Formatter` struct also provides some
178 helper methods.
179
180 Additionally, the return value of this function is `fmt::Result` which is a
181 typedef to `Result<(), IoError>` (also known as `IoError<()>`). Formatting
182 implementations should ensure that they return errors from `write!` correctly
183 (propagating errors upward).
184
185 An example of implementing the formatting traits would look
186 like:
187
188 ```rust
189 use std::fmt;
190 use std::f64;
191
192 struct Vector2D {
193 x: int,
194 y: int,
195 }
196
197 impl fmt::Show for Vector2D {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 // The `f.buf` value is of the type `&mut io::Writer`, which is what the
200 // write! macro is expecting. Note that this formatting ignores the
201 // various flags provided to format strings.
202 write!(f.buf, "({}, {})", self.x, self.y)
203 }
204 }
205
206 // Different traits allow different forms of output of a type. The meaning of
207 // this format is to print the magnitude of a vector.
208 impl fmt::Binary for Vector2D {
209 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
210 let magnitude = (self.x * self.x + self.y * self.y) as f64;
211 let magnitude = magnitude.sqrt();
212
213 // Respect the formatting flags by using the helper method
214 // `pad_integral` on the Formatter object. See the method documentation
215 // for details, and the function `pad` can be used to pad strings.
216 let decimals = f.precision.unwrap_or(3);
217 let string = f64::to_str_exact(magnitude, decimals);
218 f.pad_integral(true, "", string.as_bytes())
219 }
220 }
221
222 fn main() {
223 let myvector = Vector2D { x: 3, y: 4 };
224
225 println!("{}", myvector); // => "(3, 4)"
226 println!("{:10.3t}", myvector); // => " 5.000"
227 }
228 ```
229
230 ### Related macros
231
232 There are a number of related macros in the `format!` family. The ones that are
233 currently implemented are:
234
235 ```ignore
236 format! // described above
237 write! // first argument is a &mut io::Writer, the destination
238 writeln! // same as write but appends a newline
239 print! // the format string is printed to the standard output
240 println! // same as print but appends a newline
241 format_args! // described below.
242 ```
243
244
245 #### `write!`
246
247 This and `writeln` are two macros which are used to emit the format string to a
248 specified stream. This is used to prevent intermediate allocations of format
249 strings and instead directly write the output. Under the hood, this function is
250 actually invoking the `write` function defined in this module. Example usage is:
251
252 ```rust
253 # #![allow(unused_must_use)]
254 use std::io;
255
256 let mut w = io::MemWriter::new();
257 write!(&mut w as &mut io::Writer, "Hello {}!", "world");
258 ```
259
260 #### `print!`
261
262 This and `println` emit their output to stdout. Similarly to the `write!` macro,
263 the goal of these macros is to avoid intermediate allocations when printing
264 output. Example usage is:
265
266 ```rust
267 print!("Hello {}!", "world");
268 println!("I have a newline {}", "character at the end");
269 ```
270
271 #### `format_args!`
272 This is a curious macro which is used to safely pass around
273 an opaque object describing the format string. This object
274 does not require any heap allocations to create, and it only
275 references information on the stack. Under the hood, all of
276 the related macros are implemented in terms of this. First
277 off, some example usage is:
278
279 ```
280 use std::fmt;
281 use std::io;
282
283 # #[allow(unused_must_use)]
284 # fn main() {
285 format_args!(fmt::format, "this returns {}", "~str");
286
287 let some_writer: &mut io::Writer = &mut io::stdout();
288 format_args!(|args| { fmt::write(some_writer, args) }, "print with a {}", "closure");
289
290 fn my_fmt_fn(args: &fmt::Arguments) {
291 fmt::write(&mut io::stdout(), args);
292 }
293 format_args!(my_fmt_fn, "or a {} too", "function");
294 # }
295 ```
296
297 The first argument of the `format_args!` macro is a function (or closure) which
298 takes one argument of type `&fmt::Arguments`. This structure can then be
299 passed to the `write` and `format` functions inside this module in order to
300 process the format string. The goal of this macro is to even further prevent
301 intermediate allocations when dealing formatting strings.
302
303 For example, a logging library could use the standard formatting syntax, but it
304 would internally pass around this structure until it has been determined where
305 output should go to.
306
307 It is unsafe to programmatically create an instance of `fmt::Arguments` because
308 the operations performed when executing a format string require the compile-time
309 checks provided by the compiler. The `format_args!` macro is the only method of
310 safely creating these structures, but they can be unsafely created with the
311 constructor provided.
312
313 ## Internationalization
314
315 The formatting syntax supported by the `format!` extension supports
316 internationalization by providing "methods" which execute various different
317 outputs depending on the input. The syntax and methods provided are similar to
318 other internationalization systems, so again nothing should seem alien.
319 Currently two methods are supported by this extension: "select" and "plural".
320
321 Each method will execute one of a number of clauses, and then the value of the
322 clause will become what's the result of the argument's format. Inside of the
323 cases, nested argument strings may be provided, but all formatting arguments
324 must not be done through implicit positional means. All arguments inside of each
325 case of a method must be explicitly selected by their name or their integer
326 position.
327
328 Furthermore, whenever a case is running, the special character `#` can be used
329 to reference the string value of the argument which was selected upon. As an
330 example:
331
332 ```rust
333 format!("{0, select, other{#}}", "hello"); // => "hello".to_owned()
334 ```
335
336 This example is the equivalent of `{0:s}` essentially.
337
338 ### Select
339
340 The select method is a switch over a `&str` parameter, and the parameter *must*
341 be of the type `&str`. An example of the syntax is:
342
343 ```notrust
344 {0, select, male{...} female{...} other{...}}
345 ```
346
347 Breaking this down, the `0`-th argument is selected upon with the `select`
348 method, and then a number of cases follow. Each case is preceded by an
349 identifier which is the match-clause to execute the given arm. In this case,
350 there are two explicit cases, `male` and `female`. The case will be executed if
351 the string argument provided is an exact match to the case selected.
352
353 The `other` case is also a required case for all `select` methods. This arm will
354 be executed if none of the other arms matched the word being selected over.
355
356 ### Plural
357
358 The plural method is a switch statement over a `uint` parameter, and the
359 parameter *must* be a `uint`. A plural method in its full glory can be specified
360 as:
361
362 ```notrust
363 {0, plural, offset=1 =1{...} two{...} many{...} other{...}}
364 ```
365
366 To break this down, the first `0` indicates that this method is selecting over
367 the value of the first positional parameter to the format string. Next, the
368 `plural` method is being executed. An optionally-supplied `offset` is then given
369 which indicates a number to subtract from argument `0` when matching. This is
370 then followed by a list of cases.
371
372 Each case is allowed to supply a specific value to match upon with the syntax
373 `=N`. This case is executed if the value at argument `0` matches N exactly,
374 without taking the offset into account. A case may also be specified by one of
375 five keywords: `zero`, `one`, `two`, `few`, and `many`. These cases are matched
376 on after argument `0` has the offset taken into account. Currently the
377 definitions of `many` and `few` are hardcoded, but they are in theory defined by
378 the current locale.
379
380 Finally, all `plural` methods must have an `other` case supplied which will be
381 executed if none of the other cases match.
382
383 ## Syntax
384
385 The syntax for the formatting language used is drawn from other languages, so it
386 should not be too alien. Arguments are formatted with python-like syntax,
387 meaning that arguments are surrounded by `{}` instead of the C-like `%`. The
388 actual grammar for the formatting syntax is:
389
390 ```notrust
391 format_string := <text> [ format <text> ] *
392 format := '{' [ argument ] [ ':' format_spec ] [ ',' function_spec ] '}'
393 argument := integer | identifier
394
395 format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
396 fill := character
397 align := '<' | '>'
398 sign := '+' | '-'
399 width := count
400 precision := count | '*'
401 type := identifier | ''
402 count := parameter | integer
403 parameter := integer '$'
404
405 function_spec := plural | select
406 select := 'select' ',' ( identifier arm ) *
407 plural := 'plural' ',' [ 'offset:' integer ] ( selector arm ) *
408 selector := '=' integer | keyword
409 keyword := 'zero' | 'one' | 'two' | 'few' | 'many' | 'other'
410 arm := '{' format_string '}'
411 ```
412
413 ## Formatting Parameters
414
415 Each argument being formatted can be transformed by a number of formatting
416 parameters (corresponding to `format_spec` in the syntax above). These
417 parameters affect the string representation of what's being formatted. This
418 syntax draws heavily from Python's, so it may seem a bit familiar.
419
420 ### Fill/Alignment
421
422 The fill character is provided normally in conjunction with the `width`
423 parameter. This indicates that if the value being formatted is smaller than
424 `width` some extra characters will be printed around it. The extra characters
425 are specified by `fill`, and the alignment can be one of two options:
426
427 * `<` - the argument is left-aligned in `width` columns
428 * `>` - the argument is right-aligned in `width` columns
429
430 ### Sign/#/0
431
432 These can all be interpreted as flags for a particular formatter.
433
434 * '+' - This is intended for numeric types and indicates that the sign should
435 always be printed. Positive signs are never printed by default, and the
436 negative sign is only printed by default for the `Signed` trait. This
437 flag indicates that the correct sign (+ or -) should always be printed.
438 * '-' - Currently not used
439 * '#' - This flag is indicates that the "alternate" form of printing should be
440 used. By default, this only applies to the integer formatting traits and
441 performs like:
442 * `x` - precedes the argument with a "0x"
443 * `X` - precedes the argument with a "0x"
444 * `t` - precedes the argument with a "0b"
445 * `o` - precedes the argument with a "0o"
446 * '0' - This is used to indicate for integer formats that the padding should
447 both be done with a `0` character as well as be sign-aware. A format
448 like `{:08d}` would yield `00000001` for the integer `1`, while the same
449 format would yield `-0000001` for the integer `-1`. Notice that the
450 negative version has one fewer zero than the positive version.
451
452 ### Width
453
454 This is a parameter for the "minimum width" that the format should take up. If
455 the value's string does not fill up this many characters, then the padding
456 specified by fill/alignment will be used to take up the required space.
457
458 The default fill/alignment for non-numerics is a space and left-aligned. The
459 defaults for numeric formatters is also a space but with right-alignment. If the
460 '0' flag is specified for numerics, then the implicit fill character is '0'.
461
462 The value for the width can also be provided as a `uint` in the list of
463 parameters by using the `2$` syntax indicating that the second argument is a
464 `uint` specifying the width.
465
466 ### Precision
467
468 For non-numeric types, this can be considered a "maximum width". If the
469 resulting string is longer than this width, then it is truncated down to this
470 many characters and only those are emitted.
471
472 For integral types, this has no meaning currently.
473
474 For floating-point types, this indicates how many digits after the decimal point
475 should be printed.
476
477 ## Escaping
478
479 The literal characters `{`, `}`, or `#` may be included in a string by
480 preceding them with the `\` character. Since `\` is already an
481 escape character in Rust strings, a string literal using this escape
482 will look like `"\\{"`.
483
484 */
485
486 use any;
487 use cast;
488 use cell::Cell;
489 use char::Char;
490 use cmp;
491 use container::Container;
492 use io::MemWriter;
493 use io;
494 use iter;
495 use iter::{Iterator, range};
496 use kinds::Copy;
497 use num::Signed;
498 use option::{Option, Some, None};
499 use owned::Box;
500 use repr;
501 use result::{Ok, Err, ResultUnwrap};
502 use str::{StrSlice, StrAllocating, UTF16Item, ScalarValue, LoneSurrogate};
503 use str;
504 use slice::{Vector, ImmutableVector};
505 use slice;
506 use intrinsics::TypeId;
507
508 pub use self::num::radix;
509 pub use self::num::Radix;
510 pub use self::num::RadixFmt;
511
512 mod num;
513 pub mod rt;
514
515 #[cfg(stage0)]
516 #[allow(missing_doc)]
517 pub mod parse {
518 #[deriving(Eq)]
519 pub enum Alignment {
520 AlignLeft,
521 AlignRight,
522 AlignUnknown,
523 }
524
525 pub enum PluralKeyword {
526 Zero,
527 One,
528 Two,
529 Few,
530 Many,
531 }
532
533 pub enum Flag {
534 FlagSignPlus,
535 FlagSignMinus,
536 FlagAlternate,
537 FlagSignAwareZeroPad,
538 }
539 }
540
541 pub type Result = io::IoResult<()>;
542
543 /// A struct to represent both where to emit formatting strings to and how they
544 /// should be formatted. A mutable version of this is passed to all formatting
545 /// traits.
546 pub struct Formatter<'a> {
547 /// Flags for formatting (packed version of rt::Flag)
548 pub flags: uint,
549 /// Character used as 'fill' whenever there is alignment
550 pub fill: char,
551 /// Boolean indication of whether the output should be left-aligned
552 pub align: rt::Alignment,
553 /// Optionally specified integer width that the output should be
554 pub width: Option<uint>,
555 /// Optionally specified precision for numeric types
556 pub precision: Option<uint>,
557
558 /// Output buffer.
559 pub buf: &'a mut io::Writer,
560 curarg: slice::Items<'a, Argument<'a>>,
561 args: &'a [Argument<'a>],
562 }
563
564 /// This struct represents the generic "argument" which is taken by the Xprintf
565 /// family of functions. It contains a function to format the given value. At
566 /// compile time it is ensured that the function and the value have the correct
567 /// types, and then this struct is used to canonicalize arguments to one type.
568 pub struct Argument<'a> {
569 formatter: extern "Rust" fn(&any::Void, &mut Formatter) -> Result,
570 value: &'a any::Void,
571 }
572
573 impl<'a> Arguments<'a> {
574 /// When using the format_args!() macro, this function is used to generate the
575 /// Arguments structure. The compiler inserts an `unsafe` block to call this,
576 /// which is valid because the compiler performs all necessary validation to
577 /// ensure that the resulting call to format/write would be safe.
578 #[doc(hidden)] #[inline]
579 pub unsafe fn new<'a>(fmt: &'static [rt::Piece<'static>],
580 args: &'a [Argument<'a>]) -> Arguments<'a> {
581 Arguments{ fmt: cast::transmute(fmt), args: args }
582 }
583 }
584
585 /// This structure represents a safely precompiled version of a format string
586 /// and its arguments. This cannot be generated at runtime because it cannot
587 /// safely be done so, so no constructors are given and the fields are private
588 /// to prevent modification.
589 ///
590 /// The `format_args!` macro will safely create an instance of this structure
591 /// and pass it to a user-supplied function. The macro validates the format
592 /// string at compile-time so usage of the `write` and `format` functions can
593 /// be safely performed.
594 pub struct Arguments<'a> {
595 fmt: &'a [rt::Piece<'a>],
596 args: &'a [Argument<'a>],
597 }
598
599 impl<'a> Show for Arguments<'a> {
600 fn fmt(&self, fmt: &mut Formatter) -> Result {
601 write(fmt.buf, self)
602 }
603 }
604
605 /// When a format is not otherwise specified, types are formatted by ascribing
606 /// to this trait. There is not an explicit way of selecting this trait to be
607 /// used for formatting, it is only if no other format is specified.
608 pub trait Show {
609 /// Formats the value using the given formatter.
610 fn fmt(&self, &mut Formatter) -> Result;
611 }
612
613 /// Format trait for the `b` character
614 pub trait Bool {
615 /// Formats the value using the given formatter.
616 fn fmt(&self, &mut Formatter) -> Result;
617 }
618
619 /// Format trait for the `c` character
620 pub trait Char {
621 /// Formats the value using the given formatter.
622 fn fmt(&self, &mut Formatter) -> Result;
623 }
624
625 /// Format trait for the `i` and `d` characters
626 pub trait Signed {
627 /// Formats the value using the given formatter.
628 fn fmt(&self, &mut Formatter) -> Result;
629 }
630
631 /// Format trait for the `u` character
632 pub trait Unsigned {
633 /// Formats the value using the given formatter.
634 fn fmt(&self, &mut Formatter) -> Result;
635 }
636
637 /// Format trait for the `o` character
638 pub trait Octal {
639 /// Formats the value using the given formatter.
640 fn fmt(&self, &mut Formatter) -> Result;
641 }
642
643 /// Format trait for the `t` character
644 pub trait Binary {
645 /// Formats the value using the given formatter.
646 fn fmt(&self, &mut Formatter) -> Result;
647 }
648
649 /// Format trait for the `x` character
650 pub trait LowerHex {
651 /// Formats the value using the given formatter.
652 fn fmt(&self, &mut Formatter) -> Result;
653 }
654
655 /// Format trait for the `X` character
656 pub trait UpperHex {
657 /// Formats the value using the given formatter.
658 fn fmt(&self, &mut Formatter) -> Result;
659 }
660
661 /// Format trait for the `s` character
662 pub trait String {
663 /// Formats the value using the given formatter.
664 fn fmt(&self, &mut Formatter) -> Result;
665 }
666
667 /// Format trait for the `?` character
668 pub trait Poly {
669 /// Formats the value using the given formatter.
670 fn fmt(&self, &mut Formatter) -> Result;
671 }
672
673 /// Format trait for the `p` character
674 pub trait Pointer {
675 /// Formats the value using the given formatter.
676 fn fmt(&self, &mut Formatter) -> Result;
677 }
678
679 /// Format trait for the `f` character
680 pub trait Float {
681 /// Formats the value using the given formatter.
682 fn fmt(&self, &mut Formatter) -> Result;
683 }
684
685 /// Format trait for the `e` character
686 pub trait LowerExp {
687 /// Formats the value using the given formatter.
688 fn fmt(&self, &mut Formatter) -> Result;
689 }
690
691 /// Format trait for the `E` character
692 pub trait UpperExp {
693 /// Formats the value using the given formatter.
694 fn fmt(&self, &mut Formatter) -> Result;
695 }
696
697 // FIXME #11938 - UFCS would make us able call the above methods
698 // directly Show::show(x, fmt).
699 macro_rules! uniform_fn_call_workaround {
700 ($( $name: ident, $trait_: ident; )*) => {
701 $(
702 #[doc(hidden)]
703 pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704 x.fmt(fmt)
705 }
706 )*
707 }
708 }
709 uniform_fn_call_workaround! {
710 secret_show, Show;
711 secret_bool, Bool;
712 secret_char, Char;
713 secret_signed, Signed;
714 secret_unsigned, Unsigned;
715 secret_octal, Octal;
716 secret_binary, Binary;
717 secret_lower_hex, LowerHex;
718 secret_upper_hex, UpperHex;
719 secret_string, String;
720 secret_poly, Poly;
721 secret_pointer, Pointer;
722 secret_float, Float;
723 secret_lower_exp, LowerExp;
724 secret_upper_exp, UpperExp;
725 }
726
727 /// The `write` function takes an output stream, a precompiled format string,
728 /// and a list of arguments. The arguments will be formatted according to the
729 /// specified format string into the output stream provided.
730 ///
731 /// # Arguments
732 ///
733 /// * output - the buffer to write output to
734 /// * args - the precompiled arguments generated by `format_args!`
735 ///
736 /// # Example
737 ///
738 /// ```rust
739 /// # #![allow(unused_must_use)]
740 /// use std::fmt;
741 /// use std::io;
742 ///
743 /// let mut w = io::stdout();
744 /// format_args!(|args| { fmt::write(&mut w, args); }, "Hello, {}!", "world");
745 /// ```
746 pub fn write(output: &mut io::Writer, args: &Arguments) -> Result {
747 unsafe { write_unsafe(output, args.fmt, args.args) }
748 }
749
750 /// The `writeln` function takes the same arguments as `write`, except that it
751 /// will also write a newline (`\n`) character at the end of the format string.
752 pub fn writeln(output: &mut io::Writer, args: &Arguments) -> Result {
753 let first = unsafe { write_unsafe(output, args.fmt, args.args) };
754 first.and_then(|()| output.write(['\n' as u8]))
755 }
756
757 /// The `write_unsafe` function takes an output stream, a precompiled format
758 /// string, and a list of arguments. The arguments will be formatted according
759 /// to the specified format string into the output stream provided.
760 ///
761 /// See the documentation for `format` for why this function is unsafe and care
762 /// should be taken if calling it manually.
763 ///
764 /// Thankfully the rust compiler provides macros like `write!` and
765 /// `format_args!` which perform all of this validation at compile-time
766 /// and provide a safe interface for invoking this function.
767 ///
768 /// # Arguments
769 ///
770 /// * output - the buffer to write output to
771 /// * fmts - the precompiled format string to emit
772 /// * args - the list of arguments to the format string. These are only the
773 /// positional arguments (not named)
774 ///
775 /// Note that this function assumes that there are enough arguments for the
776 /// format string.
777 pub unsafe fn write_unsafe(output: &mut io::Writer,
778 fmt: &[rt::Piece],
779 args: &[Argument]) -> Result {
780 let mut formatter = Formatter {
781 flags: 0,
782 width: None,
783 precision: None,
784 buf: output,
785 align: rt::AlignUnknown,
786 fill: ' ',
787 args: args,
788 curarg: args.iter(),
789 };
790 for piece in fmt.iter() {
791 try!(formatter.run(piece, None));
792 }
793 Ok(())
794 }
795
796 /// The format function takes a precompiled format string and a list of
797 /// arguments, to return the resulting formatted string.
798 ///
799 /// # Arguments
800 ///
801 /// * args - a structure of arguments generated via the `format_args!` macro.
802 /// Because this structure can only be safely generated at
803 /// compile-time, this function is safe.
804 ///
805 /// # Example
806 ///
807 /// ```rust
808 /// use std::fmt;
809 ///
810 /// let s = format_args!(fmt::format, "Hello, {}!", "world");
811 /// assert_eq!(s, "Hello, world!".to_owned());
812 /// ```
813 pub fn format(args: &Arguments) -> ~str {
814 unsafe { format_unsafe(args.fmt, args.args) }
815 }
816
817 /// The unsafe version of the formatting function.
818 ///
819 /// This is currently an unsafe function because the types of all arguments
820 /// aren't verified by immediate callers of this function. This currently does
821 /// not validate that the correct types of arguments are specified for each
822 /// format specifier, nor that each argument itself contains the right function
823 /// for formatting the right type value. Because of this, the function is marked
824 /// as `unsafe` if this is being called manually.
825 ///
826 /// Thankfully the rust compiler provides the macro `format!` which will perform
827 /// all of this validation at compile-time and provides a safe interface for
828 /// invoking this function.
829 ///
830 /// # Arguments
831 ///
832 /// * fmts - the precompiled format string to emit.
833 /// * args - the list of arguments to the format string. These are only the
834 /// positional arguments (not named)
835 ///
836 /// Note that this function assumes that there are enough arguments for the
837 /// format string.
838 pub unsafe fn format_unsafe(fmt: &[rt::Piece], args: &[Argument]) -> ~str {
839 let mut output = MemWriter::new();
840 write_unsafe(&mut output as &mut io::Writer, fmt, args).unwrap();
841 return str::from_utf8(output.unwrap().as_slice()).unwrap().to_owned();
842 }
843
844 impl<'a> Formatter<'a> {
845
846 // First up is the collection of functions used to execute a format string
847 // at runtime. This consumes all of the compile-time statics generated by
848 // the format! syntax extension.
849
850 fn run(&mut self, piece: &rt::Piece, cur: Option<&str>) -> Result {
851 match *piece {
852 rt::String(s) => self.buf.write(s.as_bytes()),
853 rt::CurrentArgument(()) => self.buf.write(cur.unwrap().as_bytes()),
854 rt::Argument(ref arg) => {
855 // Fill in the format parameters into the formatter
856 self.fill = arg.format.fill;
857 self.align = arg.format.align;
858 self.flags = arg.format.flags;
859 self.width = self.getcount(&arg.format.width);
860 self.precision = self.getcount(&arg.format.precision);
861
862 // Extract the correct argument
863 let value = match arg.position {
864 rt::ArgumentNext => { *self.curarg.next().unwrap() }
865 rt::ArgumentIs(i) => self.args[i],
866 };
867
868 // Then actually do some printing
869 match arg.method {
870 None => (value.formatter)(value.value, self),
871 Some(ref method) => self.execute(*method, value)
872 }
873 }
874 }
875 }
876
877 fn getcount(&mut self, cnt: &rt::Count) -> Option<uint> {
878 match *cnt {
879 rt::CountIs(n) => { Some(n) }
880 rt::CountImplied => { None }
881 rt::CountIsParam(i) => {
882 let v = self.args[i].value;
883 unsafe { Some(*(v as *any::Void as *uint)) }
884 }
885 rt::CountIsNextParam => {
886 let v = self.curarg.next().unwrap().value;
887 unsafe { Some(*(v as *any::Void as *uint)) }
888 }
889 }
890 }
891
892 fn execute(&mut self, method: &rt::Method, arg: Argument) -> Result {
893 match *method {
894 // Pluralization is selection upon a numeric value specified as the
895 // parameter.
896 rt::Plural(offset, ref selectors, ref default) => {
897 // This is validated at compile-time to be a pointer to a
898 // '&uint' value.
899 let value: &uint = unsafe { cast::transmute(arg.value) };
900 let value = *value;
901
902 // First, attempt to match against explicit values without the
903 // offsetted value
904 for s in selectors.iter() {
905 match s.selector {
906 rt::Literal(val) if value == val => {
907 return self.runplural(value, s.result);
908 }
909 _ => {}
910 }
911 }
912
913 // Next, offset the value and attempt to match against the
914 // keyword selectors.
915 let value = value - match offset { Some(i) => i, None => 0 };
916 for s in selectors.iter() {
917 let run = match s.selector {
918 rt::Keyword(rt::Zero) => value == 0,
919 rt::Keyword(rt::One) => value == 1,
920 rt::Keyword(rt::Two) => value == 2,
921
922 // FIXME: Few/Many should have a user-specified boundary
923 // One possible option would be in the function
924 // pointer of the 'arg: Argument' struct.
925 rt::Keyword(rt::Few) => value < 8,
926 rt::Keyword(rt::Many) => value >= 8,
927
928 rt::Literal(..) => false
929 };
930 if run {
931 return self.runplural(value, s.result);
932 }
933 }
934
935 self.runplural(value, *default)
936 }
937
938 // Select is just a matching against the string specified.
939 rt::Select(ref selectors, ref default) => {
940 // This is validated at compile-time to be a pointer to a
941 // string slice,
942 let value: & &str = unsafe { cast::transmute(arg.value) };
943 let value = *value;
944
945 for s in selectors.iter() {
946 if s.selector == value {
947 for piece in s.result.iter() {
948 try!(self.run(piece, Some(value)));
949 }
950 return Ok(());
951 }
952 }
953 for piece in default.iter() {
954 try!(self.run(piece, Some(value)));
955 }
956 Ok(())
957 }
958 }
959 }
960
961 fn runplural(&mut self, value: uint, pieces: &[rt::Piece]) -> Result {
962 ::uint::to_str_bytes(value, 10, |buf| {
963 let valuestr = str::from_utf8(buf).unwrap();
964 for piece in pieces.iter() {
965 try!(self.run(piece, Some(valuestr)));
966 }
967 Ok(())
968 })
969 }
970
971 // Helper methods used for padding and processing formatting arguments that
972 // all formatting traits can use.
973
974 /// Performs the correct padding for an integer which has already been
975 /// emitted into a byte-array. The byte-array should *not* contain the sign
976 /// for the integer, that will be added by this method.
977 ///
978 /// # Arguments
979 ///
980 /// * is_positive - whether the original integer was positive or not.
981 /// * prefix - if the '#' character (FlagAlternate) is provided, this
982 /// is the prefix to put in front of the number.
983 /// * buf - the byte array that the number has been formatted into
984 ///
985 /// This function will correctly account for the flags provided as well as
986 /// the minimum width. It will not take precision into account.
987 pub fn pad_integral(&mut self, is_positive: bool, prefix: &str, buf: &[u8]) -> Result {
988 use fmt::rt::{FlagAlternate, FlagSignPlus, FlagSignAwareZeroPad};
989
990 let mut width = buf.len();
991
992 let mut sign = None;
993 if !is_positive {
994 sign = Some('-'); width += 1;
995 } else if self.flags & (1 << (FlagSignPlus as uint)) != 0 {
996 sign = Some('+'); width += 1;
997 }
998
999 let mut prefixed = false;
1000 if self.flags & (1 << (FlagAlternate as uint)) != 0 {
1001 prefixed = true; width += prefix.len();
1002 }
1003
1004 // Writes the sign if it exists, and then the prefix if it was requested
1005 let write_prefix = |f: &mut Formatter| {
1006 for c in sign.move_iter() { try!(f.buf.write_char(c)); }
1007 if prefixed { f.buf.write_str(prefix) }
1008 else { Ok(()) }
1009 };
1010
1011 // The `width` field is more of a `min-width` parameter at this point.
1012 match self.width {
1013 // If there's no minimum length requirements then we can just
1014 // write the bytes.
1015 None => {
1016 try!(write_prefix(self)); self.buf.write(buf)
1017 }
1018 // Check if we're over the minimum width, if so then we can also
1019 // just write the bytes.
1020 Some(min) if width >= min => {
1021 try!(write_prefix(self)); self.buf.write(buf)
1022 }
1023 // The sign and prefix goes before the padding if the fill character
1024 // is zero
1025 Some(min) if self.flags & (1 << (FlagSignAwareZeroPad as uint)) != 0 => {
1026 self.fill = '0';
1027 try!(write_prefix(self));
1028 self.with_padding(min - width, rt::AlignRight, |f| f.buf.write(buf))
1029 }
1030 // Otherwise, the sign and prefix goes after the padding
1031 Some(min) => {
1032 self.with_padding(min - width, rt::AlignRight, |f| {
1033 try!(write_prefix(f)); f.buf.write(buf)
1034 })
1035 }
1036 }
1037 }
1038
1039 /// This function takes a string slice and emits it to the internal buffer
1040 /// after applying the relevant formatting flags specified. The flags
1041 /// recognized for generic strings are:
1042 ///
1043 /// * width - the minimum width of what to emit
1044 /// * fill/align - what to emit and where to emit it if the string
1045 /// provided needs to be padded
1046 /// * precision - the maximum length to emit, the string is truncated if it
1047 /// is longer than this length
1048 ///
1049 /// Notably this function ignored the `flag` parameters
1050 pub fn pad(&mut self, s: &str) -> Result {
1051 // Make sure there's a fast path up front
1052 if self.width.is_none() && self.precision.is_none() {
1053 return self.buf.write(s.as_bytes());
1054 }
1055 // The `precision` field can be interpreted as a `max-width` for the
1056 // string being formatted
1057 match self.precision {
1058 Some(max) => {
1059 // If there's a maximum width and our string is longer than
1060 // that, then we must always have truncation. This is the only
1061 // case where the maximum length will matter.
1062 let char_len = s.char_len();
1063 if char_len >= max {
1064 let nchars = ::cmp::min(max, char_len);
1065 return self.buf.write(s.slice_chars(0, nchars).as_bytes());
1066 }
1067 }
1068 None => {}
1069 }
1070 // The `width` field is more of a `min-width` parameter at this point.
1071 match self.width {
1072 // If we're under the maximum length, and there's no minimum length
1073 // requirements, then we can just emit the string
1074 None => self.buf.write(s.as_bytes()),
1075 // If we're under the maximum width, check if we're over the minimum
1076 // width, if so it's as easy as just emitting the string.
1077 Some(width) if s.char_len() >= width => {
1078 self.buf.write(s.as_bytes())
1079 }
1080 // If we're under both the maximum and the minimum width, then fill
1081 // up the minimum width with the specified string + some alignment.
1082 Some(width) => {
1083 self.with_padding(width - s.len(), rt::AlignLeft, |me| {
1084 me.buf.write(s.as_bytes())
1085 })
1086 }
1087 }
1088 }
1089
1090 /// Runs a callback, emitting the correct padding either before or
1091 /// afterwards depending on whether right or left alingment is requested.
1092 fn with_padding(&mut self,
1093 padding: uint,
1094 default: rt::Alignment,
1095 f: |&mut Formatter| -> Result) -> Result {
1096 let align = match self.align {
1097 rt::AlignUnknown => default,
1098 rt::AlignLeft | rt::AlignRight => self.align
1099 };
1100 if align == rt::AlignLeft {
1101 try!(f(self));
1102 }
1103 let mut fill = [0u8, ..4];
1104 let len = self.fill.encode_utf8(fill);
1105 for _ in range(0, padding) {
1106 try!(self.buf.write(fill.slice_to(len)));
1107 }
1108 if align == rt::AlignRight {
1109 try!(f(self));
1110 }
1111 Ok(())
1112 }
1113 }
1114
1115 /// This is a function which calls are emitted to by the compiler itself to
1116 /// create the Argument structures that are passed into the `format` function.
1117 #[doc(hidden)] #[inline]
1118 pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result,
1119 t: &'a T) -> Argument<'a> {
1120 unsafe {
1121 Argument {
1122 formatter: cast::transmute(f),
1123 value: cast::transmute(t)
1124 }
1125 }
1126 }
1127
1128 /// When the compiler determines that the type of an argument *must* be a string
1129 /// (such as for select), then it invokes this method.
1130 #[doc(hidden)] #[inline]
1131 pub fn argumentstr<'a>(s: &'a &str) -> Argument<'a> {
1132 argument(secret_string, s)
1133 }
1134
1135 /// When the compiler determines that the type of an argument *must* be a uint
1136 /// (such as for plural), then it invokes this method.
1137 #[doc(hidden)] #[inline]
1138 pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
1139 argument(secret_unsigned, s)
1140 }
1141
1142 // Implementations of the core formatting traits
1143
1144 impl<T: Show> Show for @T {
1145 fn fmt(&self, f: &mut Formatter) -> Result { secret_show(&**self, f) }
1146 }
1147 impl<T: Show> Show for Box<T> {
1148 fn fmt(&self, f: &mut Formatter) -> Result { secret_show(&**self, f) }
1149 }
1150 impl<'a, T: Show> Show for &'a T {
1151 fn fmt(&self, f: &mut Formatter) -> Result { secret_show(*self, f) }
1152 }
1153
1154 impl Bool for bool {
1155 fn fmt(&self, f: &mut Formatter) -> Result {
1156 secret_string(&(if *self {"true"} else {"false"}), f)
1157 }
1158 }
1159
1160 impl<'a, T: str::Str> String for T {
1161 fn fmt(&self, f: &mut Formatter) -> Result {
1162 f.pad(self.as_slice())
1163 }
1164 }
1165
1166 impl Char for char {
1167 fn fmt(&self, f: &mut Formatter) -> Result {
1168 let mut utf8 = [0u8, ..4];
1169 let amt = self.encode_utf8(utf8);
1170 let s: &str = unsafe { cast::transmute(utf8.slice_to(amt)) };
1171 secret_string(&s, f)
1172 }
1173 }
1174
1175 macro_rules! floating(($ty:ident) => {
1176 impl Float for $ty {
1177 fn fmt(&self, fmt: &mut Formatter) -> Result {
1178 // FIXME: this shouldn't perform an allocation
1179 let s = match fmt.precision {
1180 Some(i) => ::$ty::to_str_exact(self.abs(), i),
1181 None => ::$ty::to_str_digits(self.abs(), 6)
1182 };
1183 fmt.pad_integral(*self >= 0.0, "", s.as_bytes())
1184 }
1185 }
1186
1187 impl LowerExp for $ty {
1188 fn fmt(&self, fmt: &mut Formatter) -> Result {
1189 // FIXME: this shouldn't perform an allocation
1190 let s = match fmt.precision {
1191 Some(i) => ::$ty::to_str_exp_exact(self.abs(), i, false),
1192 None => ::$ty::to_str_exp_digits(self.abs(), 6, false)
1193 };
1194 fmt.pad_integral(*self >= 0.0, "", s.as_bytes())
1195 }
1196 }
1197
1198 impl UpperExp for $ty {
1199 fn fmt(&self, fmt: &mut Formatter) -> Result {
1200 // FIXME: this shouldn't perform an allocation
1201 let s = match fmt.precision {
1202 Some(i) => ::$ty::to_str_exp_exact(self.abs(), i, true),
1203 None => ::$ty::to_str_exp_digits(self.abs(), 6, true)
1204 };
1205 fmt.pad_integral(*self >= 0.0, "", s.as_bytes())
1206 }
1207 }
1208 })
1209 floating!(f32)
1210 floating!(f64)
1211
1212 impl<T> Poly for T {
1213 fn fmt(&self, f: &mut Formatter) -> Result {
1214 match (f.width, f.precision) {
1215 (None, None) => {
1216 repr::write_repr(f.buf, self)
1217 }
1218
1219 // If we have a specified width for formatting, then we have to make
1220 // this allocation of a new string
1221 _ => {
1222 let s = repr::repr_to_str(self);
1223 f.pad(s)
1224 }
1225 }
1226 }
1227 }
1228
1229 impl<T> Pointer for *T {
1230 fn fmt(&self, f: &mut Formatter) -> Result {
1231 f.flags |= 1 << (rt::FlagAlternate as uint);
1232 secret_lower_hex::<uint>(&(*self as uint), f)
1233 }
1234 }
1235 impl<T> Pointer for *mut T {
1236 fn fmt(&self, f: &mut Formatter) -> Result {
1237 secret_pointer::<*T>(&(*self as *T), f)
1238 }
1239 }
1240 impl<'a, T> Pointer for &'a T {
1241 fn fmt(&self, f: &mut Formatter) -> Result {
1242 secret_pointer::<*T>(&(&**self as *T), f)
1243 }
1244 }
1245 impl<'a, T> Pointer for &'a mut T {
1246 fn fmt(&self, f: &mut Formatter) -> Result {
1247 secret_pointer::<*T>(&(&**self as *T), f)
1248 }
1249 }
1250
1251 // Implementation of Show for various core types
1252
1253 macro_rules! delegate(($ty:ty to $other:ident) => {
1254 impl<'a> Show for $ty {
1255 fn fmt(&self, f: &mut Formatter) -> Result {
1256 (concat_idents!(secret_, $other)(self, f))
1257 }
1258 }
1259 })
1260 delegate!(~str to string)
1261 delegate!(&'a str to string)
1262 delegate!(bool to bool)
1263 delegate!(char to char)
1264 delegate!(f32 to float)
1265 delegate!(f64 to float)
1266
1267 impl<T> Show for *T {
1268 fn fmt(&self, f: &mut Formatter) -> Result { secret_pointer(self, f) }
1269 }
1270 impl<T> Show for *mut T {
1271 fn fmt(&self, f: &mut Formatter) -> Result { secret_pointer(self, f) }
1272 }
1273
1274 macro_rules! peel(($name:ident, $($other:ident,)*) => (tuple!($($other,)*)))
1275
1276 macro_rules! tuple (
1277 () => ();
1278 ( $($name:ident,)+ ) => (
1279 impl<$($name:Show),*> Show for ($($name,)*) {
1280 #[allow(uppercase_variables, dead_assignment)]
1281 fn fmt(&self, f: &mut Formatter) -> Result {
1282 try!(write!(f.buf, "("));
1283 let ($(ref $name,)*) = *self;
1284 let mut n = 0;
1285 $(
1286 if n > 0 {
1287 try!(write!(f.buf, ", "));
1288 }
1289 try!(write!(f.buf, "{}", *$name));
1290 n += 1;
1291 )*
1292 if n == 1 {
1293 try!(write!(f.buf, ","));
1294 }
1295 write!(f.buf, ")")
1296 }
1297 }
1298 peel!($($name,)*)
1299 )
1300 )
1301
1302 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1303
1304 impl Show for Box<any::Any> {
1305 fn fmt(&self, f: &mut Formatter) -> Result { f.pad("Box<Any>") }
1306 }
1307
1308 impl<'a> Show for &'a any::Any {
1309 fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") }
1310 }
1311
1312 impl<T: Show> Show for Option<T> {
1313 fn fmt(&self, f: &mut Formatter) -> Result {
1314 match *self {
1315 Some(ref t) => write!(f.buf, "Some({})", *t),
1316 None => write!(f.buf, "None"),
1317 }
1318 }
1319 }
1320
1321 impl<T: Show, U: Show> Show for ::result::Result<T, U> {
1322 fn fmt(&self, f: &mut Formatter) -> Result {
1323 match *self {
1324 Ok(ref t) => write!(f.buf, "Ok({})", *t),
1325 Err(ref t) => write!(f.buf, "Err({})", *t),
1326 }
1327 }
1328 }
1329
1330 impl<'a, T: Show> Show for &'a [T] {
1331 fn fmt(&self, f: &mut Formatter) -> Result {
1332 if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
1333 try!(write!(f.buf, "["));
1334 }
1335 let mut is_first = true;
1336 for x in self.iter() {
1337 if is_first {
1338 is_first = false;
1339 } else {
1340 try!(write!(f.buf, ", "));
1341 }
1342 try!(write!(f.buf, "{}", *x))
1343 }
1344 if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
1345 try!(write!(f.buf, "]"));
1346 }
1347 Ok(())
1348 }
1349 }
1350
1351 impl<'a, T: Show> Show for &'a mut [T] {
1352 fn fmt(&self, f: &mut Formatter) -> Result {
1353 secret_show(&self.as_slice(), f)
1354 }
1355 }
1356
1357 impl<T: Show> Show for ~[T] {
1358 fn fmt(&self, f: &mut Formatter) -> Result {
1359 secret_show(&self.as_slice(), f)
1360 }
1361 }
1362
1363 impl Show for () {
1364 fn fmt(&self, f: &mut Formatter) -> Result {
1365 f.pad("()")
1366 }
1367 }
1368
1369 impl Show for TypeId {
1370 fn fmt(&self, f: &mut Formatter) -> Result {
1371 write!(f.buf, "TypeId \\{ {} \\}", self.hash())
1372 }
1373 }
1374
1375 impl<T: Show> Show for iter::MinMaxResult<T> {
1376 fn fmt(&self, f: &mut Formatter) -> Result {
1377 match *self {
1378 iter::NoElements =>
1379 write!(f.buf, "NoElements"),
1380 iter::OneElement(ref t) =>
1381 write!(f.buf, "OneElement({})", *t),
1382 iter::MinMax(ref t1, ref t2) =>
1383 write!(f.buf, "MinMax({}, {})", *t1, *t2),
1384 }
1385 }
1386 }
1387
1388 impl Show for cmp::Ordering {
1389 fn fmt(&self, f: &mut Formatter) -> Result {
1390 match *self {
1391 cmp::Less => write!(f.buf, "Less"),
1392 cmp::Greater => write!(f.buf, "Greater"),
1393 cmp::Equal => write!(f.buf, "Equal"),
1394 }
1395 }
1396 }
1397
1398 impl<T: Copy + Show> Show for Cell<T> {
1399 fn fmt(&self, f: &mut Formatter) -> Result {
1400 write!(f.buf, r"Cell \{ value: {} \}", self.get())
1401 }
1402 }
1403
1404 impl Show for UTF16Item {
1405 fn fmt(&self, f: &mut Formatter) -> Result {
1406 match *self {
1407 ScalarValue(c) => write!(f.buf, "ScalarValue({})", c),
1408 LoneSurrogate(u) => write!(f.buf, "LoneSurrogate({})", u),
1409 }
1410 }
1411 }
1412
1413 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1414 // it's a lot easier than creating all of the rt::Piece structures here.
libstd/fmt/mod.rs:703:12-703:12 -fn- definition:
pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
x.fmt(fmt)
}
references:- 73libstd/macros.rs:
libstd/fmt/mod.rs:667:39-667:39 -trait- definition:
/// Format trait for the `?` character
pub trait Poly {
/// Formats the value using the given formatter.
references:- 21212: impl<T> Poly for T {
1213: fn fmt(&self, f: &mut Formatter) -> Result {
libstd/fmt/mod.rs:540:1-540:1 -NK_AS_STR_TODO- definition:
pub type Result = io::IoResult<()>;
/// A struct to represent both where to emit formatting strings to and how they
/// should be formatted. A mutable version of this is passed to all formatting
references:- 183libstd/fmt/num.rs:
libstd/vec.rs:
libstd/str.rs:
libstd/strbuf.rs:
libstd/ascii.rs:
libstd/num/mod.rs:
libstd/comm/mod.rs:
libstd/comm/sync.rs:
libstd/sync/deque.rs:
libstd/os.rs:
libstd/io/mod.rs:
libstd/io/net/ip.rs:
libstd/io/process.rs:
libstd/io/signal.rs:
libstd/path/mod.rs:
libstd/fmt/mod.rs:
libstd/fmt/mod.rs:812:8-812:8 -fn- definition:
/// ```
pub fn format(args: &Arguments) -> ~str {
unsafe { format_unsafe(args.fmt, args.args) }
references:- 36libstd/rt/unwind.rs:
libstd/macros.rs:
libstd/fmt/mod.rs:593:25-593:25 -struct- definition:
/// be safely performed.
pub struct Arguments<'a> {
fmt: &'a [rt::Piece<'a>],
references:- 132libstd/rt/unwind.rs:
libstd/rt/util.rs:
libstd/macros.rs:
libstd/io/stdio.rs:
libstd/macros.rs:
libstd/fmt/mod.rs:679:39-679:39 -trait- definition:
/// Format trait for the `f` character
pub trait Float {
/// Formats the value using the given formatter.
references:- 31175: macro_rules! floating(($ty:ident) => {
1176: impl Float for $ty {
1177: fn fmt(&self, fmt: &mut Formatter) -> Result {
libstd/fmt/mod.rs:625:48-625:48 -trait- definition:
/// Format trait for the `i` and `d` characters
pub trait Signed {
/// Formats the value using the given formatter.
references:- 6702: #[doc(hidden)]
703: pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704: x.fmt(fmt)
libstd/fmt/num.rs:
159: ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
160: impl fmt::$Trait for $T {
161: fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
libstd/fmt/mod.rs:673:39-673:39 -trait- definition:
/// Format trait for the `p` character
pub trait Pointer {
/// Formats the value using the given formatter.
references:- 5702: #[doc(hidden)]
703: pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704: x.fmt(fmt)
--
1229: impl<T> Pointer for *T {
1230: fn fmt(&self, f: &mut Formatter) -> Result {
--
1239: }
1240: impl<'a, T> Pointer for &'a T {
1241: fn fmt(&self, f: &mut Formatter) -> Result {
--
1244: }
1245: impl<'a, T> Pointer for &'a mut T {
1246: fn fmt(&self, f: &mut Formatter) -> Result {
libstd/fmt/mod.rs:643:39-643:39 -trait- definition:
/// Format trait for the `t` character
pub trait Binary {
/// Formats the value using the given formatter.
references:- 11702: #[doc(hidden)]
703: pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704: x.fmt(fmt)
libstd/fmt/num.rs:
159: ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
160: impl fmt::$Trait for $T {
161: fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
libstd/fmt/mod.rs:613:39-613:39 -trait- definition:
/// Format trait for the `b` character
pub trait Bool {
/// Formats the value using the given formatter.
references:- 2702: #[doc(hidden)]
703: pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704: x.fmt(fmt)
--
1154: impl Bool for bool {
1155: fn fmt(&self, f: &mut Formatter) -> Result {
libstd/fmt/mod.rs:751:80-751:80 -fn- definition:
/// will also write a newline (`\n`) character at the end of the format string.
pub fn writeln(output: &mut io::Writer, args: &Arguments) -> Result {
let first = unsafe { write_unsafe(output, args.fmt, args.args) };
references:- 4libstd/rt/unwind.rs:
405: // FIXME: what to do when the task printing fails?
406: let _err = format_args!(|args| ::fmt::writeln(stderr, args),
407: "task '{}' failed at '{}', {}:{}",
libstd/rt/util.rs:
96: let mut w = Stderr;
97: let _ = fmt::writeln(&mut w as &mut io::Writer, args);
98: }
libstd/macros.rs:
258: let dst: &mut ::std::io::Writer = $dst;
259: format_args!(|args| { ::std::fmt::writeln(dst, args) }, $($arg)*)
260: })
libstd/io/stdio.rs:
284: pub fn println_args(fmt: &fmt::Arguments) {
285: with_task_stdout(|io| fmt::writeln(io, fmt))
286: }
libstd/fmt/mod.rs:703:12-703:12 -fn- definition:
pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
x.fmt(fmt)
}
references:- 21138: pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
1139: argument(secret_unsigned, s)
1140: }
libstd/io/mod.rs:
941: fn write_uint(&mut self, n: uint) -> IoResult<()> {
942: write!(self, "{:u}", n)
943: }
libstd/fmt/mod.rs:567:79-567:79 -struct- definition:
/// types, and then this struct is used to canonicalize arguments to one type.
pub struct Argument<'a> {
formatter: extern "Rust" fn(&any::Void, &mut Formatter) -> Result,
references:- 111120: unsafe {
1121: Argument {
1122: formatter: cast::transmute(f),
--
1138: pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
1139: argument(secret_unsigned, s)
libstd/fmt/mod.rs:1117:25-1117:25 -fn- definition:
pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result,
t: &'a T) -> Argument<'a> {
unsafe {
references:- 364libstd/fmt/num.rs:
libstd/cleanup.rs:
libstd/repr.rs:
libstd/unstable/dynamic_lib.rs:
libstd/rt/macros.rs:
libstd/rt/task.rs:
libstd/rt/thread.rs:
libstd/rt/local_heap.rs:
libstd/rt/unwind.rs:
libstd/rt/backtrace.rs:
libstd/rt/util.rs:
libstd/rt/stack.rs:
libstd/macros.rs:
libstd/bitflags.rs:
libstd/num/strconv.rs:
libstd/to_str.rs:
libstd/result.rs:
libstd/comm/mod.rs:
libstd/comm/shared.rs:
libstd/sync/deque.rs:
libstd/os.rs:
libstd/io/mod.rs:
libstd/io/test.rs:
libstd/io/tempfile.rs:
libstd/io/net/ip.rs:
libstd/io/process.rs:
libstd/io/stdio.rs:
libstd/path/windows.rs:
libstd/macros.rs:
libstd/fmt/mod.rs:545:12-545:12 -struct- definition:
/// traits.
pub struct Formatter<'a> {
/// Flags for formatting (packed version of rt::Flag)
references:- 177libstd/fmt/num.rs:
libstd/vec.rs:
libstd/str.rs:
libstd/strbuf.rs:
libstd/ascii.rs:
libstd/num/mod.rs:
libstd/comm/mod.rs:
libstd/comm/sync.rs:
libstd/sync/deque.rs:
libstd/os.rs:
libstd/io/mod.rs:
libstd/io/net/ip.rs:
libstd/io/process.rs:
libstd/io/signal.rs:
libstd/path/mod.rs:
libstd/fmt/num.rs:
libstd/fmt/mod.rs:691:39-691:39 -trait- definition:
/// Format trait for the `E` character
pub trait UpperExp {
/// Formats the value using the given formatter.
references:- 31198: impl UpperExp for $ty {
1199: fn fmt(&self, fmt: &mut Formatter) -> Result {
libstd/fmt/mod.rs:655:39-655:39 -trait- definition:
/// Format trait for the `X` character
pub trait UpperHex {
/// Formats the value using the given formatter.
references:- 11702: #[doc(hidden)]
703: pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704: x.fmt(fmt)
libstd/fmt/num.rs:
159: ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
160: impl fmt::$Trait for $T {
161: fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
libstd/fmt/mod.rs:776:19-776:19 -fn- definition:
/// format string.
pub unsafe fn write_unsafe(output: &mut io::Writer,
fmt: &[rt::Piece],
references:- 3839: let mut output = MemWriter::new();
840: write_unsafe(&mut output as &mut io::Writer, fmt, args).unwrap();
841: return str::from_utf8(output.unwrap().as_slice()).unwrap().to_owned();
libstd/fmt/mod.rs:637:39-637:39 -trait- definition:
/// Format trait for the `o` character
pub trait Octal {
/// Formats the value using the given formatter.
references:- 11702: #[doc(hidden)]
703: pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704: x.fmt(fmt)
libstd/fmt/num.rs:
159: ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
160: impl fmt::$Trait for $T {
161: fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
libstd/fmt/mod.rs:631:39-631:39 -trait- definition:
/// Format trait for the `u` character
pub trait Unsigned {
/// Formats the value using the given formatter.
references:- 6702: #[doc(hidden)]
703: pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704: x.fmt(fmt)
libstd/fmt/num.rs:
159: ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
160: impl fmt::$Trait for $T {
161: fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
libstd/fmt/mod.rs:661:39-661:39 -trait- definition:
/// Format trait for the `s` character
pub trait String {
/// Formats the value using the given formatter.
references:- 2702: #[doc(hidden)]
703: pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704: x.fmt(fmt)
--
1160: impl<'a, T: str::Str> String for T {
1161: fn fmt(&self, f: &mut Formatter) -> Result {
libstd/fmt/mod.rs:685:39-685:39 -trait- definition:
/// Format trait for the `e` character
pub trait LowerExp {
/// Formats the value using the given formatter.
references:- 3702: #[doc(hidden)]
703: pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704: x.fmt(fmt)
--
1187: impl LowerExp for $ty {
1188: fn fmt(&self, fmt: &mut Formatter) -> Result {
libstd/fmt/mod.rs:703:12-703:12 -fn- definition:
pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
x.fmt(fmt)
}
references:- 21255: fn fmt(&self, f: &mut Formatter) -> Result {
1256: (concat_idents!(secret_, $other)(self, f))
1257: }
libstd/fmt/mod.rs:703:12-703:12 -fn- definition:
pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
x.fmt(fmt)
}
references:- 9libstd/io/net/ip.rs:
53: write!(fmt.buf, "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}",
54: a, b, c, d, e, f, g, h)
55: }
libstd/fmt/mod.rs:
1231: f.flags |= 1 << (rt::FlagAlternate as uint);
1232: secret_lower_hex::<uint>(&(*self as uint), f)
1233: }
libstd/fmt/mod.rs:619:39-619:39 -trait- definition:
/// Format trait for the `c` character
pub trait Char {
/// Formats the value using the given formatter.
references:- 21166: impl Char for char {
1167: fn fmt(&self, f: &mut Formatter) -> Result {
libstd/fmt/mod.rs:745:8-745:8 -fn- definition:
/// ```
pub fn write(output: &mut io::Writer, args: &Arguments) -> Result {
unsafe { write_unsafe(output, args.fmt, args.args) }
references:- 290libstd/macros.rs:
libstd/num/mod.rs:
libstd/comm/mod.rs:
libstd/comm/sync.rs:
libstd/sync/deque.rs:
libstd/io/mod.rs:
libstd/io/signal.rs:
libstd/io/stdio.rs:
libstd/macros.rs:
libstd/fmt/mod.rs:649:39-649:39 -trait- definition:
/// Format trait for the `x` character
pub trait LowerHex {
/// Formats the value using the given formatter.
references:- 11702: #[doc(hidden)]
703: pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
704: x.fmt(fmt)
libstd/fmt/num.rs:
159: ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
160: impl fmt::$Trait for $T {
161: fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
libstd/fmt/mod.rs:703:12-703:12 -fn- definition:
pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
x.fmt(fmt)
}
references:- 51270: impl<T> Show for *mut T {
1271: fn fmt(&self, f: &mut Formatter) -> Result { secret_pointer(self, f) }
1272: }
libstd/fmt/mod.rs:607:69-607:69 -trait- definition:
/// used for formatting, it is only if no other format is specified.
pub trait Show {
/// Formats the value using the given formatter.
references:- 172libstd/fmt/num.rs:
libstd/vec.rs:
libstd/str.rs:
libstd/strbuf.rs:
libstd/ascii.rs:
libstd/num/mod.rs:
libstd/to_str.rs:
libstd/result.rs:
libstd/comm/mod.rs:
libstd/comm/sync.rs:
libstd/sync/deque.rs:
libstd/os.rs:
libstd/io/mod.rs:
libstd/io/net/ip.rs:
libstd/io/process.rs:
libstd/io/signal.rs:
libstd/path/mod.rs:
libstd/fmt/mod.rs:
libstd/fmt/mod.rs:703:12-703:12 -fn- definition:
pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
x.fmt(fmt)
}
references:- 289libstd/fmt/num.rs:
libstd/cleanup.rs:
libstd/repr.rs:
libstd/unstable/dynamic_lib.rs:
libstd/rt/macros.rs:
libstd/rt/task.rs:
libstd/rt/thread.rs:
libstd/rt/local_heap.rs:
libstd/rt/unwind.rs:
libstd/rt/backtrace.rs:
libstd/rt/util.rs:
libstd/rt/stack.rs:
libstd/macros.rs:
libstd/bitflags.rs:
libstd/num/strconv.rs:
libstd/to_str.rs:
libstd/result.rs:
libstd/comm/mod.rs:
libstd/comm/shared.rs:
libstd/sync/deque.rs:
libstd/os.rs:
libstd/io/mod.rs:
libstd/io/test.rs:
libstd/io/tempfile.rs:
libstd/io/net/ip.rs:
libstd/io/process.rs:
libstd/io/stdio.rs:
libstd/path/windows.rs:
libstd/repr.rs: