]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/mod.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[rust.git] / src / libcore / fmt / mod.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Utilities for formatting and printing strings
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use any;
16 use cell::{Cell, RefCell, Ref, RefMut, BorrowState};
17 use char::CharExt;
18 use iter::{Iterator, IteratorExt};
19 use marker::{Copy, Sized};
20 use mem;
21 use option::Option;
22 use option::Option::{Some, None};
23 use result::Result::Ok;
24 use ops::{Deref, FnOnce};
25 use result;
26 use slice::SliceExt;
27 use slice;
28 use str::{self, StrExt};
29 use self::rt::v1::Alignment;
30
31 pub use self::num::radix;
32 pub use self::num::Radix;
33 pub use self::num::RadixFmt;
34
35 mod num;
36 mod float;
37
38 #[stable(feature = "rust1", since = "1.0.0")]
39 #[doc(hidden)]
40 pub mod rt {
41     pub mod v1;
42 }
43
44 #[stable(feature = "rust1", since = "1.0.0")]
45 /// The type returned by formatter methods.
46 pub type Result = result::Result<(), Error>;
47
48 /// The error type which is returned from formatting a message into a stream.
49 ///
50 /// This type does not support transmission of an error other than that an error
51 /// occurred. Any extra information must be arranged to be transmitted through
52 /// some other means.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 #[derive(Copy, Debug)]
55 pub struct Error;
56
57 /// A collection of methods that are required to format a message into a stream.
58 ///
59 /// This trait is the type which this modules requires when formatting
60 /// information. This is similar to the standard library's `io::Write` trait,
61 /// but it is only intended for use in libcore.
62 ///
63 /// This trait should generally not be implemented by consumers of the standard
64 /// library. The `write!` macro accepts an instance of `io::Write`, and the
65 /// `io::Write` trait is favored over implementing this trait.
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub trait Write {
68     /// Writes a slice of bytes into this writer, returning whether the write
69     /// succeeded.
70     ///
71     /// This method can only succeed if the entire byte slice was successfully
72     /// written, and this method will not return until all data has been
73     /// written or an error occurs.
74     ///
75     /// # Errors
76     ///
77     /// This function will return an instance of `FormatError` on error.
78     #[stable(feature = "rust1", since = "1.0.0")]
79     fn write_str(&mut self, s: &str) -> Result;
80
81     /// Glue for usage of the `write!` macro with implementers of this trait.
82     ///
83     /// This method should generally not be invoked manually, but rather through
84     /// the `write!` macro itself.
85     #[stable(feature = "rust1", since = "1.0.0")]
86     fn write_fmt(&mut self, args: Arguments) -> Result {
87         // This Adapter is needed to allow `self` (of type `&mut
88         // Self`) to be cast to a Write (below) without
89         // requiring a `Sized` bound.
90         struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
91
92         impl<'a, T: ?Sized> Write for Adapter<'a, T>
93             where T: Write
94         {
95             fn write_str(&mut self, s: &str) -> Result {
96                 self.0.write_str(s)
97             }
98
99             fn write_fmt(&mut self, args: Arguments) -> Result {
100                 self.0.write_fmt(args)
101             }
102         }
103
104         write(&mut Adapter(self), args)
105     }
106 }
107
108 /// A struct to represent both where to emit formatting strings to and how they
109 /// should be formatted. A mutable version of this is passed to all formatting
110 /// traits.
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct Formatter<'a> {
113     flags: uint,
114     fill: char,
115     align: rt::v1::Alignment,
116     width: Option<uint>,
117     precision: Option<uint>,
118
119     buf: &'a mut (Write+'a),
120     curarg: slice::Iter<'a, ArgumentV1<'a>>,
121     args: &'a [ArgumentV1<'a>],
122 }
123
124 // NB. Argument is essentially an optimized partially applied formatting function,
125 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
126
127 enum Void {}
128
129 /// This struct represents the generic "argument" which is taken by the Xprintf
130 /// family of functions. It contains a function to format the given value. At
131 /// compile time it is ensured that the function and the value have the correct
132 /// types, and then this struct is used to canonicalize arguments to one type.
133 #[derive(Copy)]
134 #[stable(feature = "rust1", since = "1.0.0")]
135 #[doc(hidden)]
136 pub struct ArgumentV1<'a> {
137     value: &'a Void,
138     formatter: fn(&Void, &mut Formatter) -> Result,
139 }
140
141 impl<'a> ArgumentV1<'a> {
142     #[inline(never)]
143     fn show_uint(x: &uint, f: &mut Formatter) -> Result {
144         Display::fmt(x, f)
145     }
146
147     #[doc(hidden)]
148     #[stable(feature = "rust1", since = "1.0.0")]
149     pub fn new<'b, T>(x: &'b T,
150                       f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
151         unsafe {
152             ArgumentV1 {
153                 formatter: mem::transmute(f),
154                 value: mem::transmute(x)
155             }
156         }
157     }
158
159     #[doc(hidden)]
160     #[stable(feature = "rust1", since = "1.0.0")]
161     pub fn from_uint(x: &uint) -> ArgumentV1 {
162         ArgumentV1::new(x, ArgumentV1::show_uint)
163     }
164
165     fn as_uint(&self) -> Option<uint> {
166         if self.formatter as uint == ArgumentV1::show_uint as uint {
167             Some(unsafe { *(self.value as *const _ as *const uint) })
168         } else {
169             None
170         }
171     }
172 }
173
174 // flags available in the v1 format of format_args
175 #[derive(Copy)]
176 #[allow(dead_code)] // SignMinus isn't currently used
177 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
178
179 impl<'a> Arguments<'a> {
180     /// When using the format_args!() macro, this function is used to generate the
181     /// Arguments structure.
182     #[doc(hidden)] #[inline]
183     #[stable(feature = "rust1", since = "1.0.0")]
184     pub fn new_v1(pieces: &'a [&'a str],
185                   args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
186         Arguments {
187             pieces: pieces,
188             fmt: None,
189             args: args
190         }
191     }
192
193     /// This function is used to specify nonstandard formatting parameters.
194     /// The `pieces` array must be at least as long as `fmt` to construct
195     /// a valid Arguments structure. Also, any `Count` within `fmt` that is
196     /// `CountIsParam` or `CountIsNextParam` has to point to an argument
197     /// created with `argumentuint`. However, failing to do so doesn't cause
198     /// unsafety, but will ignore invalid .
199     #[doc(hidden)] #[inline]
200     #[stable(feature = "rust1", since = "1.0.0")]
201     pub fn new_v1_formatted(pieces: &'a [&'a str],
202                             args: &'a [ArgumentV1<'a>],
203                             fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
204         Arguments {
205             pieces: pieces,
206             fmt: Some(fmt),
207             args: args
208         }
209     }
210 }
211
212 /// This structure represents a safely precompiled version of a format string
213 /// and its arguments. This cannot be generated at runtime because it cannot
214 /// safely be done so, so no constructors are given and the fields are private
215 /// to prevent modification.
216 ///
217 /// The `format_args!` macro will safely create an instance of this structure
218 /// and pass it to a function or closure, passed as the first argument. The
219 /// macro validates the format string at compile-time so usage of the `write`
220 /// and `format` functions can be safely performed.
221 #[stable(feature = "rust1", since = "1.0.0")]
222 #[derive(Copy)]
223 pub struct Arguments<'a> {
224     // Format string pieces to print.
225     pieces: &'a [&'a str],
226
227     // Placeholder specs, or `None` if all specs are default (as in "{}{}").
228     fmt: Option<&'a [rt::v1::Argument]>,
229
230     // Dynamic arguments for interpolation, to be interleaved with string
231     // pieces. (Every argument is preceded by a string piece.)
232     args: &'a [ArgumentV1<'a>],
233 }
234
235 #[stable(feature = "rust1", since = "1.0.0")]
236 impl<'a> Debug for Arguments<'a> {
237     fn fmt(&self, fmt: &mut Formatter) -> Result {
238         Display::fmt(self, fmt)
239     }
240 }
241
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl<'a> Display for Arguments<'a> {
244     fn fmt(&self, fmt: &mut Formatter) -> Result {
245         write(fmt.buf, *self)
246     }
247 }
248
249 /// Format trait for the `:?` format. Useful for debugging, all types
250 /// should implement this.
251 #[deprecated(since = "1.0.0", reason = "renamed to Debug")]
252 #[unstable(feature = "old_fmt")]
253 pub trait Show {
254     /// Formats the value using the given formatter.
255     #[stable(feature = "rust1", since = "1.0.0")]
256     fn fmt(&self, &mut Formatter) -> Result;
257 }
258
259 /// Format trait for the `:?` format. Useful for debugging, all types
260 /// should implement this.
261 #[stable(feature = "rust1", since = "1.0.0")]
262 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
263                             defined in your crate, add `#[derive(Debug)]` or \
264                             manually implement it"]
265 #[lang = "debug_trait"]
266 pub trait Debug {
267     /// Formats the value using the given formatter.
268     #[stable(feature = "rust1", since = "1.0.0")]
269     fn fmt(&self, &mut Formatter) -> Result;
270 }
271
272 #[allow(deprecated)]
273 impl<T: Show + ?Sized> Debug for T {
274     #[allow(deprecated)]
275     fn fmt(&self, f: &mut Formatter) -> Result { Show::fmt(self, f) }
276 }
277
278 /// When a value can be semantically expressed as a String, this trait may be
279 /// used. It corresponds to the default format, `{}`.
280 #[deprecated(since = "1.0.0", reason = "renamed to Display")]
281 #[unstable(feature = "old_fmt")]
282 pub trait String {
283     /// Formats the value using the given formatter.
284     #[stable(feature = "rust1", since = "1.0.0")]
285     fn fmt(&self, &mut Formatter) -> Result;
286 }
287
288 /// When a value can be semantically expressed as a String, this trait may be
289 /// used. It corresponds to the default format, `{}`.
290 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
291                             formatter; try using `:?` instead if you are using \
292                             a format string"]
293 #[stable(feature = "rust1", since = "1.0.0")]
294 pub trait Display {
295     /// Formats the value using the given formatter.
296     #[stable(feature = "rust1", since = "1.0.0")]
297     fn fmt(&self, &mut Formatter) -> Result;
298 }
299
300 #[allow(deprecated)]
301 impl<T: String + ?Sized> Display for T {
302     #[allow(deprecated)]
303     fn fmt(&self, f: &mut Formatter) -> Result { String::fmt(self, f) }
304 }
305
306 /// Format trait for the `o` character
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub trait Octal {
309     /// Formats the value using the given formatter.
310     #[stable(feature = "rust1", since = "1.0.0")]
311     fn fmt(&self, &mut Formatter) -> Result;
312 }
313
314 /// Format trait for the `b` character
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub trait Binary {
317     /// Formats the value using the given formatter.
318     #[stable(feature = "rust1", since = "1.0.0")]
319     fn fmt(&self, &mut Formatter) -> Result;
320 }
321
322 /// Format trait for the `x` character
323 #[stable(feature = "rust1", since = "1.0.0")]
324 pub trait LowerHex {
325     /// Formats the value using the given formatter.
326     #[stable(feature = "rust1", since = "1.0.0")]
327     fn fmt(&self, &mut Formatter) -> Result;
328 }
329
330 /// Format trait for the `X` character
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub trait UpperHex {
333     /// Formats the value using the given formatter.
334     #[stable(feature = "rust1", since = "1.0.0")]
335     fn fmt(&self, &mut Formatter) -> Result;
336 }
337
338 /// Format trait for the `p` character
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub trait Pointer {
341     /// Formats the value using the given formatter.
342     #[stable(feature = "rust1", since = "1.0.0")]
343     fn fmt(&self, &mut Formatter) -> Result;
344 }
345
346 /// Format trait for the `e` character
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub trait LowerExp {
349     /// Formats the value using the given formatter.
350     #[stable(feature = "rust1", since = "1.0.0")]
351     fn fmt(&self, &mut Formatter) -> Result;
352 }
353
354 /// Format trait for the `E` character
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub trait UpperExp {
357     /// Formats the value using the given formatter.
358     #[stable(feature = "rust1", since = "1.0.0")]
359     fn fmt(&self, &mut Formatter) -> Result;
360 }
361
362 /// The `write` function takes an output stream, a precompiled format string,
363 /// and a list of arguments. The arguments will be formatted according to the
364 /// specified format string into the output stream provided.
365 ///
366 /// # Arguments
367 ///
368 ///   * output - the buffer to write output to
369 ///   * args - the precompiled arguments generated by `format_args!`
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn write(output: &mut Write, args: Arguments) -> Result {
372     let mut formatter = Formatter {
373         flags: 0,
374         width: None,
375         precision: None,
376         buf: output,
377         align: Alignment::Unknown,
378         fill: ' ',
379         args: args.args,
380         curarg: args.args.iter(),
381     };
382
383     let mut pieces = args.pieces.iter();
384
385     match args.fmt {
386         None => {
387             // We can use default formatting parameters for all arguments.
388             for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
389                 try!(formatter.buf.write_str(*piece));
390                 try!((arg.formatter)(arg.value, &mut formatter));
391             }
392         }
393         Some(fmt) => {
394             // Every spec has a corresponding argument that is preceded by
395             // a string piece.
396             for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
397                 try!(formatter.buf.write_str(*piece));
398                 try!(formatter.run(arg));
399             }
400         }
401     }
402
403     // There can be only one trailing string piece left.
404     match pieces.next() {
405         Some(piece) => {
406             try!(formatter.buf.write_str(*piece));
407         }
408         None => {}
409     }
410
411     Ok(())
412 }
413
414 impl<'a> Formatter<'a> {
415
416     // First up is the collection of functions used to execute a format string
417     // at runtime. This consumes all of the compile-time statics generated by
418     // the format! syntax extension.
419     fn run(&mut self, arg: &rt::v1::Argument) -> Result {
420         // Fill in the format parameters into the formatter
421         self.fill = arg.format.fill;
422         self.align = arg.format.align;
423         self.flags = arg.format.flags;
424         self.width = self.getcount(&arg.format.width);
425         self.precision = self.getcount(&arg.format.precision);
426
427         // Extract the correct argument
428         let value = match arg.position {
429             rt::v1::Position::Next => { *self.curarg.next().unwrap() }
430             rt::v1::Position::At(i) => self.args[i],
431         };
432
433         // Then actually do some printing
434         (value.formatter)(value.value, self)
435     }
436
437     fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<uint> {
438         match *cnt {
439             rt::v1::Count::Is(n) => Some(n),
440             rt::v1::Count::Implied => None,
441             rt::v1::Count::Param(i) => {
442                 self.args[i].as_uint()
443             }
444             rt::v1::Count::NextParam => {
445                 self.curarg.next().and_then(|arg| arg.as_uint())
446             }
447         }
448     }
449
450     // Helper methods used for padding and processing formatting arguments that
451     // all formatting traits can use.
452
453     /// Performs the correct padding for an integer which has already been
454     /// emitted into a str. The str should *not* contain the sign for the
455     /// integer, that will be added by this method.
456     ///
457     /// # Arguments
458     ///
459     /// * is_positive - whether the original integer was positive or not.
460     /// * prefix - if the '#' character (FlagAlternate) is provided, this
461     ///   is the prefix to put in front of the number.
462     /// * buf - the byte array that the number has been formatted into
463     ///
464     /// This function will correctly account for the flags provided as well as
465     /// the minimum width. It will not take precision into account.
466     #[stable(feature = "rust1", since = "1.0.0")]
467     pub fn pad_integral(&mut self,
468                         is_positive: bool,
469                         prefix: &str,
470                         buf: &str)
471                         -> Result {
472         use char::CharExt;
473
474         let mut width = buf.len();
475
476         let mut sign = None;
477         if !is_positive {
478             sign = Some('-'); width += 1;
479         } else if self.flags & (1 << (FlagV1::SignPlus as uint)) != 0 {
480             sign = Some('+'); width += 1;
481         }
482
483         let mut prefixed = false;
484         if self.flags & (1 << (FlagV1::Alternate as uint)) != 0 {
485             prefixed = true; width += prefix.char_len();
486         }
487
488         // Writes the sign if it exists, and then the prefix if it was requested
489         let write_prefix = |f: &mut Formatter| {
490             if let Some(c) = sign {
491                 let mut b = [0; 4];
492                 let n = c.encode_utf8(&mut b).unwrap_or(0);
493                 let b = unsafe { str::from_utf8_unchecked(&b[..n]) };
494                 try!(f.buf.write_str(b));
495             }
496             if prefixed { f.buf.write_str(prefix) }
497             else { Ok(()) }
498         };
499
500         // The `width` field is more of a `min-width` parameter at this point.
501         match self.width {
502             // If there's no minimum length requirements then we can just
503             // write the bytes.
504             None => {
505                 try!(write_prefix(self)); self.buf.write_str(buf)
506             }
507             // Check if we're over the minimum width, if so then we can also
508             // just write the bytes.
509             Some(min) if width >= min => {
510                 try!(write_prefix(self)); self.buf.write_str(buf)
511             }
512             // The sign and prefix goes before the padding if the fill character
513             // is zero
514             Some(min) if self.flags & (1 << (FlagV1::SignAwareZeroPad as uint)) != 0 => {
515                 self.fill = '0';
516                 try!(write_prefix(self));
517                 self.with_padding(min - width, Alignment::Right, |f| {
518                     f.buf.write_str(buf)
519                 })
520             }
521             // Otherwise, the sign and prefix goes after the padding
522             Some(min) => {
523                 self.with_padding(min - width, Alignment::Right, |f| {
524                     try!(write_prefix(f)); f.buf.write_str(buf)
525                 })
526             }
527         }
528     }
529
530     /// This function takes a string slice and emits it to the internal buffer
531     /// after applying the relevant formatting flags specified. The flags
532     /// recognized for generic strings are:
533     ///
534     /// * width - the minimum width of what to emit
535     /// * fill/align - what to emit and where to emit it if the string
536     ///                provided needs to be padded
537     /// * precision - the maximum length to emit, the string is truncated if it
538     ///               is longer than this length
539     ///
540     /// Notably this function ignored the `flag` parameters
541     #[stable(feature = "rust1", since = "1.0.0")]
542     pub fn pad(&mut self, s: &str) -> Result {
543         // Make sure there's a fast path up front
544         if self.width.is_none() && self.precision.is_none() {
545             return self.buf.write_str(s);
546         }
547         // The `precision` field can be interpreted as a `max-width` for the
548         // string being formatted
549         match self.precision {
550             Some(max) => {
551                 // If there's a maximum width and our string is longer than
552                 // that, then we must always have truncation. This is the only
553                 // case where the maximum length will matter.
554                 let char_len = s.char_len();
555                 if char_len >= max {
556                     let nchars = ::cmp::min(max, char_len);
557                     return self.buf.write_str(s.slice_chars(0, nchars));
558                 }
559             }
560             None => {}
561         }
562         // The `width` field is more of a `min-width` parameter at this point.
563         match self.width {
564             // If we're under the maximum length, and there's no minimum length
565             // requirements, then we can just emit the string
566             None => self.buf.write_str(s),
567             // If we're under the maximum width, check if we're over the minimum
568             // width, if so it's as easy as just emitting the string.
569             Some(width) if s.char_len() >= width => {
570                 self.buf.write_str(s)
571             }
572             // If we're under both the maximum and the minimum width, then fill
573             // up the minimum width with the specified string + some alignment.
574             Some(width) => {
575                 self.with_padding(width - s.char_len(), Alignment::Left, |me| {
576                     me.buf.write_str(s)
577                 })
578             }
579         }
580     }
581
582     /// Runs a callback, emitting the correct padding either before or
583     /// afterwards depending on whether right or left alignment is requested.
584     fn with_padding<F>(&mut self, padding: uint, default: Alignment,
585                        f: F) -> Result
586         where F: FnOnce(&mut Formatter) -> Result,
587     {
588         use char::CharExt;
589         let align = match self.align {
590             Alignment::Unknown => default,
591             _ => self.align
592         };
593
594         let (pre_pad, post_pad) = match align {
595             Alignment::Left => (0, padding),
596             Alignment::Right | Alignment::Unknown => (padding, 0),
597             Alignment::Center => (padding / 2, (padding + 1) / 2),
598         };
599
600         let mut fill = [0u8; 4];
601         let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
602         let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) };
603
604         for _ in 0..pre_pad {
605             try!(self.buf.write_str(fill));
606         }
607
608         try!(f(self));
609
610         for _ in 0..post_pad {
611             try!(self.buf.write_str(fill));
612         }
613
614         Ok(())
615     }
616
617     /// Writes some data to the underlying buffer contained within this
618     /// formatter.
619     #[stable(feature = "rust1", since = "1.0.0")]
620     pub fn write_str(&mut self, data: &str) -> Result {
621         self.buf.write_str(data)
622     }
623
624     /// Writes some formatted information into this instance
625     #[stable(feature = "rust1", since = "1.0.0")]
626     pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
627         write(self.buf, fmt)
628     }
629
630     /// Flags for formatting (packed version of rt::Flag)
631     #[stable(feature = "rust1", since = "1.0.0")]
632     pub fn flags(&self) -> usize { self.flags }
633
634     /// Character used as 'fill' whenever there is alignment
635     #[unstable(feature = "core", reason = "method was just created")]
636     pub fn fill(&self) -> char { self.fill }
637
638     /// Flag indicating what form of alignment was requested
639     #[unstable(feature = "core", reason = "method was just created")]
640     pub fn align(&self) -> Alignment { self.align }
641
642     /// Optionally specified integer width that the output should be
643     #[unstable(feature = "core", reason = "method was just created")]
644     pub fn width(&self) -> Option<uint> { self.width }
645
646     /// Optionally specified precision for numeric types
647     #[unstable(feature = "core", reason = "method was just created")]
648     pub fn precision(&self) -> Option<uint> { self.precision }
649 }
650
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl Display for Error {
653     fn fmt(&self, f: &mut Formatter) -> Result {
654         Display::fmt("an error occurred when formatting an argument", f)
655     }
656 }
657
658 // Implementations of the core formatting traits
659
660 macro_rules! fmt_refs {
661     ($($tr:ident),*) => {
662         $(
663         #[stable(feature = "rust1", since = "1.0.0")]
664         impl<'a, T: ?Sized + $tr> $tr for &'a T {
665             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
666         }
667         #[stable(feature = "rust1", since = "1.0.0")]
668         impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
669             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
670         }
671         )*
672     }
673 }
674
675 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
676
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl Debug for bool {
679     fn fmt(&self, f: &mut Formatter) -> Result {
680         Display::fmt(self, f)
681     }
682 }
683
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl Display for bool {
686     fn fmt(&self, f: &mut Formatter) -> Result {
687         Display::fmt(if *self { "true" } else { "false" }, f)
688     }
689 }
690
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl Debug for str {
693     fn fmt(&self, f: &mut Formatter) -> Result {
694         try!(write!(f, "\""));
695         for c in self.chars().flat_map(|c| c.escape_default()) {
696             try!(write!(f, "{}", c));
697         }
698         write!(f, "\"")
699     }
700 }
701
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl Display for str {
704     fn fmt(&self, f: &mut Formatter) -> Result {
705         f.pad(self)
706     }
707 }
708
709 #[stable(feature = "rust1", since = "1.0.0")]
710 impl Debug for char {
711     fn fmt(&self, f: &mut Formatter) -> Result {
712         use char::CharExt;
713         try!(write!(f, "'"));
714         for c in self.escape_default() {
715             try!(write!(f, "{}", c));
716         }
717         write!(f, "'")
718     }
719 }
720
721 #[stable(feature = "rust1", since = "1.0.0")]
722 impl Display for char {
723     fn fmt(&self, f: &mut Formatter) -> Result {
724         let mut utf8 = [0u8; 4];
725         let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
726         let s: &str = unsafe { mem::transmute(&utf8[..amt]) };
727         Display::fmt(s, f)
728     }
729 }
730
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl<T> Pointer for *const T {
733     fn fmt(&self, f: &mut Formatter) -> Result {
734         f.flags |= 1 << (FlagV1::Alternate as uint);
735         let ret = LowerHex::fmt(&(*self as uint), f);
736         f.flags &= !(1 << (FlagV1::Alternate as uint));
737         ret
738     }
739 }
740
741 #[stable(feature = "rust1", since = "1.0.0")]
742 impl<T> Pointer for *mut T {
743     fn fmt(&self, f: &mut Formatter) -> Result {
744         Pointer::fmt(&(*self as *const T), f)
745     }
746 }
747
748 #[stable(feature = "rust1", since = "1.0.0")]
749 impl<'a, T> Pointer for &'a T {
750     fn fmt(&self, f: &mut Formatter) -> Result {
751         Pointer::fmt(&(*self as *const T), f)
752     }
753 }
754
755 #[stable(feature = "rust1", since = "1.0.0")]
756 impl<'a, T> Pointer for &'a mut T {
757     fn fmt(&self, f: &mut Formatter) -> Result {
758         Pointer::fmt(&(&**self as *const T), f)
759     }
760 }
761
762 macro_rules! floating { ($ty:ident) => {
763
764     #[stable(feature = "rust1", since = "1.0.0")]
765     impl Debug for $ty {
766         fn fmt(&self, fmt: &mut Formatter) -> Result {
767             Display::fmt(self, fmt)
768         }
769     }
770
771     #[stable(feature = "rust1", since = "1.0.0")]
772     impl Display for $ty {
773         fn fmt(&self, fmt: &mut Formatter) -> Result {
774             use num::Float;
775
776             let digits = match fmt.precision {
777                 Some(i) => float::DigExact(i),
778                 None => float::DigMax(6),
779             };
780             float::float_to_str_bytes_common(self.abs(),
781                                              10,
782                                              true,
783                                              float::SignNeg,
784                                              digits,
785                                              float::ExpNone,
786                                              false,
787                                              |bytes| {
788                 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
789             })
790         }
791     }
792
793     #[stable(feature = "rust1", since = "1.0.0")]
794     impl LowerExp for $ty {
795         fn fmt(&self, fmt: &mut Formatter) -> Result {
796             use num::Float;
797
798             let digits = match fmt.precision {
799                 Some(i) => float::DigExact(i),
800                 None => float::DigMax(6),
801             };
802             float::float_to_str_bytes_common(self.abs(),
803                                              10,
804                                              true,
805                                              float::SignNeg,
806                                              digits,
807                                              float::ExpDec,
808                                              false,
809                                              |bytes| {
810                 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
811             })
812         }
813     }
814
815     #[stable(feature = "rust1", since = "1.0.0")]
816     impl UpperExp for $ty {
817         fn fmt(&self, fmt: &mut Formatter) -> Result {
818             use num::Float;
819
820             let digits = match fmt.precision {
821                 Some(i) => float::DigExact(i),
822                 None => float::DigMax(6),
823             };
824             float::float_to_str_bytes_common(self.abs(),
825                                              10,
826                                              true,
827                                              float::SignNeg,
828                                              digits,
829                                              float::ExpDec,
830                                              true,
831                                              |bytes| {
832                 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
833             })
834         }
835     }
836 } }
837 floating! { f32 }
838 floating! { f64 }
839
840 // Implementation of Display/Debug for various core types
841
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<T> Debug for *const T {
844     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
845 }
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl<T> Debug for *mut T {
848     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
849 }
850
851 macro_rules! peel {
852     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
853 }
854
855 macro_rules! tuple {
856     () => ();
857     ( $($name:ident,)+ ) => (
858         #[stable(feature = "rust1", since = "1.0.0")]
859         impl<$($name:Debug),*> Debug for ($($name,)*) {
860             #[allow(non_snake_case, unused_assignments)]
861             fn fmt(&self, f: &mut Formatter) -> Result {
862                 try!(write!(f, "("));
863                 let ($(ref $name,)*) = *self;
864                 let mut n = 0;
865                 $(
866                     if n > 0 {
867                         try!(write!(f, ", "));
868                     }
869                     try!(write!(f, "{:?}", *$name));
870                     n += 1;
871                 )*
872                 if n == 1 {
873                     try!(write!(f, ","));
874                 }
875                 write!(f, ")")
876             }
877         }
878         peel! { $($name,)* }
879     )
880 }
881
882 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
883
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl<'a> Debug for &'a (any::Any+'a) {
886     fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") }
887 }
888
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl<T: Debug> Debug for [T] {
891     fn fmt(&self, f: &mut Formatter) -> Result {
892         if f.flags & (1 << (FlagV1::Alternate as uint)) == 0 {
893             try!(write!(f, "["));
894         }
895         let mut is_first = true;
896         for x in self {
897             if is_first {
898                 is_first = false;
899             } else {
900                 try!(write!(f, ", "));
901             }
902             try!(write!(f, "{:?}", *x))
903         }
904         if f.flags & (1 << (FlagV1::Alternate as uint)) == 0 {
905             try!(write!(f, "]"));
906         }
907         Ok(())
908     }
909 }
910
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl Debug for () {
913     fn fmt(&self, f: &mut Formatter) -> Result {
914         f.pad("()")
915     }
916 }
917
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl<T: Copy + Debug> Debug for Cell<T> {
920     fn fmt(&self, f: &mut Formatter) -> Result {
921         write!(f, "Cell {{ value: {:?} }}", self.get())
922     }
923 }
924
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<T: Debug> Debug for RefCell<T> {
927     fn fmt(&self, f: &mut Formatter) -> Result {
928         match self.borrow_state() {
929             BorrowState::Unused | BorrowState::Reading => {
930                 write!(f, "RefCell {{ value: {:?} }}", self.borrow())
931             }
932             BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
933         }
934     }
935 }
936
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'b, T: Debug> Debug for Ref<'b, T> {
939     fn fmt(&self, f: &mut Formatter) -> Result {
940         Debug::fmt(&**self, f)
941     }
942 }
943
944 #[stable(feature = "rust1", since = "1.0.0")]
945 impl<'b, T: Debug> Debug for RefMut<'b, T> {
946     fn fmt(&self, f: &mut Formatter) -> Result {
947         Debug::fmt(&*(self.deref()), f)
948     }
949 }
950
951 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
952 // it's a lot easier than creating all of the rt::Piece structures here.