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