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