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