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