]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/mod.rs
f940300a26945cf84ed29536f217ec28a4f5fb9e
[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::Writer` 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::Writer`, and the
65 /// `io::Writer` trait is favored over implementing this trait.
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub trait Writer {
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 FormatWriter (below) without
89         // requiring a `Sized` bound.
90         struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
91
92         impl<'a, T: ?Sized> Writer for Adapter<'a, T>
93             where T: Writer
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 (Writer+'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     pub fn new_v1_formatted(pieces: &'a [&'a str],
201                             args: &'a [ArgumentV1<'a>],
202                             fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
203         Arguments {
204             pieces: pieces,
205             fmt: Some(fmt),
206             args: args
207         }
208     }
209 }
210
211 /// This structure represents a safely precompiled version of a format string
212 /// and its arguments. This cannot be generated at runtime because it cannot
213 /// safely be done so, so no constructors are given and the fields are private
214 /// to prevent modification.
215 ///
216 /// The `format_args!` macro will safely create an instance of this structure
217 /// and pass it to a function or closure, passed as the first argument. The
218 /// macro validates the format string at compile-time so usage of the `write`
219 /// and `format` functions can be safely performed.
220 #[stable(feature = "rust1", since = "1.0.0")]
221 #[derive(Copy)]
222 pub struct Arguments<'a> {
223     // Format string pieces to print.
224     pieces: &'a [&'a str],
225
226     // Placeholder specs, or `None` if all specs are default (as in "{}{}").
227     fmt: Option<&'a [rt::v1::Argument]>,
228
229     // Dynamic arguments for interpolation, to be interleaved with string
230     // pieces. (Every argument is preceded by a string piece.)
231     args: &'a [ArgumentV1<'a>],
232 }
233
234 #[stable(feature = "rust1", since = "1.0.0")]
235 impl<'a> Debug for Arguments<'a> {
236     fn fmt(&self, fmt: &mut Formatter) -> Result {
237         Display::fmt(self, fmt)
238     }
239 }
240
241 #[stable(feature = "rust1", since = "1.0.0")]
242 impl<'a> Display for Arguments<'a> {
243     fn fmt(&self, fmt: &mut Formatter) -> Result {
244         write(fmt.buf, *self)
245     }
246 }
247
248 /// Format trait for the `:?` format. Useful for debugging, all types
249 /// should implement this.
250 #[deprecated(since = "1.0.0", reason = "renamed to Debug")]
251 #[unstable(feature = "old_fmt")]
252 pub trait Show {
253     /// Formats the value using the given formatter.
254     #[stable(feature = "rust1", since = "1.0.0")]
255     fn fmt(&self, &mut Formatter) -> Result;
256 }
257
258 /// Format trait for the `:?` format. Useful for debugging, all types
259 /// should implement this.
260 #[stable(feature = "rust1", since = "1.0.0")]
261 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
262                             defined in your crate, add `#[derive(Debug)]` or \
263                             manually implement it"]
264 #[lang = "debug_trait"]
265 pub trait Debug {
266     /// Formats the value using the given formatter.
267     #[stable(feature = "rust1", since = "1.0.0")]
268     fn fmt(&self, &mut Formatter) -> Result;
269 }
270
271 #[allow(deprecated)]
272 impl<T: Show + ?Sized> Debug for T {
273     #[allow(deprecated)]
274     fn fmt(&self, f: &mut Formatter) -> Result { Show::fmt(self, f) }
275 }
276
277 /// When a value can be semantically expressed as a String, this trait may be
278 /// used. It corresponds to the default format, `{}`.
279 #[deprecated(since = "1.0.0", reason = "renamed to Display")]
280 #[unstable(feature = "old_fmt")]
281 pub trait String {
282     /// Formats the value using the given formatter.
283     #[stable(feature = "rust1", since = "1.0.0")]
284     fn fmt(&self, &mut Formatter) -> Result;
285 }
286
287 /// When a value can be semantically expressed as a String, this trait may be
288 /// used. It corresponds to the default format, `{}`.
289 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
290                             formatter; try using `:?` instead if you are using \
291                             a format string"]
292 #[stable(feature = "rust1", since = "1.0.0")]
293 pub trait Display {
294     /// Formats the value using the given formatter.
295     #[stable(feature = "rust1", since = "1.0.0")]
296     fn fmt(&self, &mut Formatter) -> Result;
297 }
298
299 #[allow(deprecated)]
300 impl<T: String + ?Sized> Display for T {
301     #[allow(deprecated)]
302     fn fmt(&self, f: &mut Formatter) -> Result { String::fmt(self, f) }
303 }
304
305 /// Format trait for the `o` character
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub trait Octal {
308     /// Formats the value using the given formatter.
309     #[stable(feature = "rust1", since = "1.0.0")]
310     fn fmt(&self, &mut Formatter) -> Result;
311 }
312
313 /// Format trait for the `b` character
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub trait Binary {
316     /// Formats the value using the given formatter.
317     #[stable(feature = "rust1", since = "1.0.0")]
318     fn fmt(&self, &mut Formatter) -> Result;
319 }
320
321 /// Format trait for the `x` character
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub trait LowerHex {
324     /// Formats the value using the given formatter.
325     #[stable(feature = "rust1", since = "1.0.0")]
326     fn fmt(&self, &mut Formatter) -> Result;
327 }
328
329 /// Format trait for the `X` character
330 #[stable(feature = "rust1", since = "1.0.0")]
331 pub trait UpperHex {
332     /// Formats the value using the given formatter.
333     #[stable(feature = "rust1", since = "1.0.0")]
334     fn fmt(&self, &mut Formatter) -> Result;
335 }
336
337 /// Format trait for the `p` character
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub trait Pointer {
340     /// Formats the value using the given formatter.
341     #[stable(feature = "rust1", since = "1.0.0")]
342     fn fmt(&self, &mut Formatter) -> Result;
343 }
344
345 /// Format trait for the `e` character
346 #[stable(feature = "rust1", since = "1.0.0")]
347 pub trait LowerExp {
348     /// Formats the value using the given formatter.
349     #[stable(feature = "rust1", since = "1.0.0")]
350     fn fmt(&self, &mut Formatter) -> Result;
351 }
352
353 /// Format trait for the `E` character
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub trait UpperExp {
356     /// Formats the value using the given formatter.
357     #[stable(feature = "rust1", since = "1.0.0")]
358     fn fmt(&self, &mut Formatter) -> Result;
359 }
360
361 /// The `write` function takes an output stream, a precompiled format string,
362 /// and a list of arguments. The arguments will be formatted according to the
363 /// specified format string into the output stream provided.
364 ///
365 /// # Arguments
366 ///
367 ///   * output - the buffer to write output to
368 ///   * args - the precompiled arguments generated by `format_args!`
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn write(output: &mut Writer, args: Arguments) -> Result {
371     let mut formatter = Formatter {
372         flags: 0,
373         width: None,
374         precision: None,
375         buf: output,
376         align: Alignment::Unknown,
377         fill: ' ',
378         args: args.args,
379         curarg: args.args.iter(),
380     };
381
382     let mut pieces = args.pieces.iter();
383
384     match args.fmt {
385         None => {
386             // We can use default formatting parameters for all arguments.
387             for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
388                 try!(formatter.buf.write_str(*piece));
389                 try!((arg.formatter)(arg.value, &mut formatter));
390             }
391         }
392         Some(fmt) => {
393             // Every spec has a corresponding argument that is preceded by
394             // a string piece.
395             for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
396                 try!(formatter.buf.write_str(*piece));
397                 try!(formatter.run(arg));
398             }
399         }
400     }
401
402     // There can be only one trailing string piece left.
403     match pieces.next() {
404         Some(piece) => {
405             try!(formatter.buf.write_str(*piece));
406         }
407         None => {}
408     }
409
410     Ok(())
411 }
412
413 impl<'a> Formatter<'a> {
414
415     // First up is the collection of functions used to execute a format string
416     // at runtime. This consumes all of the compile-time statics generated by
417     // the format! syntax extension.
418     fn run(&mut self, arg: &rt::v1::Argument) -> Result {
419         // Fill in the format parameters into the formatter
420         self.fill = arg.format.fill;
421         self.align = arg.format.align;
422         self.flags = arg.format.flags;
423         self.width = self.getcount(&arg.format.width);
424         self.precision = self.getcount(&arg.format.precision);
425
426         // Extract the correct argument
427         let value = match arg.position {
428             rt::v1::Position::Next => { *self.curarg.next().unwrap() }
429             rt::v1::Position::At(i) => self.args[i],
430         };
431
432         // Then actually do some printing
433         (value.formatter)(value.value, self)
434     }
435
436     fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<uint> {
437         match *cnt {
438             rt::v1::Count::Is(n) => Some(n),
439             rt::v1::Count::Implied => None,
440             rt::v1::Count::Param(i) => {
441                 self.args[i].as_uint()
442             }
443             rt::v1::Count::NextParam => {
444                 self.curarg.next().and_then(|arg| arg.as_uint())
445             }
446         }
447     }
448
449     // Helper methods used for padding and processing formatting arguments that
450     // all formatting traits can use.
451
452     /// Performs the correct padding for an integer which has already been
453     /// emitted into a str. The str should *not* contain the sign for the
454     /// integer, that will be added by this method.
455     ///
456     /// # Arguments
457     ///
458     /// * is_positive - whether the original integer was positive or not.
459     /// * prefix - if the '#' character (FlagAlternate) is provided, this
460     ///   is the prefix to put in front of the number.
461     /// * buf - the byte array that the number has been formatted into
462     ///
463     /// This function will correctly account for the flags provided as well as
464     /// the minimum width. It will not take precision into account.
465     #[stable(feature = "rust1", since = "1.0.0")]
466     pub fn pad_integral(&mut self,
467                         is_positive: bool,
468                         prefix: &str,
469                         buf: &str)
470                         -> Result {
471         use char::CharExt;
472
473         let mut width = buf.len();
474
475         let mut sign = None;
476         if !is_positive {
477             sign = Some('-'); width += 1;
478         } else if self.flags & (1 << (FlagV1::SignPlus as uint)) != 0 {
479             sign = Some('+'); width += 1;
480         }
481
482         let mut prefixed = false;
483         if self.flags & (1 << (FlagV1::Alternate as uint)) != 0 {
484             prefixed = true; width += prefix.char_len();
485         }
486
487         // Writes the sign if it exists, and then the prefix if it was requested
488         let write_prefix = |f: &mut Formatter| {
489             if let Some(c) = sign {
490                 let mut b = [0; 4];
491                 let n = c.encode_utf8(&mut b).unwrap_or(0);
492                 let b = unsafe { str::from_utf8_unchecked(&b[..n]) };
493                 try!(f.buf.write_str(b));
494             }
495             if prefixed { f.buf.write_str(prefix) }
496             else { Ok(()) }
497         };
498
499         // The `width` field is more of a `min-width` parameter at this point.
500         match self.width {
501             // If there's no minimum length requirements then we can just
502             // write the bytes.
503             None => {
504                 try!(write_prefix(self)); self.buf.write_str(buf)
505             }
506             // Check if we're over the minimum width, if so then we can also
507             // just write the bytes.
508             Some(min) if width >= min => {
509                 try!(write_prefix(self)); self.buf.write_str(buf)
510             }
511             // The sign and prefix goes before the padding if the fill character
512             // is zero
513             Some(min) if self.flags & (1 << (FlagV1::SignAwareZeroPad as uint)) != 0 => {
514                 self.fill = '0';
515                 try!(write_prefix(self));
516                 self.with_padding(min - width, Alignment::Right, |f| {
517                     f.buf.write_str(buf)
518                 })
519             }
520             // Otherwise, the sign and prefix goes after the padding
521             Some(min) => {
522                 self.with_padding(min - width, Alignment::Right, |f| {
523                     try!(write_prefix(f)); f.buf.write_str(buf)
524                 })
525             }
526         }
527     }
528
529     /// This function takes a string slice and emits it to the internal buffer
530     /// after applying the relevant formatting flags specified. The flags
531     /// recognized for generic strings are:
532     ///
533     /// * width - the minimum width of what to emit
534     /// * fill/align - what to emit and where to emit it if the string
535     ///                provided needs to be padded
536     /// * precision - the maximum length to emit, the string is truncated if it
537     ///               is longer than this length
538     ///
539     /// Notably this function ignored the `flag` parameters
540     #[stable(feature = "rust1", since = "1.0.0")]
541     pub fn pad(&mut self, s: &str) -> Result {
542         // Make sure there's a fast path up front
543         if self.width.is_none() && self.precision.is_none() {
544             return self.buf.write_str(s);
545         }
546         // The `precision` field can be interpreted as a `max-width` for the
547         // string being formatted
548         match self.precision {
549             Some(max) => {
550                 // If there's a maximum width and our string is longer than
551                 // that, then we must always have truncation. This is the only
552                 // case where the maximum length will matter.
553                 let char_len = s.char_len();
554                 if char_len >= max {
555                     let nchars = ::cmp::min(max, char_len);
556                     return self.buf.write_str(s.slice_chars(0, nchars));
557                 }
558             }
559             None => {}
560         }
561         // The `width` field is more of a `min-width` parameter at this point.
562         match self.width {
563             // If we're under the maximum length, and there's no minimum length
564             // requirements, then we can just emit the string
565             None => self.buf.write_str(s),
566             // If we're under the maximum width, check if we're over the minimum
567             // width, if so it's as easy as just emitting the string.
568             Some(width) if s.char_len() >= width => {
569                 self.buf.write_str(s)
570             }
571             // If we're under both the maximum and the minimum width, then fill
572             // up the minimum width with the specified string + some alignment.
573             Some(width) => {
574                 self.with_padding(width - s.char_len(), Alignment::Left, |me| {
575                     me.buf.write_str(s)
576                 })
577             }
578         }
579     }
580
581     /// Runs a callback, emitting the correct padding either before or
582     /// afterwards depending on whether right or left alignment is requested.
583     fn with_padding<F>(&mut self, padding: uint, default: Alignment,
584                        f: F) -> Result
585         where F: FnOnce(&mut Formatter) -> Result,
586     {
587         use char::CharExt;
588         let align = match self.align {
589             Alignment::Unknown => default,
590             _ => self.align
591         };
592
593         let (pre_pad, post_pad) = match align {
594             Alignment::Left => (0, padding),
595             Alignment::Right | Alignment::Unknown => (padding, 0),
596             Alignment::Center => (padding / 2, (padding + 1) / 2),
597         };
598
599         let mut fill = [0u8; 4];
600         let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
601         let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) };
602
603         for _ in 0..pre_pad {
604             try!(self.buf.write_str(fill));
605         }
606
607         try!(f(self));
608
609         for _ in 0..post_pad {
610             try!(self.buf.write_str(fill));
611         }
612
613         Ok(())
614     }
615
616     /// Writes some data to the underlying buffer contained within this
617     /// formatter.
618     #[stable(feature = "rust1", since = "1.0.0")]
619     pub fn write_str(&mut self, data: &str) -> Result {
620         self.buf.write_str(data)
621     }
622
623     /// Writes some formatted information into this instance
624     #[stable(feature = "rust1", since = "1.0.0")]
625     pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
626         write(self.buf, fmt)
627     }
628
629     /// Flags for formatting (packed version of rt::Flag)
630     #[stable(feature = "rust1", since = "1.0.0")]
631     pub fn flags(&self) -> usize { self.flags }
632
633     /// Character used as 'fill' whenever there is alignment
634     #[unstable(feature = "core", reason = "method was just created")]
635     pub fn fill(&self) -> char { self.fill }
636
637     /// Flag indicating what form of alignment was requested
638     #[unstable(feature = "core", reason = "method was just created")]
639     pub fn align(&self) -> Alignment { self.align }
640
641     /// Optionally specified integer width that the output should be
642     #[unstable(feature = "core", reason = "method was just created")]
643     pub fn width(&self) -> Option<uint> { self.width }
644
645     /// Optionally specified precision for numeric types
646     #[unstable(feature = "core", reason = "method was just created")]
647     pub fn precision(&self) -> Option<uint> { self.precision }
648 }
649
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl Display for Error {
652     fn fmt(&self, f: &mut Formatter) -> Result {
653         Display::fmt("an error occurred when formatting an argument", f)
654     }
655 }
656
657 // Implementations of the core formatting traits
658
659 macro_rules! fmt_refs {
660     ($($tr:ident),*) => {
661         $(
662         #[stable(feature = "rust1", since = "1.0.0")]
663         impl<'a, T: ?Sized + $tr> $tr for &'a T {
664             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
665         }
666         #[stable(feature = "rust1", since = "1.0.0")]
667         impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
668             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
669         }
670         )*
671     }
672 }
673
674 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
675
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl Debug for bool {
678     fn fmt(&self, f: &mut Formatter) -> Result {
679         Display::fmt(self, f)
680     }
681 }
682
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl Display for bool {
685     fn fmt(&self, f: &mut Formatter) -> Result {
686         Display::fmt(if *self { "true" } else { "false" }, f)
687     }
688 }
689
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl Debug for str {
692     fn fmt(&self, f: &mut Formatter) -> Result {
693         try!(write!(f, "\""));
694         for c in self.chars().flat_map(|c| c.escape_default()) {
695             try!(write!(f, "{}", c));
696         }
697         write!(f, "\"")
698     }
699 }
700
701 #[stable(feature = "rust1", since = "1.0.0")]
702 impl Display for str {
703     fn fmt(&self, f: &mut Formatter) -> Result {
704         f.pad(self)
705     }
706 }
707
708 #[stable(feature = "rust1", since = "1.0.0")]
709 impl Debug for char {
710     fn fmt(&self, f: &mut Formatter) -> Result {
711         use char::CharExt;
712         try!(write!(f, "'"));
713         for c in self.escape_default() {
714             try!(write!(f, "{}", c));
715         }
716         write!(f, "'")
717     }
718 }
719
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl Display for char {
722     fn fmt(&self, f: &mut Formatter) -> Result {
723         let mut utf8 = [0u8; 4];
724         let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
725         let s: &str = unsafe { mem::transmute(&utf8[..amt]) };
726         Display::fmt(s, f)
727     }
728 }
729
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl<T> Pointer for *const T {
732     fn fmt(&self, f: &mut Formatter) -> Result {
733         f.flags |= 1 << (FlagV1::Alternate as uint);
734         let ret = LowerHex::fmt(&(*self as uint), f);
735         f.flags &= !(1 << (FlagV1::Alternate as uint));
736         ret
737     }
738 }
739
740 #[stable(feature = "rust1", since = "1.0.0")]
741 impl<T> Pointer for *mut T {
742     fn fmt(&self, f: &mut Formatter) -> Result {
743         Pointer::fmt(&(*self as *const T), f)
744     }
745 }
746
747 #[stable(feature = "rust1", since = "1.0.0")]
748 impl<'a, T> Pointer for &'a T {
749     fn fmt(&self, f: &mut Formatter) -> Result {
750         Pointer::fmt(&(*self as *const T), f)
751     }
752 }
753
754 #[stable(feature = "rust1", since = "1.0.0")]
755 impl<'a, T> Pointer for &'a mut T {
756     fn fmt(&self, f: &mut Formatter) -> Result {
757         Pointer::fmt(&(&**self as *const T), f)
758     }
759 }
760
761 macro_rules! floating { ($ty:ident) => {
762
763     #[stable(feature = "rust1", since = "1.0.0")]
764     impl Debug for $ty {
765         fn fmt(&self, fmt: &mut Formatter) -> Result {
766             Display::fmt(self, fmt)
767         }
768     }
769
770     #[stable(feature = "rust1", since = "1.0.0")]
771     impl Display for $ty {
772         fn fmt(&self, fmt: &mut Formatter) -> Result {
773             use num::Float;
774
775             let digits = match fmt.precision {
776                 Some(i) => float::DigExact(i),
777                 None => float::DigMax(6),
778             };
779             float::float_to_str_bytes_common(self.abs(),
780                                              10,
781                                              true,
782                                              float::SignNeg,
783                                              digits,
784                                              float::ExpNone,
785                                              false,
786                                              |bytes| {
787                 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
788             })
789         }
790     }
791
792     #[stable(feature = "rust1", since = "1.0.0")]
793     impl LowerExp for $ty {
794         fn fmt(&self, fmt: &mut Formatter) -> Result {
795             use num::Float;
796
797             let digits = match fmt.precision {
798                 Some(i) => float::DigExact(i),
799                 None => float::DigMax(6),
800             };
801             float::float_to_str_bytes_common(self.abs(),
802                                              10,
803                                              true,
804                                              float::SignNeg,
805                                              digits,
806                                              float::ExpDec,
807                                              false,
808                                              |bytes| {
809                 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
810             })
811         }
812     }
813
814     #[stable(feature = "rust1", since = "1.0.0")]
815     impl UpperExp for $ty {
816         fn fmt(&self, fmt: &mut Formatter) -> Result {
817             use num::Float;
818
819             let digits = match fmt.precision {
820                 Some(i) => float::DigExact(i),
821                 None => float::DigMax(6),
822             };
823             float::float_to_str_bytes_common(self.abs(),
824                                              10,
825                                              true,
826                                              float::SignNeg,
827                                              digits,
828                                              float::ExpDec,
829                                              true,
830                                              |bytes| {
831                 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
832             })
833         }
834     }
835 } }
836 floating! { f32 }
837 floating! { f64 }
838
839 // Implementation of Display/Debug for various core types
840
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<T> Debug for *const T {
843     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
844 }
845 #[stable(feature = "rust1", since = "1.0.0")]
846 impl<T> Debug for *mut T {
847     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
848 }
849
850 macro_rules! peel {
851     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
852 }
853
854 macro_rules! tuple {
855     () => ();
856     ( $($name:ident,)+ ) => (
857         #[stable(feature = "rust1", since = "1.0.0")]
858         impl<$($name:Debug),*> Debug for ($($name,)*) {
859             #[allow(non_snake_case, unused_assignments)]
860             fn fmt(&self, f: &mut Formatter) -> Result {
861                 try!(write!(f, "("));
862                 let ($(ref $name,)*) = *self;
863                 let mut n = 0;
864                 $(
865                     if n > 0 {
866                         try!(write!(f, ", "));
867                     }
868                     try!(write!(f, "{:?}", *$name));
869                     n += 1;
870                 )*
871                 if n == 1 {
872                     try!(write!(f, ","));
873                 }
874                 write!(f, ")")
875             }
876         }
877         peel! { $($name,)* }
878     )
879 }
880
881 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
882
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl<'a> Debug for &'a (any::Any+'a) {
885     fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") }
886 }
887
888 #[stable(feature = "rust1", since = "1.0.0")]
889 impl<T: Debug> Debug for [T] {
890     fn fmt(&self, f: &mut Formatter) -> Result {
891         if f.flags & (1 << (FlagV1::Alternate as uint)) == 0 {
892             try!(write!(f, "["));
893         }
894         let mut is_first = true;
895         for x in self {
896             if is_first {
897                 is_first = false;
898             } else {
899                 try!(write!(f, ", "));
900             }
901             try!(write!(f, "{:?}", *x))
902         }
903         if f.flags & (1 << (FlagV1::Alternate as uint)) == 0 {
904             try!(write!(f, "]"));
905         }
906         Ok(())
907     }
908 }
909
910 #[stable(feature = "rust1", since = "1.0.0")]
911 impl Debug for () {
912     fn fmt(&self, f: &mut Formatter) -> Result {
913         f.pad("()")
914     }
915 }
916
917 #[stable(feature = "rust1", since = "1.0.0")]
918 impl<T: Copy + Debug> Debug for Cell<T> {
919     fn fmt(&self, f: &mut Formatter) -> Result {
920         write!(f, "Cell {{ value: {:?} }}", self.get())
921     }
922 }
923
924 #[stable(feature = "rust1", since = "1.0.0")]
925 impl<T: Debug> Debug for RefCell<T> {
926     fn fmt(&self, f: &mut Formatter) -> Result {
927         match self.borrow_state() {
928             BorrowState::Unused | BorrowState::Reading => {
929                 write!(f, "RefCell {{ value: {:?} }}", self.borrow())
930             }
931             BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
932         }
933     }
934 }
935
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<'b, T: Debug> Debug for Ref<'b, T> {
938     fn fmt(&self, f: &mut Formatter) -> Result {
939         Debug::fmt(&**self, f)
940     }
941 }
942
943 #[stable(feature = "rust1", since = "1.0.0")]
944 impl<'b, T: Debug> Debug for RefMut<'b, T> {
945     fn fmt(&self, f: &mut Formatter) -> Result {
946         Debug::fmt(&*(self.deref()), f)
947     }
948 }
949
950 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
951 // it's a lot easier than creating all of the rt::Piece structures here.