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