]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/mod.rs
f850cdbbd609057bb752bdbdd1bbeff1acb4ec87
[rust.git] / src / libcore / fmt / mod.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 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use prelude::v1::*;
16
17 use cell::{Cell, RefCell, Ref, RefMut, BorrowState};
18 use marker::PhantomData;
19 use mem;
20 use num::flt2dec;
21 use ops::Deref;
22 use result;
23 use slice;
24 use str;
25 use self::rt::v1::Alignment;
26
27 pub use self::num::radix;
28 pub use self::num::Radix;
29 pub use self::num::RadixFmt;
30
31 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
32
33 mod num;
34 mod builders;
35
36 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
37            issue = "0")]
38 #[doc(hidden)]
39 pub mod rt {
40     pub mod v1;
41 }
42
43 #[stable(feature = "rust1", since = "1.0.0")]
44 /// The type returned by formatter methods.
45 pub type Result = result::Result<(), Error>;
46
47 /// The error type which is returned from formatting a message into a stream.
48 ///
49 /// This type does not support transmission of an error other than that an error
50 /// occurred. Any extra information must be arranged to be transmitted through
51 /// some other means.
52 #[stable(feature = "rust1", since = "1.0.0")]
53 #[derive(Copy, Clone, Debug)]
54 pub struct Error;
55
56 /// A collection of methods that are required to format a message into a stream.
57 ///
58 /// This trait is the type which this modules requires when formatting
59 /// information. This is similar to the standard library's `io::Write` trait,
60 /// but it is only intended for use in libcore.
61 ///
62 /// This trait should generally not be implemented by consumers of the standard
63 /// library. The `write!` macro accepts an instance of `io::Write`, and the
64 /// `io::Write` trait is favored over implementing this trait.
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub trait Write {
67     /// Writes a slice of bytes into this writer, returning whether the write
68     /// succeeded.
69     ///
70     /// This method can only succeed if the entire byte slice was successfully
71     /// written, and this method will not return until all data has been
72     /// written or an error occurs.
73     ///
74     /// # Errors
75     ///
76     /// This function will return an instance of `Error` on error.
77     #[stable(feature = "rust1", since = "1.0.0")]
78     fn write_str(&mut self, s: &str) -> Result;
79
80     /// Writes a `char` into this writer, returning whether the write succeeded.
81     ///
82     /// A single `char` may be encoded as more than one byte.
83     /// This method can only succeed if the entire byte sequence was successfully
84     /// written, and this method will not return until all data has been
85     /// written or an error occurs.
86     ///
87     /// # Errors
88     ///
89     /// This function will return an instance of `Error` on error.
90     #[stable(feature = "fmt_write_char", since = "1.1.0")]
91     fn write_char(&mut self, c: char) -> Result {
92         let mut utf_8 = [0u8; 4];
93         let bytes_written = c.encode_utf8(&mut utf_8).unwrap_or(0);
94         self.write_str(unsafe { str::from_utf8_unchecked(&utf_8[..bytes_written]) })
95     }
96
97     /// Glue for usage of the `write!` macro with implementors of this trait.
98     ///
99     /// This method should generally not be invoked manually, but rather through
100     /// the `write!` macro itself.
101     #[stable(feature = "rust1", since = "1.0.0")]
102     fn write_fmt(&mut self, args: Arguments) -> Result {
103         // This Adapter is needed to allow `self` (of type `&mut
104         // Self`) to be cast to a Write (below) without
105         // requiring a `Sized` bound.
106         struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
107
108         impl<'a, T: ?Sized> Write for Adapter<'a, T>
109             where T: Write
110         {
111             fn write_str(&mut self, s: &str) -> Result {
112                 self.0.write_str(s)
113             }
114
115             fn write_fmt(&mut self, args: Arguments) -> Result {
116                 self.0.write_fmt(args)
117             }
118         }
119
120         write(&mut Adapter(self), args)
121     }
122 }
123
124 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
125 impl<'a, W: Write + ?Sized> Write for &'a mut W {
126     fn write_str(&mut self, s: &str) -> Result {
127         (**self).write_str(s)
128     }
129
130     fn write_char(&mut self, c: char) -> Result {
131         (**self).write_char(c)
132     }
133
134     fn write_fmt(&mut self, args: Arguments) -> Result {
135         (**self).write_fmt(args)
136     }
137 }
138
139 /// A struct to represent both where to emit formatting strings to and how they
140 /// should be formatted. A mutable version of this is passed to all formatting
141 /// traits.
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub struct Formatter<'a> {
144     flags: u32,
145     fill: char,
146     align: rt::v1::Alignment,
147     width: Option<usize>,
148     precision: Option<usize>,
149
150     buf: &'a mut (Write+'a),
151     curarg: slice::Iter<'a, ArgumentV1<'a>>,
152     args: &'a [ArgumentV1<'a>],
153 }
154
155 // NB. Argument is essentially an optimized partially applied formatting function,
156 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
157
158 enum Void {}
159
160 /// This struct represents the generic "argument" which is taken by the Xprintf
161 /// family of functions. It contains a function to format the given value. At
162 /// compile time it is ensured that the function and the value have the correct
163 /// types, and then this struct is used to canonicalize arguments to one type.
164 #[derive(Copy)]
165 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
166            issue = "0")]
167 #[doc(hidden)]
168 pub struct ArgumentV1<'a> {
169     value: &'a Void,
170     formatter: fn(&Void, &mut Formatter) -> Result,
171 }
172
173 impl<'a> Clone for ArgumentV1<'a> {
174     fn clone(&self) -> ArgumentV1<'a> {
175         *self
176     }
177 }
178
179 impl<'a> ArgumentV1<'a> {
180     #[inline(never)]
181     fn show_usize(x: &usize, f: &mut Formatter) -> Result {
182         Display::fmt(x, f)
183     }
184
185     #[doc(hidden)]
186     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
187                issue = "0")]
188     pub fn new<'b, T>(x: &'b T,
189                       f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
190         unsafe {
191             ArgumentV1 {
192                 formatter: mem::transmute(f),
193                 value: mem::transmute(x)
194             }
195         }
196     }
197
198     #[doc(hidden)]
199     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
200                issue = "0")]
201     pub fn from_usize(x: &usize) -> ArgumentV1 {
202         ArgumentV1::new(x, ArgumentV1::show_usize)
203     }
204
205     fn as_usize(&self) -> Option<usize> {
206         if self.formatter as usize == ArgumentV1::show_usize as usize {
207             Some(unsafe { *(self.value as *const _ as *const usize) })
208         } else {
209             None
210         }
211     }
212 }
213
214 // flags available in the v1 format of format_args
215 #[derive(Copy, Clone)]
216 #[allow(dead_code)] // SignMinus isn't currently used
217 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
218
219 impl<'a> Arguments<'a> {
220     /// When using the format_args!() macro, this function is used to generate the
221     /// Arguments structure.
222     #[doc(hidden)] #[inline]
223     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
224                issue = "0")]
225     pub fn new_v1(pieces: &'a [&'a str],
226                   args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
227         Arguments {
228             pieces: pieces,
229             fmt: None,
230             args: args
231         }
232     }
233
234     /// This function is used to specify nonstandard formatting parameters.
235     /// The `pieces` array must be at least as long as `fmt` to construct
236     /// a valid Arguments structure. Also, any `Count` within `fmt` that is
237     /// `CountIsParam` or `CountIsNextParam` has to point to an argument
238     /// created with `argumentusize`. However, failing to do so doesn't cause
239     /// unsafety, but will ignore invalid .
240     #[doc(hidden)] #[inline]
241     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
242                issue = "0")]
243     pub fn new_v1_formatted(pieces: &'a [&'a str],
244                             args: &'a [ArgumentV1<'a>],
245                             fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
246         Arguments {
247             pieces: pieces,
248             fmt: Some(fmt),
249             args: args
250         }
251     }
252 }
253
254 /// This structure represents a safely precompiled version of a format string
255 /// and its arguments. This cannot be generated at runtime because it cannot
256 /// safely be done so, so no constructors are given and the fields are private
257 /// to prevent modification.
258 ///
259 /// The `format_args!` macro will safely create an instance of this structure
260 /// and pass it to a function or closure, passed as the first argument. The
261 /// macro validates the format string at compile-time so usage of the `write`
262 /// and `format` functions can be safely performed.
263 #[stable(feature = "rust1", since = "1.0.0")]
264 #[derive(Copy, Clone)]
265 pub struct Arguments<'a> {
266     // Format string pieces to print.
267     pieces: &'a [&'a str],
268
269     // Placeholder specs, or `None` if all specs are default (as in "{}{}").
270     fmt: Option<&'a [rt::v1::Argument]>,
271
272     // Dynamic arguments for interpolation, to be interleaved with string
273     // pieces. (Every argument is preceded by a string piece.)
274     args: &'a [ArgumentV1<'a>],
275 }
276
277 #[stable(feature = "rust1", since = "1.0.0")]
278 impl<'a> Debug for Arguments<'a> {
279     fn fmt(&self, fmt: &mut Formatter) -> Result {
280         Display::fmt(self, fmt)
281     }
282 }
283
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl<'a> Display for Arguments<'a> {
286     fn fmt(&self, fmt: &mut Formatter) -> Result {
287         write(fmt.buf, *self)
288     }
289 }
290
291 /// Format trait for the `?` character.
292 ///
293 /// `Debug` should format the output in a programmer-facing, debugging context.
294 ///
295 /// Generally speaking, you should just `derive` a `Debug` implementation.
296 ///
297 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
298 ///
299 /// For more information on formatters, see [the module-level documentation][module].
300 ///
301 /// [module]: ../../std/fmt/index.html
302 ///
303 /// # Examples
304 ///
305 /// Deriving an implementation:
306 ///
307 /// ```
308 /// #[derive(Debug)]
309 /// struct Point {
310 ///     x: i32,
311 ///     y: i32,
312 /// }
313 ///
314 /// let origin = Point { x: 0, y: 0 };
315 ///
316 /// println!("The origin is: {:?}", origin);
317 /// ```
318 ///
319 /// Manually implementing:
320 ///
321 /// ```
322 /// use std::fmt;
323 ///
324 /// struct Point {
325 ///     x: i32,
326 ///     y: i32,
327 /// }
328 ///
329 /// impl fmt::Debug for Point {
330 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
331 ///         write!(f, "({}, {})", self.x, self.y)
332 ///     }
333 /// }
334 ///
335 /// let origin = Point { x: 0, y: 0 };
336 ///
337 /// println!("The origin is: {:?}", origin);
338 /// ```
339 ///
340 /// This outputs:
341 ///
342 /// ```text
343 /// The origin is: Point { x: 0, y: 0 }
344 /// ```
345 ///
346 /// There are a number of `debug_*` methods on `Formatter` to help you with manual
347 /// implementations, such as [`debug_struct`][debug_struct].
348 ///
349 /// `Debug` implementations using either `derive` or the debug builder API
350 /// on `Formatter` support pretty printing using the alternate flag: `{:#?}`.
351 ///
352 /// [debug_struct]: ../std/fmt/struct.Formatter.html#method.debug_struct
353 ///
354 /// Pretty printing with `#?`:
355 ///
356 /// ```
357 /// #[derive(Debug)]
358 /// struct Point {
359 ///     x: i32,
360 ///     y: i32,
361 /// }
362 ///
363 /// let origin = Point { x: 0, y: 0 };
364 ///
365 /// println!("The origin is: {:#?}", origin);
366 /// ```
367 ///
368 /// This outputs:
369 ///
370 /// ```text
371 /// The origin is: Point {
372 ///     x: 0,
373 ///     y: 0
374 /// }
375 /// ```
376 #[stable(feature = "rust1", since = "1.0.0")]
377 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
378                             defined in your crate, add `#[derive(Debug)]` or \
379                             manually implement it"]
380 #[lang = "debug_trait"]
381 pub trait Debug {
382     /// Formats the value using the given formatter.
383     #[stable(feature = "rust1", since = "1.0.0")]
384     fn fmt(&self, &mut Formatter) -> Result;
385 }
386
387 /// Format trait for an empty format, `{}`.
388 ///
389 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
390 /// output, and so cannot be derived.
391 ///
392 /// [debug]: trait.Debug.html
393 ///
394 /// For more information on formatters, see [the module-level documentation][module].
395 ///
396 /// [module]: ../../std/fmt/index.html
397 ///
398 /// # Examples
399 ///
400 /// Implementing `Display` on a type:
401 ///
402 /// ```
403 /// use std::fmt;
404 ///
405 /// struct Point {
406 ///     x: i32,
407 ///     y: i32,
408 /// }
409 ///
410 /// impl fmt::Display for Point {
411 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
412 ///         write!(f, "({}, {})", self.x, self.y)
413 ///     }
414 /// }
415 ///
416 /// let origin = Point { x: 0, y: 0 };
417 ///
418 /// println!("The origin is: {}", origin);
419 /// ```
420 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
421                             formatter; try using `:?` instead if you are using \
422                             a format string"]
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub trait Display {
425     /// Formats the value using the given formatter.
426     #[stable(feature = "rust1", since = "1.0.0")]
427     fn fmt(&self, &mut Formatter) -> Result;
428 }
429
430 /// Format trait for the `o` character.
431 ///
432 /// The `Octal` trait should format its output as a number in base-8.
433 ///
434 /// The alternate flag, `#`, adds a `0o` in front of the output.
435 ///
436 /// For more information on formatters, see [the module-level documentation][module].
437 ///
438 /// [module]: ../../std/fmt/index.html
439 ///
440 /// # Examples
441 ///
442 /// Basic usage with `i32`:
443 ///
444 /// ```
445 /// let x = 42; // 42 is '52' in octal
446 ///
447 /// assert_eq!(format!("{:o}", x), "52");
448 /// assert_eq!(format!("{:#o}", x), "0o52");
449 /// ```
450 ///
451 /// Implementing `Octal` on a type:
452 ///
453 /// ```
454 /// use std::fmt;
455 ///
456 /// struct Length(i32);
457 ///
458 /// impl fmt::Octal for Length {
459 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
460 ///         let val = self.0;
461 ///
462 ///         write!(f, "{:o}", val) // delegate to i32's implementation
463 ///     }
464 /// }
465 ///
466 /// let l = Length(9);
467 ///
468 /// println!("l as octal is: {:o}", l);
469 /// ```
470 #[stable(feature = "rust1", since = "1.0.0")]
471 pub trait Octal {
472     /// Formats the value using the given formatter.
473     #[stable(feature = "rust1", since = "1.0.0")]
474     fn fmt(&self, &mut Formatter) -> Result;
475 }
476
477 /// Format trait for the `b` character.
478 ///
479 /// The `Binary` trait should format its output as a number in binary.
480 ///
481 /// The alternate flag, `#`, adds a `0b` in front of the output.
482 ///
483 /// For more information on formatters, see [the module-level documentation][module].
484 ///
485 /// [module]: ../../std/fmt/index.html
486 ///
487 /// # Examples
488 ///
489 /// Basic usage with `i32`:
490 ///
491 /// ```
492 /// let x = 42; // 42 is '101010' in binary
493 ///
494 /// assert_eq!(format!("{:b}", x), "101010");
495 /// assert_eq!(format!("{:#b}", x), "0b101010");
496 /// ```
497 ///
498 /// Implementing `Binary` on a type:
499 ///
500 /// ```
501 /// use std::fmt;
502 ///
503 /// struct Length(i32);
504 ///
505 /// impl fmt::Binary for Length {
506 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
507 ///         let val = self.0;
508 ///
509 ///         write!(f, "{:b}", val) // delegate to i32's implementation
510 ///     }
511 /// }
512 ///
513 /// let l = Length(107);
514 ///
515 /// println!("l as binary is: {:b}", l);
516 /// ```
517 #[stable(feature = "rust1", since = "1.0.0")]
518 pub trait Binary {
519     /// Formats the value using the given formatter.
520     #[stable(feature = "rust1", since = "1.0.0")]
521     fn fmt(&self, &mut Formatter) -> Result;
522 }
523
524 /// Format trait for the `x` character.
525 ///
526 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
527 /// in lower case.
528 ///
529 /// The alternate flag, `#`, adds a `0x` in front of the output.
530 ///
531 /// For more information on formatters, see [the module-level documentation][module].
532 ///
533 /// [module]: ../../std/fmt/index.html
534 ///
535 /// # Examples
536 ///
537 /// Basic usage with `i32`:
538 ///
539 /// ```
540 /// let x = 42; // 42 is '2a' in hex
541 ///
542 /// assert_eq!(format!("{:x}", x), "2a");
543 /// assert_eq!(format!("{:#x}", x), "0x2a");
544 /// ```
545 ///
546 /// Implementing `LowerHex` on a type:
547 ///
548 /// ```
549 /// use std::fmt;
550 ///
551 /// struct Length(i32);
552 ///
553 /// impl fmt::LowerHex for Length {
554 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
555 ///         let val = self.0;
556 ///
557 ///         write!(f, "{:x}", val) // delegate to i32's implementation
558 ///     }
559 /// }
560 ///
561 /// let l = Length(9);
562 ///
563 /// println!("l as hex is: {:x}", l);
564 /// ```
565 #[stable(feature = "rust1", since = "1.0.0")]
566 pub trait LowerHex {
567     /// Formats the value using the given formatter.
568     #[stable(feature = "rust1", since = "1.0.0")]
569     fn fmt(&self, &mut Formatter) -> Result;
570 }
571
572 /// Format trait for the `X` character.
573 ///
574 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
575 /// in upper case.
576 ///
577 /// The alternate flag, `#`, adds a `0x` in front of the output.
578 ///
579 /// For more information on formatters, see [the module-level documentation][module].
580 ///
581 /// [module]: ../../std/fmt/index.html
582 ///
583 /// # Examples
584 ///
585 /// Basic usage with `i32`:
586 ///
587 /// ```
588 /// let x = 42; // 42 is '2A' in hex
589 ///
590 /// assert_eq!(format!("{:X}", x), "2A");
591 /// assert_eq!(format!("{:#X}", x), "0x2A");
592 /// ```
593 ///
594 /// Implementing `UpperHex` on a type:
595 ///
596 /// ```
597 /// use std::fmt;
598 ///
599 /// struct Length(i32);
600 ///
601 /// impl fmt::UpperHex for Length {
602 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
603 ///         let val = self.0;
604 ///
605 ///         write!(f, "{:X}", val) // delegate to i32's implementation
606 ///     }
607 /// }
608 ///
609 /// let l = Length(9);
610 ///
611 /// println!("l as hex is: {:X}", l);
612 /// ```
613 #[stable(feature = "rust1", since = "1.0.0")]
614 pub trait UpperHex {
615     /// Formats the value using the given formatter.
616     #[stable(feature = "rust1", since = "1.0.0")]
617     fn fmt(&self, &mut Formatter) -> Result;
618 }
619
620 /// Format trait for the `p` character.
621 ///
622 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
623 /// as hexadecimal.
624 ///
625 /// For more information on formatters, see [the module-level documentation][module].
626 ///
627 /// [module]: ../../std/fmt/index.html
628 ///
629 /// # Examples
630 ///
631 /// Basic usage with `&i32`:
632 ///
633 /// ```
634 /// let x = &42;
635 ///
636 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
637 /// ```
638 ///
639 /// Implementing `Pointer` on a type:
640 ///
641 /// ```
642 /// use std::fmt;
643 ///
644 /// struct Length(i32);
645 ///
646 /// impl fmt::Pointer for Length {
647 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
648 ///         // use `as` to convert to a `*const T`, which implements Pointer, which we can use
649 ///
650 ///         write!(f, "{:p}", self as *const Length)
651 ///     }
652 /// }
653 ///
654 /// let l = Length(42);
655 ///
656 /// println!("l is in memory here: {:p}", l);
657 /// ```
658 #[stable(feature = "rust1", since = "1.0.0")]
659 pub trait Pointer {
660     /// Formats the value using the given formatter.
661     #[stable(feature = "rust1", since = "1.0.0")]
662     fn fmt(&self, &mut Formatter) -> Result;
663 }
664
665 /// Format trait for the `e` character.
666 ///
667 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
668 ///
669 /// For more information on formatters, see [the module-level documentation][module].
670 ///
671 /// [module]: ../../std/fmt/index.html
672 ///
673 /// # Examples
674 ///
675 /// Basic usage with `i32`:
676 ///
677 /// ```
678 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
679 ///
680 /// assert_eq!(format!("{:e}", x), "4.2e1");
681 /// ```
682 ///
683 /// Implementing `LowerExp` on a type:
684 ///
685 /// ```
686 /// use std::fmt;
687 ///
688 /// struct Length(i32);
689 ///
690 /// impl fmt::LowerExp for Length {
691 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
692 ///         let val = self.0;
693 ///         write!(f, "{}e1", val / 10)
694 ///     }
695 /// }
696 ///
697 /// let l = Length(100);
698 ///
699 /// println!("l in scientific notation is: {:e}", l);
700 /// ```
701 #[stable(feature = "rust1", since = "1.0.0")]
702 pub trait LowerExp {
703     /// Formats the value using the given formatter.
704     #[stable(feature = "rust1", since = "1.0.0")]
705     fn fmt(&self, &mut Formatter) -> Result;
706 }
707
708 /// Format trait for the `E` character.
709 ///
710 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
711 ///
712 /// For more information on formatters, see [the module-level documentation][module].
713 ///
714 /// [module]: ../../std/fmt/index.html
715 ///
716 /// # Examples
717 ///
718 /// Basic usage with `f32`:
719 ///
720 /// ```
721 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
722 ///
723 /// assert_eq!(format!("{:E}", x), "4.2E1");
724 /// ```
725 ///
726 /// Implementing `UpperExp` on a type:
727 ///
728 /// ```
729 /// use std::fmt;
730 ///
731 /// struct Length(i32);
732 ///
733 /// impl fmt::UpperExp for Length {
734 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
735 ///         let val = self.0;
736 ///         write!(f, "{}E1", val / 10)
737 ///     }
738 /// }
739 ///
740 /// let l = Length(100);
741 ///
742 /// println!("l in scientific notation is: {:E}", l);
743 /// ```
744 #[stable(feature = "rust1", since = "1.0.0")]
745 pub trait UpperExp {
746     /// Formats the value using the given formatter.
747     #[stable(feature = "rust1", since = "1.0.0")]
748     fn fmt(&self, &mut Formatter) -> Result;
749 }
750
751 /// The `write` function takes an output stream, a precompiled format string,
752 /// and a list of arguments. The arguments will be formatted according to the
753 /// specified format string into the output stream provided.
754 ///
755 /// # Arguments
756 ///
757 ///   * output - the buffer to write output to
758 ///   * args - the precompiled arguments generated by `format_args!`
759 #[stable(feature = "rust1", since = "1.0.0")]
760 pub fn write(output: &mut Write, args: Arguments) -> Result {
761     let mut formatter = Formatter {
762         flags: 0,
763         width: None,
764         precision: None,
765         buf: output,
766         align: Alignment::Unknown,
767         fill: ' ',
768         args: args.args,
769         curarg: args.args.iter(),
770     };
771
772     let mut pieces = args.pieces.iter();
773
774     match args.fmt {
775         None => {
776             // We can use default formatting parameters for all arguments.
777             for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
778                 try!(formatter.buf.write_str(*piece));
779                 try!((arg.formatter)(arg.value, &mut formatter));
780             }
781         }
782         Some(fmt) => {
783             // Every spec has a corresponding argument that is preceded by
784             // a string piece.
785             for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
786                 try!(formatter.buf.write_str(*piece));
787                 try!(formatter.run(arg));
788             }
789         }
790     }
791
792     // There can be only one trailing string piece left.
793     match pieces.next() {
794         Some(piece) => {
795             try!(formatter.buf.write_str(*piece));
796         }
797         None => {}
798     }
799
800     Ok(())
801 }
802
803 impl<'a> Formatter<'a> {
804
805     // First up is the collection of functions used to execute a format string
806     // at runtime. This consumes all of the compile-time statics generated by
807     // the format! syntax extension.
808     fn run(&mut self, arg: &rt::v1::Argument) -> Result {
809         // Fill in the format parameters into the formatter
810         self.fill = arg.format.fill;
811         self.align = arg.format.align;
812         self.flags = arg.format.flags;
813         self.width = self.getcount(&arg.format.width);
814         self.precision = self.getcount(&arg.format.precision);
815
816         // Extract the correct argument
817         let value = match arg.position {
818             rt::v1::Position::Next => { *self.curarg.next().unwrap() }
819             rt::v1::Position::At(i) => self.args[i],
820         };
821
822         // Then actually do some printing
823         (value.formatter)(value.value, self)
824     }
825
826     fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
827         match *cnt {
828             rt::v1::Count::Is(n) => Some(n),
829             rt::v1::Count::Implied => None,
830             rt::v1::Count::Param(i) => {
831                 self.args[i].as_usize()
832             }
833             rt::v1::Count::NextParam => {
834                 self.curarg.next().and_then(|arg| arg.as_usize())
835             }
836         }
837     }
838
839     // Helper methods used for padding and processing formatting arguments that
840     // all formatting traits can use.
841
842     /// Performs the correct padding for an integer which has already been
843     /// emitted into a str. The str should *not* contain the sign for the
844     /// integer, that will be added by this method.
845     ///
846     /// # Arguments
847     ///
848     /// * is_positive - whether the original integer was positive or not.
849     /// * prefix - if the '#' character (Alternate) is provided, this
850     ///   is the prefix to put in front of the number.
851     /// * buf - the byte array that the number has been formatted into
852     ///
853     /// This function will correctly account for the flags provided as well as
854     /// the minimum width. It will not take precision into account.
855     #[stable(feature = "rust1", since = "1.0.0")]
856     pub fn pad_integral(&mut self,
857                         is_positive: bool,
858                         prefix: &str,
859                         buf: &str)
860                         -> Result {
861         use char::CharExt;
862
863         let mut width = buf.len();
864
865         let mut sign = None;
866         if !is_positive {
867             sign = Some('-'); width += 1;
868         } else if self.sign_plus() {
869             sign = Some('+'); width += 1;
870         }
871
872         let mut prefixed = false;
873         if self.alternate() {
874             prefixed = true; width += prefix.char_len();
875         }
876
877         // Writes the sign if it exists, and then the prefix if it was requested
878         let write_prefix = |f: &mut Formatter| {
879             if let Some(c) = sign {
880                 let mut b = [0; 4];
881                 let n = c.encode_utf8(&mut b).unwrap_or(0);
882                 let b = unsafe { str::from_utf8_unchecked(&b[..n]) };
883                 try!(f.buf.write_str(b));
884             }
885             if prefixed { f.buf.write_str(prefix) }
886             else { Ok(()) }
887         };
888
889         // The `width` field is more of a `min-width` parameter at this point.
890         match self.width {
891             // If there's no minimum length requirements then we can just
892             // write the bytes.
893             None => {
894                 try!(write_prefix(self)); self.buf.write_str(buf)
895             }
896             // Check if we're over the minimum width, if so then we can also
897             // just write the bytes.
898             Some(min) if width >= min => {
899                 try!(write_prefix(self)); self.buf.write_str(buf)
900             }
901             // The sign and prefix goes before the padding if the fill character
902             // is zero
903             Some(min) if self.sign_aware_zero_pad() => {
904                 self.fill = '0';
905                 try!(write_prefix(self));
906                 self.with_padding(min - width, Alignment::Right, |f| {
907                     f.buf.write_str(buf)
908                 })
909             }
910             // Otherwise, the sign and prefix goes after the padding
911             Some(min) => {
912                 self.with_padding(min - width, Alignment::Right, |f| {
913                     try!(write_prefix(f)); f.buf.write_str(buf)
914                 })
915             }
916         }
917     }
918
919     /// This function takes a string slice and emits it to the internal buffer
920     /// after applying the relevant formatting flags specified. The flags
921     /// recognized for generic strings are:
922     ///
923     /// * width - the minimum width of what to emit
924     /// * fill/align - what to emit and where to emit it if the string
925     ///                provided needs to be padded
926     /// * precision - the maximum length to emit, the string is truncated if it
927     ///               is longer than this length
928     ///
929     /// Notably this function ignored the `flag` parameters
930     #[stable(feature = "rust1", since = "1.0.0")]
931     pub fn pad(&mut self, s: &str) -> Result {
932         // Make sure there's a fast path up front
933         if self.width.is_none() && self.precision.is_none() {
934             return self.buf.write_str(s);
935         }
936         // The `precision` field can be interpreted as a `max-width` for the
937         // string being formatted
938         match self.precision {
939             Some(max) => {
940                 // If there's a maximum width and our string is longer than
941                 // that, then we must always have truncation. This is the only
942                 // case where the maximum length will matter.
943                 let char_len = s.char_len();
944                 if char_len >= max {
945                     let nchars = ::cmp::min(max, char_len);
946                     return self.buf.write_str(s.slice_chars(0, nchars));
947                 }
948             }
949             None => {}
950         }
951         // The `width` field is more of a `min-width` parameter at this point.
952         match self.width {
953             // If we're under the maximum length, and there's no minimum length
954             // requirements, then we can just emit the string
955             None => self.buf.write_str(s),
956             // If we're under the maximum width, check if we're over the minimum
957             // width, if so it's as easy as just emitting the string.
958             Some(width) if s.char_len() >= width => {
959                 self.buf.write_str(s)
960             }
961             // If we're under both the maximum and the minimum width, then fill
962             // up the minimum width with the specified string + some alignment.
963             Some(width) => {
964                 self.with_padding(width - s.char_len(), Alignment::Left, |me| {
965                     me.buf.write_str(s)
966                 })
967             }
968         }
969     }
970
971     /// Runs a callback, emitting the correct padding either before or
972     /// afterwards depending on whether right or left alignment is requested.
973     fn with_padding<F>(&mut self, padding: usize, default: Alignment,
974                        f: F) -> Result
975         where F: FnOnce(&mut Formatter) -> Result,
976     {
977         use char::CharExt;
978         let align = match self.align {
979             Alignment::Unknown => default,
980             _ => self.align
981         };
982
983         let (pre_pad, post_pad) = match align {
984             Alignment::Left => (0, padding),
985             Alignment::Right | Alignment::Unknown => (padding, 0),
986             Alignment::Center => (padding / 2, (padding + 1) / 2),
987         };
988
989         let mut fill = [0; 4];
990         let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
991         let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) };
992
993         for _ in 0..pre_pad {
994             try!(self.buf.write_str(fill));
995         }
996
997         try!(f(self));
998
999         for _ in 0..post_pad {
1000             try!(self.buf.write_str(fill));
1001         }
1002
1003         Ok(())
1004     }
1005
1006     /// Takes the formatted parts and applies the padding.
1007     /// Assumes that the caller already has rendered the parts with required precision,
1008     /// so that `self.precision` can be ignored.
1009     fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1010         if let Some(mut width) = self.width {
1011             // for the sign-aware zero padding, we render the sign first and
1012             // behave as if we had no sign from the beginning.
1013             let mut formatted = formatted.clone();
1014             let mut align = self.align;
1015             let old_fill = self.fill;
1016             if self.sign_aware_zero_pad() {
1017                 // a sign always goes first
1018                 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1019                 try!(self.buf.write_str(sign));
1020
1021                 // remove the sign from the formatted parts
1022                 formatted.sign = b"";
1023                 width = if width < sign.len() { 0 } else { width - sign.len() };
1024                 align = Alignment::Right;
1025                 self.fill = '0';
1026             }
1027
1028             // remaining parts go through the ordinary padding process.
1029             let len = formatted.len();
1030             let ret = if width <= len { // no padding
1031                 self.write_formatted_parts(&formatted)
1032             } else {
1033                 self.with_padding(width - len, align, |f| {
1034                     f.write_formatted_parts(&formatted)
1035                 })
1036             };
1037             self.fill = old_fill;
1038             ret
1039         } else {
1040             // this is the common case and we take a shortcut
1041             self.write_formatted_parts(formatted)
1042         }
1043     }
1044
1045     fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1046         fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1047             buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1048         }
1049
1050         if !formatted.sign.is_empty() {
1051             try!(write_bytes(self.buf, formatted.sign));
1052         }
1053         for part in formatted.parts {
1054             match *part {
1055                 flt2dec::Part::Zero(mut nzeroes) => {
1056                     const ZEROES: &'static str = // 64 zeroes
1057                         "0000000000000000000000000000000000000000000000000000000000000000";
1058                     while nzeroes > ZEROES.len() {
1059                         try!(self.buf.write_str(ZEROES));
1060                         nzeroes -= ZEROES.len();
1061                     }
1062                     if nzeroes > 0 {
1063                         try!(self.buf.write_str(&ZEROES[..nzeroes]));
1064                     }
1065                 }
1066                 flt2dec::Part::Num(mut v) => {
1067                     let mut s = [0; 5];
1068                     let len = part.len();
1069                     for c in s[..len].iter_mut().rev() {
1070                         *c = b'0' + (v % 10) as u8;
1071                         v /= 10;
1072                     }
1073                     try!(write_bytes(self.buf, &s[..len]));
1074                 }
1075                 flt2dec::Part::Copy(buf) => {
1076                     try!(write_bytes(self.buf, buf));
1077                 }
1078             }
1079         }
1080         Ok(())
1081     }
1082
1083     /// Writes some data to the underlying buffer contained within this
1084     /// formatter.
1085     #[stable(feature = "rust1", since = "1.0.0")]
1086     pub fn write_str(&mut self, data: &str) -> Result {
1087         self.buf.write_str(data)
1088     }
1089
1090     /// Writes some formatted information into this instance
1091     #[stable(feature = "rust1", since = "1.0.0")]
1092     pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1093         write(self.buf, fmt)
1094     }
1095
1096     /// Flags for formatting (packed version of rt::Flag)
1097     #[stable(feature = "rust1", since = "1.0.0")]
1098     pub fn flags(&self) -> u32 { self.flags }
1099
1100     /// Character used as 'fill' whenever there is alignment
1101     #[stable(feature = "fmt_flags", since = "1.5.0")]
1102     pub fn fill(&self) -> char { self.fill }
1103
1104     /// Flag indicating what form of alignment was requested
1105     #[unstable(feature = "fmt_flags_align", reason = "method was just created",
1106                issue = "27726")]
1107     pub fn align(&self) -> Alignment { self.align }
1108
1109     /// Optionally specified integer width that the output should be
1110     #[stable(feature = "fmt_flags", since = "1.5.0")]
1111     pub fn width(&self) -> Option<usize> { self.width }
1112
1113     /// Optionally specified precision for numeric types
1114     #[stable(feature = "fmt_flags", since = "1.5.0")]
1115     pub fn precision(&self) -> Option<usize> { self.precision }
1116
1117     /// Determines if the `+` flag was specified.
1118     #[stable(feature = "fmt_flags", since = "1.5.0")]
1119     pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1120
1121     /// Determines if the `-` flag was specified.
1122     #[stable(feature = "fmt_flags", since = "1.5.0")]
1123     pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1124
1125     /// Determines if the `#` flag was specified.
1126     #[stable(feature = "fmt_flags", since = "1.5.0")]
1127     pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1128
1129     /// Determines if the `0` flag was specified.
1130     #[stable(feature = "fmt_flags", since = "1.5.0")]
1131     pub fn sign_aware_zero_pad(&self) -> bool {
1132         self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1133     }
1134
1135     /// Creates a `DebugStruct` builder designed to assist with creation of
1136     /// `fmt::Debug` implementations for structs.
1137     ///
1138     /// # Examples
1139     ///
1140     /// ```rust
1141     /// use std::fmt;
1142     ///
1143     /// struct Foo {
1144     ///     bar: i32,
1145     ///     baz: String,
1146     /// }
1147     ///
1148     /// impl fmt::Debug for Foo {
1149     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1150     ///         fmt.debug_struct("Foo")
1151     ///             .field("bar", &self.bar)
1152     ///             .field("baz", &self.baz)
1153     ///             .finish()
1154     ///     }
1155     /// }
1156     ///
1157     /// // prints "Foo { bar: 10, baz: "Hello World" }"
1158     /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1159     /// ```
1160     #[stable(feature = "debug_builders", since = "1.2.0")]
1161     #[inline]
1162     pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1163         builders::debug_struct_new(self, name)
1164     }
1165
1166     /// Creates a `DebugTuple` builder designed to assist with creation of
1167     /// `fmt::Debug` implementations for tuple structs.
1168     ///
1169     /// # Examples
1170     ///
1171     /// ```rust
1172     /// use std::fmt;
1173     ///
1174     /// struct Foo(i32, String);
1175     ///
1176     /// impl fmt::Debug for Foo {
1177     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1178     ///         fmt.debug_tuple("Foo")
1179     ///             .field(&self.0)
1180     ///             .field(&self.1)
1181     ///             .finish()
1182     ///     }
1183     /// }
1184     ///
1185     /// // prints "Foo(10, "Hello World")"
1186     /// println!("{:?}", Foo(10, "Hello World".to_string()));
1187     /// ```
1188     #[stable(feature = "debug_builders", since = "1.2.0")]
1189     #[inline]
1190     pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1191         builders::debug_tuple_new(self, name)
1192     }
1193
1194     /// Creates a `DebugList` builder designed to assist with creation of
1195     /// `fmt::Debug` implementations for list-like structures.
1196     ///
1197     /// # Examples
1198     ///
1199     /// ```rust
1200     /// use std::fmt;
1201     ///
1202     /// struct Foo(Vec<i32>);
1203     ///
1204     /// impl fmt::Debug for Foo {
1205     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1206     ///         fmt.debug_list().entries(self.0.iter()).finish()
1207     ///     }
1208     /// }
1209     ///
1210     /// // prints "[10, 11]"
1211     /// println!("{:?}", Foo(vec![10, 11]));
1212     /// ```
1213     #[stable(feature = "debug_builders", since = "1.2.0")]
1214     #[inline]
1215     pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1216         builders::debug_list_new(self)
1217     }
1218
1219     /// Creates a `DebugSet` builder designed to assist with creation of
1220     /// `fmt::Debug` implementations for set-like structures.
1221     ///
1222     /// # Examples
1223     ///
1224     /// ```rust
1225     /// use std::fmt;
1226     ///
1227     /// struct Foo(Vec<i32>);
1228     ///
1229     /// impl fmt::Debug for Foo {
1230     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1231     ///         fmt.debug_set().entries(self.0.iter()).finish()
1232     ///     }
1233     /// }
1234     ///
1235     /// // prints "{10, 11}"
1236     /// println!("{:?}", Foo(vec![10, 11]));
1237     /// ```
1238     #[stable(feature = "debug_builders", since = "1.2.0")]
1239     #[inline]
1240     pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1241         builders::debug_set_new(self)
1242     }
1243
1244     /// Creates a `DebugMap` builder designed to assist with creation of
1245     /// `fmt::Debug` implementations for map-like structures.
1246     ///
1247     /// # Examples
1248     ///
1249     /// ```rust
1250     /// use std::fmt;
1251     ///
1252     /// struct Foo(Vec<(String, i32)>);
1253     ///
1254     /// impl fmt::Debug for Foo {
1255     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1256     ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1257     ///     }
1258     /// }
1259     ///
1260     /// // prints "{"A": 10, "B": 11}"
1261     /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1262     /// ```
1263     #[stable(feature = "debug_builders", since = "1.2.0")]
1264     #[inline]
1265     pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1266         builders::debug_map_new(self)
1267     }
1268 }
1269
1270 #[stable(since = "1.2.0", feature = "formatter_write")]
1271 impl<'a> Write for Formatter<'a> {
1272     fn write_str(&mut self, s: &str) -> Result {
1273         self.buf.write_str(s)
1274     }
1275
1276     fn write_char(&mut self, c: char) -> Result {
1277         self.buf.write_char(c)
1278     }
1279
1280     fn write_fmt(&mut self, args: Arguments) -> Result {
1281         write(self.buf, args)
1282     }
1283 }
1284
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl Display for Error {
1287     fn fmt(&self, f: &mut Formatter) -> Result {
1288         Display::fmt("an error occurred when formatting an argument", f)
1289     }
1290 }
1291
1292 // Implementations of the core formatting traits
1293
1294 macro_rules! fmt_refs {
1295     ($($tr:ident),*) => {
1296         $(
1297         #[stable(feature = "rust1", since = "1.0.0")]
1298         impl<'a, T: ?Sized + $tr> $tr for &'a T {
1299             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1300         }
1301         #[stable(feature = "rust1", since = "1.0.0")]
1302         impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1303             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1304         }
1305         )*
1306     }
1307 }
1308
1309 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1310
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl Debug for bool {
1313     fn fmt(&self, f: &mut Formatter) -> Result {
1314         Display::fmt(self, f)
1315     }
1316 }
1317
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl Display for bool {
1320     fn fmt(&self, f: &mut Formatter) -> Result {
1321         Display::fmt(if *self { "true" } else { "false" }, f)
1322     }
1323 }
1324
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 impl Debug for str {
1327     fn fmt(&self, f: &mut Formatter) -> Result {
1328         try!(f.write_char('"'));
1329         let mut from = 0;
1330         for (i, c) in self.char_indices() {
1331             let esc = c.escape_default();
1332             // If char needs escaping, flush backlog so far and write, else skip
1333             if esc.size_hint() != (1, Some(1)) {
1334                 try!(f.write_str(&self[from..i]));
1335                 for c in esc {
1336                     try!(f.write_char(c));
1337                 }
1338                 from = i + c.len_utf8();
1339             }
1340         }
1341         try!(f.write_str(&self[from..]));
1342         f.write_char('"')
1343     }
1344 }
1345
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 impl Display for str {
1348     fn fmt(&self, f: &mut Formatter) -> Result {
1349         f.pad(self)
1350     }
1351 }
1352
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 impl Debug for char {
1355     fn fmt(&self, f: &mut Formatter) -> Result {
1356         try!(f.write_char('\''));
1357         for c in self.escape_default() {
1358             try!(f.write_char(c))
1359         }
1360         f.write_char('\'')
1361     }
1362 }
1363
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 impl Display for char {
1366     fn fmt(&self, f: &mut Formatter) -> Result {
1367         if f.width.is_none() && f.precision.is_none() {
1368             f.write_char(*self)
1369         } else {
1370             let mut utf8 = [0; 4];
1371             let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
1372             let s: &str = unsafe { str::from_utf8_unchecked(&utf8[..amt]) };
1373             f.pad(s)
1374         }
1375     }
1376 }
1377
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 impl<T> Pointer for *const T {
1380     fn fmt(&self, f: &mut Formatter) -> Result {
1381         let old_width = f.width;
1382         let old_flags = f.flags;
1383
1384         // The alternate flag is already treated by LowerHex as being special-
1385         // it denotes whether to prefix with 0x. We use it to work out whether
1386         // or not to zero extend, and then unconditionally set it to get the
1387         // prefix.
1388         if f.alternate() {
1389             f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1390
1391             if let None = f.width {
1392                 f.width = Some((::usize::BITS/4) + 2);
1393             }
1394         }
1395         f.flags |= 1 << (FlagV1::Alternate as u32);
1396
1397         let ret = LowerHex::fmt(&(*self as usize), f);
1398
1399         f.width = old_width;
1400         f.flags = old_flags;
1401
1402         ret
1403     }
1404 }
1405
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 impl<T> Pointer for *mut T {
1408     fn fmt(&self, f: &mut Formatter) -> Result {
1409         // FIXME(#23542) Replace with type ascription.
1410         #![allow(trivial_casts)]
1411         Pointer::fmt(&(*self as *const T), f)
1412     }
1413 }
1414
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 impl<'a, T> Pointer for &'a T {
1417     fn fmt(&self, f: &mut Formatter) -> Result {
1418         // FIXME(#23542) Replace with type ascription.
1419         #![allow(trivial_casts)]
1420         Pointer::fmt(&(*self as *const T), f)
1421     }
1422 }
1423
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 impl<'a, T> Pointer for &'a mut T {
1426     fn fmt(&self, f: &mut Formatter) -> Result {
1427         // FIXME(#23542) Replace with type ascription.
1428         #![allow(trivial_casts)]
1429         Pointer::fmt(&(&**self as *const T), f)
1430     }
1431 }
1432
1433 // Common code of floating point Debug and Display.
1434 fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
1435     where T: flt2dec::DecodableFloat
1436 {
1437     let force_sign = fmt.sign_plus();
1438     let sign = match (force_sign, negative_zero) {
1439         (false, false) => flt2dec::Sign::Minus,
1440         (false, true)  => flt2dec::Sign::MinusRaw,
1441         (true,  false) => flt2dec::Sign::MinusPlus,
1442         (true,  true)  => flt2dec::Sign::MinusPlusRaw,
1443     };
1444
1445     let mut buf = [0; 1024]; // enough for f32 and f64
1446     let mut parts = [flt2dec::Part::Zero(0); 16];
1447     let formatted = if let Some(precision) = fmt.precision {
1448         flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1449                                     precision, false, &mut buf, &mut parts)
1450     } else {
1451         flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1452                                  0, false, &mut buf, &mut parts)
1453     };
1454     fmt.pad_formatted_parts(&formatted)
1455 }
1456
1457 // Common code of floating point LowerExp and UpperExp.
1458 fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
1459     where T: flt2dec::DecodableFloat
1460 {
1461     let force_sign = fmt.sign_plus();
1462     let sign = match force_sign {
1463         false => flt2dec::Sign::Minus,
1464         true  => flt2dec::Sign::MinusPlus,
1465     };
1466
1467     let mut buf = [0; 1024]; // enough for f32 and f64
1468     let mut parts = [flt2dec::Part::Zero(0); 16];
1469     let formatted = if let Some(precision) = fmt.precision {
1470         // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1471         flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1472                                   precision + 1, upper, &mut buf, &mut parts)
1473     } else {
1474         flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1475                                      (0, 0), upper, &mut buf, &mut parts)
1476     };
1477     fmt.pad_formatted_parts(&formatted)
1478 }
1479
1480 macro_rules! floating { ($ty:ident) => {
1481
1482     #[stable(feature = "rust1", since = "1.0.0")]
1483     impl Debug for $ty {
1484         fn fmt(&self, fmt: &mut Formatter) -> Result {
1485             float_to_decimal_common(fmt, self, true)
1486         }
1487     }
1488
1489     #[stable(feature = "rust1", since = "1.0.0")]
1490     impl Display for $ty {
1491         fn fmt(&self, fmt: &mut Formatter) -> Result {
1492             float_to_decimal_common(fmt, self, false)
1493         }
1494     }
1495
1496     #[stable(feature = "rust1", since = "1.0.0")]
1497     impl LowerExp for $ty {
1498         fn fmt(&self, fmt: &mut Formatter) -> Result {
1499             float_to_exponential_common(fmt, self, false)
1500         }
1501     }
1502
1503     #[stable(feature = "rust1", since = "1.0.0")]
1504     impl UpperExp for $ty {
1505         fn fmt(&self, fmt: &mut Formatter) -> Result {
1506             float_to_exponential_common(fmt, self, true)
1507         }
1508     }
1509 } }
1510 floating! { f32 }
1511 floating! { f64 }
1512
1513 // Implementation of Display/Debug for various core types
1514
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 impl<T> Debug for *const T {
1517     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1518 }
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<T> Debug for *mut T {
1521     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1522 }
1523
1524 macro_rules! peel {
1525     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1526 }
1527
1528 macro_rules! tuple {
1529     () => ();
1530     ( $($name:ident,)+ ) => (
1531         #[stable(feature = "rust1", since = "1.0.0")]
1532         impl<$($name:Debug),*> Debug for ($($name,)*) {
1533             #[allow(non_snake_case, unused_assignments)]
1534             fn fmt(&self, f: &mut Formatter) -> Result {
1535                 let mut builder = f.debug_tuple("");
1536                 let ($(ref $name,)*) = *self;
1537                 let mut n = 0;
1538                 $(
1539                     builder.field($name);
1540                     n += 1;
1541                 )*
1542
1543                 if n == 1 {
1544                     try!(write!(builder.formatter(), ","));
1545                 }
1546
1547                 builder.finish()
1548             }
1549         }
1550         peel! { $($name,)* }
1551     )
1552 }
1553
1554 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1555
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 impl<T: Debug> Debug for [T] {
1558     fn fmt(&self, f: &mut Formatter) -> Result {
1559         f.debug_list().entries(self.iter()).finish()
1560     }
1561 }
1562
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 impl Debug for () {
1565     fn fmt(&self, f: &mut Formatter) -> Result {
1566         f.pad("()")
1567     }
1568 }
1569 impl<T> Debug for PhantomData<T> {
1570     fn fmt(&self, f: &mut Formatter) -> Result {
1571         f.pad("PhantomData")
1572     }
1573 }
1574
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl<T: Copy + Debug> Debug for Cell<T> {
1577     fn fmt(&self, f: &mut Formatter) -> Result {
1578         write!(f, "Cell {{ value: {:?} }}", self.get())
1579     }
1580 }
1581
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1584     fn fmt(&self, f: &mut Formatter) -> Result {
1585         match self.borrow_state() {
1586             BorrowState::Unused | BorrowState::Reading => {
1587                 write!(f, "RefCell {{ value: {:?} }}", self.borrow())
1588             }
1589             BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
1590         }
1591     }
1592 }
1593
1594 #[stable(feature = "rust1", since = "1.0.0")]
1595 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1596     fn fmt(&self, f: &mut Formatter) -> Result {
1597         Debug::fmt(&**self, f)
1598     }
1599 }
1600
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1603     fn fmt(&self, f: &mut Formatter) -> Result {
1604         Debug::fmt(&*(self.deref()), f)
1605     }
1606 }
1607
1608 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1609 // it's a lot easier than creating all of the rt::Piece structures here.