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