]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/mod.rs
Unignore u128 test for stage 0,1
[rust.git] / src / libcore / fmt / mod.rs
1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Utilities for formatting and printing strings.
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use cell::{UnsafeCell, Cell, RefCell, Ref, RefMut};
16 use marker::PhantomData;
17 use mem;
18 use num::flt2dec;
19 use ops::Deref;
20 use result;
21 use slice;
22 use str;
23
24 #[unstable(feature = "fmt_flags_align", issue = "27726")]
25 /// Possible alignments returned by `Formatter::align`
26 #[derive(Debug)]
27 pub enum Alignment {
28     /// Indication that contents should be left-aligned.
29     Left,
30     /// Indication that contents should be right-aligned.
31     Right,
32     /// Indication that contents should be center-aligned.
33     Center,
34     /// No alignment was requested.
35     Unknown,
36 }
37
38 #[stable(feature = "debug_builders", since = "1.2.0")]
39 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
40
41 mod num;
42 mod builders;
43
44 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
45            issue = "0")]
46 #[doc(hidden)]
47 pub mod rt {
48     pub mod v1;
49 }
50
51 #[stable(feature = "rust1", since = "1.0.0")]
52 /// The type returned by formatter methods.
53 pub type Result = result::Result<(), Error>;
54
55 /// The error type which is returned from formatting a message into a stream.
56 ///
57 /// This type does not support transmission of an error other than that an error
58 /// occurred. Any extra information must be arranged to be transmitted through
59 /// some other means.
60 #[stable(feature = "rust1", since = "1.0.0")]
61 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
62 pub struct Error;
63
64 /// A collection of methods that are required to format a message into a stream.
65 ///
66 /// This trait is the type which this modules requires when formatting
67 /// information. This is similar to the standard library's `io::Write` trait,
68 /// but it is only intended for use in libcore.
69 ///
70 /// This trait should generally not be implemented by consumers of the standard
71 /// library. The `write!` macro accepts an instance of `io::Write`, and the
72 /// `io::Write` trait is favored over implementing this trait.
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub trait Write {
75     /// Writes a slice of bytes into this writer, returning whether the write
76     /// succeeded.
77     ///
78     /// This method can only succeed if the entire byte slice was successfully
79     /// written, and this method will not return until all data has been
80     /// written or an error occurs.
81     ///
82     /// # Errors
83     ///
84     /// This function will return an instance of `Error` on error.
85     #[stable(feature = "rust1", since = "1.0.0")]
86     fn write_str(&mut self, s: &str) -> Result;
87
88     /// Writes a `char` into this writer, returning whether the write succeeded.
89     ///
90     /// A single `char` may be encoded as more than one byte.
91     /// This method can only succeed if the entire byte sequence was successfully
92     /// written, and this method will not return until all data has been
93     /// written or an error occurs.
94     ///
95     /// # Errors
96     ///
97     /// This function will return an instance of `Error` on error.
98     #[stable(feature = "fmt_write_char", since = "1.1.0")]
99     fn write_char(&mut self, c: char) -> Result {
100         self.write_str(c.encode_utf8(&mut [0; 4]))
101     }
102
103     /// Glue for usage of the `write!` macro with implementors of this trait.
104     ///
105     /// This method should generally not be invoked manually, but rather through
106     /// the `write!` macro itself.
107     #[stable(feature = "rust1", since = "1.0.0")]
108     fn write_fmt(&mut self, args: Arguments) -> Result {
109         // This Adapter is needed to allow `self` (of type `&mut
110         // Self`) to be cast to a Write (below) without
111         // requiring a `Sized` bound.
112         struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
113
114         impl<'a, T: ?Sized> Write for Adapter<'a, T>
115             where T: Write
116         {
117             fn write_str(&mut self, s: &str) -> Result {
118                 self.0.write_str(s)
119             }
120
121             fn write_char(&mut self, c: char) -> Result {
122                 self.0.write_char(c)
123             }
124
125             fn write_fmt(&mut self, args: Arguments) -> Result {
126                 self.0.write_fmt(args)
127             }
128         }
129
130         write(&mut Adapter(self), args)
131     }
132 }
133
134 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
135 impl<'a, W: Write + ?Sized> Write for &'a mut W {
136     fn write_str(&mut self, s: &str) -> Result {
137         (**self).write_str(s)
138     }
139
140     fn write_char(&mut self, c: char) -> Result {
141         (**self).write_char(c)
142     }
143
144     fn write_fmt(&mut self, args: Arguments) -> Result {
145         (**self).write_fmt(args)
146     }
147 }
148
149 /// A struct to represent both where to emit formatting strings to and how they
150 /// should be formatted. A mutable version of this is passed to all formatting
151 /// traits.
152 #[allow(missing_debug_implementations)]
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub struct Formatter<'a> {
155     flags: u32,
156     fill: char,
157     align: rt::v1::Alignment,
158     width: Option<usize>,
159     precision: Option<usize>,
160
161     buf: &'a mut (Write+'a),
162     curarg: slice::Iter<'a, ArgumentV1<'a>>,
163     args: &'a [ArgumentV1<'a>],
164 }
165
166 // NB. Argument is essentially an optimized partially applied formatting function,
167 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
168
169 struct Void {
170     _priv: (),
171 }
172
173 /// This struct represents the generic "argument" which is taken by the Xprintf
174 /// family of functions. It contains a function to format the given value. At
175 /// compile time it is ensured that the function and the value have the correct
176 /// types, and then this struct is used to canonicalize arguments to one type.
177 #[derive(Copy)]
178 #[allow(missing_debug_implementations)]
179 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
180            issue = "0")]
181 #[doc(hidden)]
182 pub struct ArgumentV1<'a> {
183     value: &'a Void,
184     formatter: fn(&Void, &mut Formatter) -> Result,
185 }
186
187 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
188            issue = "0")]
189 impl<'a> Clone for ArgumentV1<'a> {
190     fn clone(&self) -> ArgumentV1<'a> {
191         *self
192     }
193 }
194
195 impl<'a> ArgumentV1<'a> {
196     #[inline(never)]
197     fn show_usize(x: &usize, f: &mut Formatter) -> Result {
198         Display::fmt(x, f)
199     }
200
201     #[doc(hidden)]
202     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
203                issue = "0")]
204     pub fn new<'b, T>(x: &'b T,
205                       f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
206         unsafe {
207             ArgumentV1 {
208                 formatter: mem::transmute(f),
209                 value: mem::transmute(x)
210             }
211         }
212     }
213
214     #[doc(hidden)]
215     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
216                issue = "0")]
217     pub fn from_usize(x: &usize) -> ArgumentV1 {
218         ArgumentV1::new(x, ArgumentV1::show_usize)
219     }
220
221     fn as_usize(&self) -> Option<usize> {
222         if self.formatter as usize == ArgumentV1::show_usize as usize {
223             Some(unsafe { *(self.value as *const _ as *const usize) })
224         } else {
225             None
226         }
227     }
228 }
229
230 // flags available in the v1 format of format_args
231 #[derive(Copy, Clone)]
232 #[allow(dead_code)] // SignMinus isn't currently used
233 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
234
235 impl<'a> Arguments<'a> {
236     /// When using the format_args!() macro, this function is used to generate the
237     /// Arguments structure.
238     #[doc(hidden)] #[inline]
239     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
240                issue = "0")]
241     pub fn new_v1(pieces: &'a [&'a str],
242                   args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
243         Arguments {
244             pieces: pieces,
245             fmt: None,
246             args: args
247         }
248     }
249
250     /// This function is used to specify nonstandard formatting parameters.
251     /// The `pieces` array must be at least as long as `fmt` to construct
252     /// a valid Arguments structure. Also, any `Count` within `fmt` that is
253     /// `CountIsParam` or `CountIsNextParam` has to point to an argument
254     /// created with `argumentusize`. However, failing to do so doesn't cause
255     /// unsafety, but will ignore invalid .
256     #[doc(hidden)] #[inline]
257     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
258                issue = "0")]
259     pub fn new_v1_formatted(pieces: &'a [&'a str],
260                             args: &'a [ArgumentV1<'a>],
261                             fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
262         Arguments {
263             pieces: pieces,
264             fmt: Some(fmt),
265             args: args
266         }
267     }
268
269     /// Estimates the length of the formatted text.
270     ///
271     /// This is intended to be used for setting initial `String` capacity
272     /// when using `format!`. Note: this is neither the lower nor upper bound.
273     #[doc(hidden)] #[inline]
274     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
275                issue = "0")]
276     pub fn estimated_capacity(&self) -> usize {
277         let pieces_length: usize = self.pieces.iter()
278             .map(|x| x.len()).sum();
279
280         if self.args.is_empty() {
281             pieces_length
282         } else if self.pieces[0] == "" && pieces_length < 16 {
283             // If the format string starts with an argument,
284             // don't preallocate anything, unless length
285             // of pieces is significant.
286             0
287         } else {
288             // There are some arguments, so any additional push
289             // will reallocate the string. To avoid that,
290             // we're "pre-doubling" the capacity here.
291             pieces_length.checked_mul(2).unwrap_or(0)
292         }
293     }
294 }
295
296 /// This structure represents a safely precompiled version of a format string
297 /// and its arguments. This cannot be generated at runtime because it cannot
298 /// safely be done so, so no constructors are given and the fields are private
299 /// to prevent modification.
300 ///
301 /// The [`format_args!`] macro will safely create an instance of this structure
302 /// and pass it to a function or closure, passed as the first argument. The
303 /// macro validates the format string at compile-time so usage of the [`write`]
304 /// and [`format`] functions can be safely performed.
305 ///
306 /// [`format_args!`]: ../../std/macro.format_args.html
307 /// [`format`]: ../../std/fmt/fn.format.html
308 /// [`write`]: ../../std/fmt/fn.write.html
309 #[stable(feature = "rust1", since = "1.0.0")]
310 #[derive(Copy, Clone)]
311 pub struct Arguments<'a> {
312     // Format string pieces to print.
313     pieces: &'a [&'a str],
314
315     // Placeholder specs, or `None` if all specs are default (as in "{}{}").
316     fmt: Option<&'a [rt::v1::Argument]>,
317
318     // Dynamic arguments for interpolation, to be interleaved with string
319     // pieces. (Every argument is preceded by a string piece.)
320     args: &'a [ArgumentV1<'a>],
321 }
322
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<'a> Debug for Arguments<'a> {
325     fn fmt(&self, fmt: &mut Formatter) -> Result {
326         Display::fmt(self, fmt)
327     }
328 }
329
330 #[stable(feature = "rust1", since = "1.0.0")]
331 impl<'a> Display for Arguments<'a> {
332     fn fmt(&self, fmt: &mut Formatter) -> Result {
333         write(fmt.buf, *self)
334     }
335 }
336
337 /// Format trait for the `?` character.
338 ///
339 /// `Debug` should format the output in a programmer-facing, debugging context.
340 ///
341 /// Generally speaking, you should just `derive` a `Debug` implementation.
342 ///
343 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
344 ///
345 /// For more information on formatters, see [the module-level documentation][module].
346 ///
347 /// [module]: ../../std/fmt/index.html
348 ///
349 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
350 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
351 /// comma-separated list of each field's name and `Debug` value, then `}`. For
352 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
353 /// `Debug` values of the fields, then `)`.
354 ///
355 /// # Examples
356 ///
357 /// Deriving an implementation:
358 ///
359 /// ```
360 /// #[derive(Debug)]
361 /// struct Point {
362 ///     x: i32,
363 ///     y: i32,
364 /// }
365 ///
366 /// let origin = Point { x: 0, y: 0 };
367 ///
368 /// println!("The origin is: {:?}", origin);
369 /// ```
370 ///
371 /// Manually implementing:
372 ///
373 /// ```
374 /// use std::fmt;
375 ///
376 /// struct Point {
377 ///     x: i32,
378 ///     y: i32,
379 /// }
380 ///
381 /// impl fmt::Debug for Point {
382 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
383 ///         write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
384 ///     }
385 /// }
386 ///
387 /// let origin = Point { x: 0, y: 0 };
388 ///
389 /// println!("The origin is: {:?}", origin);
390 /// ```
391 ///
392 /// This outputs:
393 ///
394 /// ```text
395 /// The origin is: Point { x: 0, y: 0 }
396 /// ```
397 ///
398 /// There are a number of `debug_*` methods on `Formatter` to help you with manual
399 /// implementations, such as [`debug_struct`][debug_struct].
400 ///
401 /// `Debug` implementations using either `derive` or the debug builder API
402 /// on `Formatter` support pretty printing using the alternate flag: `{:#?}`.
403 ///
404 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
405 ///
406 /// Pretty printing with `#?`:
407 ///
408 /// ```
409 /// #[derive(Debug)]
410 /// struct Point {
411 ///     x: i32,
412 ///     y: i32,
413 /// }
414 ///
415 /// let origin = Point { x: 0, y: 0 };
416 ///
417 /// println!("The origin is: {:#?}", origin);
418 /// ```
419 ///
420 /// This outputs:
421 ///
422 /// ```text
423 /// The origin is: Point {
424 ///     x: 0,
425 ///     y: 0
426 /// }
427 /// ```
428 #[stable(feature = "rust1", since = "1.0.0")]
429 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
430                             defined in your crate, add `#[derive(Debug)]` or \
431                             manually implement it"]
432 #[lang = "debug_trait"]
433 pub trait Debug {
434     /// Formats the value using the given formatter.
435     #[stable(feature = "rust1", since = "1.0.0")]
436     fn fmt(&self, &mut Formatter) -> Result;
437 }
438
439 /// Format trait for an empty format, `{}`.
440 ///
441 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
442 /// output, and so cannot be derived.
443 ///
444 /// [debug]: trait.Debug.html
445 ///
446 /// For more information on formatters, see [the module-level documentation][module].
447 ///
448 /// [module]: ../../std/fmt/index.html
449 ///
450 /// # Examples
451 ///
452 /// Implementing `Display` on a type:
453 ///
454 /// ```
455 /// use std::fmt;
456 ///
457 /// struct Point {
458 ///     x: i32,
459 ///     y: i32,
460 /// }
461 ///
462 /// impl fmt::Display for Point {
463 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
464 ///         write!(f, "({}, {})", self.x, self.y)
465 ///     }
466 /// }
467 ///
468 /// let origin = Point { x: 0, y: 0 };
469 ///
470 /// println!("The origin is: {}", origin);
471 /// ```
472 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
473                             formatter; try using `:?` instead if you are using \
474                             a format string"]
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub trait Display {
477     /// Formats the value using the given formatter.
478     #[stable(feature = "rust1", since = "1.0.0")]
479     fn fmt(&self, &mut Formatter) -> Result;
480 }
481
482 /// Format trait for the `o` character.
483 ///
484 /// The `Octal` trait should format its output as a number in base-8.
485 ///
486 /// The alternate flag, `#`, adds a `0o` in front of the output.
487 ///
488 /// For more information on formatters, see [the module-level documentation][module].
489 ///
490 /// [module]: ../../std/fmt/index.html
491 ///
492 /// # Examples
493 ///
494 /// Basic usage with `i32`:
495 ///
496 /// ```
497 /// let x = 42; // 42 is '52' in octal
498 ///
499 /// assert_eq!(format!("{:o}", x), "52");
500 /// assert_eq!(format!("{:#o}", x), "0o52");
501 /// ```
502 ///
503 /// Implementing `Octal` on a type:
504 ///
505 /// ```
506 /// use std::fmt;
507 ///
508 /// struct Length(i32);
509 ///
510 /// impl fmt::Octal for Length {
511 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
512 ///         let val = self.0;
513 ///
514 ///         write!(f, "{:o}", val) // delegate to i32's implementation
515 ///     }
516 /// }
517 ///
518 /// let l = Length(9);
519 ///
520 /// println!("l as octal is: {:o}", l);
521 /// ```
522 #[stable(feature = "rust1", since = "1.0.0")]
523 pub trait Octal {
524     /// Formats the value using the given formatter.
525     #[stable(feature = "rust1", since = "1.0.0")]
526     fn fmt(&self, &mut Formatter) -> Result;
527 }
528
529 /// Format trait for the `b` character.
530 ///
531 /// The `Binary` trait should format its output as a number in binary.
532 ///
533 /// The alternate flag, `#`, adds a `0b` in front of the output.
534 ///
535 /// For more information on formatters, see [the module-level documentation][module].
536 ///
537 /// [module]: ../../std/fmt/index.html
538 ///
539 /// # Examples
540 ///
541 /// Basic usage with `i32`:
542 ///
543 /// ```
544 /// let x = 42; // 42 is '101010' in binary
545 ///
546 /// assert_eq!(format!("{:b}", x), "101010");
547 /// assert_eq!(format!("{:#b}", x), "0b101010");
548 /// ```
549 ///
550 /// Implementing `Binary` on a type:
551 ///
552 /// ```
553 /// use std::fmt;
554 ///
555 /// struct Length(i32);
556 ///
557 /// impl fmt::Binary for Length {
558 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
559 ///         let val = self.0;
560 ///
561 ///         write!(f, "{:b}", val) // delegate to i32's implementation
562 ///     }
563 /// }
564 ///
565 /// let l = Length(107);
566 ///
567 /// println!("l as binary is: {:b}", l);
568 /// ```
569 #[stable(feature = "rust1", since = "1.0.0")]
570 pub trait Binary {
571     /// Formats the value using the given formatter.
572     #[stable(feature = "rust1", since = "1.0.0")]
573     fn fmt(&self, &mut Formatter) -> Result;
574 }
575
576 /// Format trait for the `x` character.
577 ///
578 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
579 /// in lower case.
580 ///
581 /// The alternate flag, `#`, adds a `0x` in front of the output.
582 ///
583 /// For more information on formatters, see [the module-level documentation][module].
584 ///
585 /// [module]: ../../std/fmt/index.html
586 ///
587 /// # Examples
588 ///
589 /// Basic usage with `i32`:
590 ///
591 /// ```
592 /// let x = 42; // 42 is '2a' in hex
593 ///
594 /// assert_eq!(format!("{:x}", x), "2a");
595 /// assert_eq!(format!("{:#x}", x), "0x2a");
596 /// ```
597 ///
598 /// Implementing `LowerHex` on a type:
599 ///
600 /// ```
601 /// use std::fmt;
602 ///
603 /// struct Length(i32);
604 ///
605 /// impl fmt::LowerHex for Length {
606 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
607 ///         let val = self.0;
608 ///
609 ///         write!(f, "{:x}", val) // delegate to i32's implementation
610 ///     }
611 /// }
612 ///
613 /// let l = Length(9);
614 ///
615 /// println!("l as hex is: {:x}", l);
616 /// ```
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub trait LowerHex {
619     /// Formats the value using the given formatter.
620     #[stable(feature = "rust1", since = "1.0.0")]
621     fn fmt(&self, &mut Formatter) -> Result;
622 }
623
624 /// Format trait for the `X` character.
625 ///
626 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
627 /// in upper case.
628 ///
629 /// The alternate flag, `#`, adds a `0x` in front of the output.
630 ///
631 /// For more information on formatters, see [the module-level documentation][module].
632 ///
633 /// [module]: ../../std/fmt/index.html
634 ///
635 /// # Examples
636 ///
637 /// Basic usage with `i32`:
638 ///
639 /// ```
640 /// let x = 42; // 42 is '2A' in hex
641 ///
642 /// assert_eq!(format!("{:X}", x), "2A");
643 /// assert_eq!(format!("{:#X}", x), "0x2A");
644 /// ```
645 ///
646 /// Implementing `UpperHex` on a type:
647 ///
648 /// ```
649 /// use std::fmt;
650 ///
651 /// struct Length(i32);
652 ///
653 /// impl fmt::UpperHex for Length {
654 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
655 ///         let val = self.0;
656 ///
657 ///         write!(f, "{:X}", val) // delegate to i32's implementation
658 ///     }
659 /// }
660 ///
661 /// let l = Length(9);
662 ///
663 /// println!("l as hex is: {:X}", l);
664 /// ```
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub trait UpperHex {
667     /// Formats the value using the given formatter.
668     #[stable(feature = "rust1", since = "1.0.0")]
669     fn fmt(&self, &mut Formatter) -> Result;
670 }
671
672 /// Format trait for the `p` character.
673 ///
674 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
675 /// as hexadecimal.
676 ///
677 /// For more information on formatters, see [the module-level documentation][module].
678 ///
679 /// [module]: ../../std/fmt/index.html
680 ///
681 /// # Examples
682 ///
683 /// Basic usage with `&i32`:
684 ///
685 /// ```
686 /// let x = &42;
687 ///
688 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
689 /// ```
690 ///
691 /// Implementing `Pointer` on a type:
692 ///
693 /// ```
694 /// use std::fmt;
695 ///
696 /// struct Length(i32);
697 ///
698 /// impl fmt::Pointer for Length {
699 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
700 ///         // use `as` to convert to a `*const T`, which implements Pointer, which we can use
701 ///
702 ///         write!(f, "{:p}", self as *const Length)
703 ///     }
704 /// }
705 ///
706 /// let l = Length(42);
707 ///
708 /// println!("l is in memory here: {:p}", l);
709 /// ```
710 #[stable(feature = "rust1", since = "1.0.0")]
711 pub trait Pointer {
712     /// Formats the value using the given formatter.
713     #[stable(feature = "rust1", since = "1.0.0")]
714     fn fmt(&self, &mut Formatter) -> Result;
715 }
716
717 /// Format trait for the `e` character.
718 ///
719 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
720 ///
721 /// For more information on formatters, see [the module-level documentation][module].
722 ///
723 /// [module]: ../../std/fmt/index.html
724 ///
725 /// # Examples
726 ///
727 /// Basic usage with `i32`:
728 ///
729 /// ```
730 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
731 ///
732 /// assert_eq!(format!("{:e}", x), "4.2e1");
733 /// ```
734 ///
735 /// Implementing `LowerExp` on a type:
736 ///
737 /// ```
738 /// use std::fmt;
739 ///
740 /// struct Length(i32);
741 ///
742 /// impl fmt::LowerExp for Length {
743 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
744 ///         let val = self.0;
745 ///         write!(f, "{}e1", val / 10)
746 ///     }
747 /// }
748 ///
749 /// let l = Length(100);
750 ///
751 /// println!("l in scientific notation is: {:e}", l);
752 /// ```
753 #[stable(feature = "rust1", since = "1.0.0")]
754 pub trait LowerExp {
755     /// Formats the value using the given formatter.
756     #[stable(feature = "rust1", since = "1.0.0")]
757     fn fmt(&self, &mut Formatter) -> Result;
758 }
759
760 /// Format trait for the `E` character.
761 ///
762 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
763 ///
764 /// For more information on formatters, see [the module-level documentation][module].
765 ///
766 /// [module]: ../../std/fmt/index.html
767 ///
768 /// # Examples
769 ///
770 /// Basic usage with `f32`:
771 ///
772 /// ```
773 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
774 ///
775 /// assert_eq!(format!("{:E}", x), "4.2E1");
776 /// ```
777 ///
778 /// Implementing `UpperExp` on a type:
779 ///
780 /// ```
781 /// use std::fmt;
782 ///
783 /// struct Length(i32);
784 ///
785 /// impl fmt::UpperExp for Length {
786 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
787 ///         let val = self.0;
788 ///         write!(f, "{}E1", val / 10)
789 ///     }
790 /// }
791 ///
792 /// let l = Length(100);
793 ///
794 /// println!("l in scientific notation is: {:E}", l);
795 /// ```
796 #[stable(feature = "rust1", since = "1.0.0")]
797 pub trait UpperExp {
798     /// Formats the value using the given formatter.
799     #[stable(feature = "rust1", since = "1.0.0")]
800     fn fmt(&self, &mut Formatter) -> Result;
801 }
802
803 /// The `write` function takes an output stream, a precompiled format string,
804 /// and a list of arguments. The arguments will be formatted according to the
805 /// specified format string into the output stream provided.
806 ///
807 /// # Arguments
808 ///
809 ///   * output - the buffer to write output to
810 ///   * args - the precompiled arguments generated by `format_args!`
811 ///
812 /// # Examples
813 ///
814 /// Basic usage:
815 ///
816 /// ```
817 /// use std::fmt;
818 ///
819 /// let mut output = String::new();
820 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
821 ///     .expect("Error occurred while trying to write in String");
822 /// assert_eq!(output, "Hello world!");
823 /// ```
824 ///
825 /// Please note that using [`write!`] might be preferrable. Example:
826 ///
827 /// ```
828 /// use std::fmt::Write;
829 ///
830 /// let mut output = String::new();
831 /// write!(&mut output, "Hello {}!", "world")
832 ///     .expect("Error occurred while trying to write in String");
833 /// assert_eq!(output, "Hello world!");
834 /// ```
835 ///
836 /// [`write!`]: ../../std/macro.write.html
837 #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn write(output: &mut Write, args: Arguments) -> Result {
839     let mut formatter = Formatter {
840         flags: 0,
841         width: None,
842         precision: None,
843         buf: output,
844         align: rt::v1::Alignment::Unknown,
845         fill: ' ',
846         args: args.args,
847         curarg: args.args.iter(),
848     };
849
850     let mut pieces = args.pieces.iter();
851
852     match args.fmt {
853         None => {
854             // We can use default formatting parameters for all arguments.
855             for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
856                 formatter.buf.write_str(*piece)?;
857                 (arg.formatter)(arg.value, &mut formatter)?;
858             }
859         }
860         Some(fmt) => {
861             // Every spec has a corresponding argument that is preceded by
862             // a string piece.
863             for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
864                 formatter.buf.write_str(*piece)?;
865                 formatter.run(arg)?;
866             }
867         }
868     }
869
870     // There can be only one trailing string piece left.
871     if let Some(piece) = pieces.next() {
872         formatter.buf.write_str(*piece)?;
873     }
874
875     Ok(())
876 }
877
878 impl<'a> Formatter<'a> {
879
880     // First up is the collection of functions used to execute a format string
881     // at runtime. This consumes all of the compile-time statics generated by
882     // the format! syntax extension.
883     fn run(&mut self, arg: &rt::v1::Argument) -> Result {
884         // Fill in the format parameters into the formatter
885         self.fill = arg.format.fill;
886         self.align = arg.format.align;
887         self.flags = arg.format.flags;
888         self.width = self.getcount(&arg.format.width);
889         self.precision = self.getcount(&arg.format.precision);
890
891         // Extract the correct argument
892         let value = match arg.position {
893             rt::v1::Position::Next => { *self.curarg.next().unwrap() }
894             rt::v1::Position::At(i) => self.args[i],
895         };
896
897         // Then actually do some printing
898         (value.formatter)(value.value, self)
899     }
900
901     fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
902         match *cnt {
903             rt::v1::Count::Is(n) => Some(n),
904             rt::v1::Count::Implied => None,
905             rt::v1::Count::Param(i) => {
906                 self.args[i].as_usize()
907             }
908             rt::v1::Count::NextParam => {
909                 self.curarg.next().and_then(|arg| arg.as_usize())
910             }
911         }
912     }
913
914     // Helper methods used for padding and processing formatting arguments that
915     // all formatting traits can use.
916
917     /// Performs the correct padding for an integer which has already been
918     /// emitted into a str. The str should *not* contain the sign for the
919     /// integer, that will be added by this method.
920     ///
921     /// # Arguments
922     ///
923     /// * is_nonnegative - whether the original integer was either positive or zero.
924     /// * prefix - if the '#' character (Alternate) is provided, this
925     ///   is the prefix to put in front of the number.
926     /// * buf - the byte array that the number has been formatted into
927     ///
928     /// This function will correctly account for the flags provided as well as
929     /// the minimum width. It will not take precision into account.
930     #[stable(feature = "rust1", since = "1.0.0")]
931     pub fn pad_integral(&mut self,
932                         is_nonnegative: bool,
933                         prefix: &str,
934                         buf: &str)
935                         -> Result {
936         let mut width = buf.len();
937
938         let mut sign = None;
939         if !is_nonnegative {
940             sign = Some('-'); width += 1;
941         } else if self.sign_plus() {
942             sign = Some('+'); width += 1;
943         }
944
945         let mut prefixed = false;
946         if self.alternate() {
947             prefixed = true; width += prefix.chars().count();
948         }
949
950         // Writes the sign if it exists, and then the prefix if it was requested
951         let write_prefix = |f: &mut Formatter| {
952             if let Some(c) = sign {
953                 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
954             }
955             if prefixed { f.buf.write_str(prefix) }
956             else { Ok(()) }
957         };
958
959         // The `width` field is more of a `min-width` parameter at this point.
960         match self.width {
961             // If there's no minimum length requirements then we can just
962             // write the bytes.
963             None => {
964                 write_prefix(self)?; self.buf.write_str(buf)
965             }
966             // Check if we're over the minimum width, if so then we can also
967             // just write the bytes.
968             Some(min) if width >= min => {
969                 write_prefix(self)?; self.buf.write_str(buf)
970             }
971             // The sign and prefix goes before the padding if the fill character
972             // is zero
973             Some(min) if self.sign_aware_zero_pad() => {
974                 self.fill = '0';
975                 write_prefix(self)?;
976                 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
977                     f.buf.write_str(buf)
978                 })
979             }
980             // Otherwise, the sign and prefix goes after the padding
981             Some(min) => {
982                 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
983                     write_prefix(f)?; f.buf.write_str(buf)
984                 })
985             }
986         }
987     }
988
989     /// This function takes a string slice and emits it to the internal buffer
990     /// after applying the relevant formatting flags specified. The flags
991     /// recognized for generic strings are:
992     ///
993     /// * width - the minimum width of what to emit
994     /// * fill/align - what to emit and where to emit it if the string
995     ///                provided needs to be padded
996     /// * precision - the maximum length to emit, the string is truncated if it
997     ///               is longer than this length
998     ///
999     /// Notably this function ignored the `flag` parameters
1000     #[stable(feature = "rust1", since = "1.0.0")]
1001     pub fn pad(&mut self, s: &str) -> Result {
1002         // Make sure there's a fast path up front
1003         if self.width.is_none() && self.precision.is_none() {
1004             return self.buf.write_str(s);
1005         }
1006         // The `precision` field can be interpreted as a `max-width` for the
1007         // string being formatted.
1008         let s = if let Some(max) = self.precision {
1009             // If our string is longer that the precision, then we must have
1010             // truncation. However other flags like `fill`, `width` and `align`
1011             // must act as always.
1012             if let Some((i, _)) = s.char_indices().skip(max).next() {
1013                 &s[..i]
1014             } else {
1015                 &s
1016             }
1017         } else {
1018             &s
1019         };
1020         // The `width` field is more of a `min-width` parameter at this point.
1021         match self.width {
1022             // If we're under the maximum length, and there's no minimum length
1023             // requirements, then we can just emit the string
1024             None => self.buf.write_str(s),
1025             // If we're under the maximum width, check if we're over the minimum
1026             // width, if so it's as easy as just emitting the string.
1027             Some(width) if s.chars().count() >= width => {
1028                 self.buf.write_str(s)
1029             }
1030             // If we're under both the maximum and the minimum width, then fill
1031             // up the minimum width with the specified string + some alignment.
1032             Some(width) => {
1033                 let align = rt::v1::Alignment::Left;
1034                 self.with_padding(width - s.chars().count(), align, |me| {
1035                     me.buf.write_str(s)
1036                 })
1037             }
1038         }
1039     }
1040
1041     /// Runs a callback, emitting the correct padding either before or
1042     /// afterwards depending on whether right or left alignment is requested.
1043     fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1044                        f: F) -> Result
1045         where F: FnOnce(&mut Formatter) -> Result,
1046     {
1047         let align = match self.align {
1048             rt::v1::Alignment::Unknown => default,
1049             _ => self.align
1050         };
1051
1052         let (pre_pad, post_pad) = match align {
1053             rt::v1::Alignment::Left => (0, padding),
1054             rt::v1::Alignment::Right |
1055             rt::v1::Alignment::Unknown => (padding, 0),
1056             rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1057         };
1058
1059         let mut fill = [0; 4];
1060         let fill = self.fill.encode_utf8(&mut fill);
1061
1062         for _ in 0..pre_pad {
1063             self.buf.write_str(fill)?;
1064         }
1065
1066         f(self)?;
1067
1068         for _ in 0..post_pad {
1069             self.buf.write_str(fill)?;
1070         }
1071
1072         Ok(())
1073     }
1074
1075     /// Takes the formatted parts and applies the padding.
1076     /// Assumes that the caller already has rendered the parts with required precision,
1077     /// so that `self.precision` can be ignored.
1078     fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1079         if let Some(mut width) = self.width {
1080             // for the sign-aware zero padding, we render the sign first and
1081             // behave as if we had no sign from the beginning.
1082             let mut formatted = formatted.clone();
1083             let mut align = self.align;
1084             let old_fill = self.fill;
1085             if self.sign_aware_zero_pad() {
1086                 // a sign always goes first
1087                 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1088                 self.buf.write_str(sign)?;
1089
1090                 // remove the sign from the formatted parts
1091                 formatted.sign = b"";
1092                 width = if width < sign.len() { 0 } else { width - sign.len() };
1093                 align = rt::v1::Alignment::Right;
1094                 self.fill = '0';
1095             }
1096
1097             // remaining parts go through the ordinary padding process.
1098             let len = formatted.len();
1099             let ret = if width <= len { // no padding
1100                 self.write_formatted_parts(&formatted)
1101             } else {
1102                 self.with_padding(width - len, align, |f| {
1103                     f.write_formatted_parts(&formatted)
1104                 })
1105             };
1106             self.fill = old_fill;
1107             ret
1108         } else {
1109             // this is the common case and we take a shortcut
1110             self.write_formatted_parts(formatted)
1111         }
1112     }
1113
1114     fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1115         fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1116             buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1117         }
1118
1119         if !formatted.sign.is_empty() {
1120             write_bytes(self.buf, formatted.sign)?;
1121         }
1122         for part in formatted.parts {
1123             match *part {
1124                 flt2dec::Part::Zero(mut nzeroes) => {
1125                     const ZEROES: &'static str = // 64 zeroes
1126                         "0000000000000000000000000000000000000000000000000000000000000000";
1127                     while nzeroes > ZEROES.len() {
1128                         self.buf.write_str(ZEROES)?;
1129                         nzeroes -= ZEROES.len();
1130                     }
1131                     if nzeroes > 0 {
1132                         self.buf.write_str(&ZEROES[..nzeroes])?;
1133                     }
1134                 }
1135                 flt2dec::Part::Num(mut v) => {
1136                     let mut s = [0; 5];
1137                     let len = part.len();
1138                     for c in s[..len].iter_mut().rev() {
1139                         *c = b'0' + (v % 10) as u8;
1140                         v /= 10;
1141                     }
1142                     write_bytes(self.buf, &s[..len])?;
1143                 }
1144                 flt2dec::Part::Copy(buf) => {
1145                     write_bytes(self.buf, buf)?;
1146                 }
1147             }
1148         }
1149         Ok(())
1150     }
1151
1152     /// Writes some data to the underlying buffer contained within this
1153     /// formatter.
1154     #[stable(feature = "rust1", since = "1.0.0")]
1155     pub fn write_str(&mut self, data: &str) -> Result {
1156         self.buf.write_str(data)
1157     }
1158
1159     /// Writes some formatted information into this instance
1160     #[stable(feature = "rust1", since = "1.0.0")]
1161     pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1162         write(self.buf, fmt)
1163     }
1164
1165     /// Flags for formatting (packed version of rt::Flag)
1166     #[stable(feature = "rust1", since = "1.0.0")]
1167     pub fn flags(&self) -> u32 { self.flags }
1168
1169     /// Character used as 'fill' whenever there is alignment
1170     #[stable(feature = "fmt_flags", since = "1.5.0")]
1171     pub fn fill(&self) -> char { self.fill }
1172
1173     /// Flag indicating what form of alignment was requested
1174     #[unstable(feature = "fmt_flags_align", reason = "method was just created",
1175                issue = "27726")]
1176     pub fn align(&self) -> Alignment {
1177         match self.align {
1178             rt::v1::Alignment::Left => Alignment::Left,
1179             rt::v1::Alignment::Right => Alignment::Right,
1180             rt::v1::Alignment::Center => Alignment::Center,
1181             rt::v1::Alignment::Unknown => Alignment::Unknown,
1182         }
1183     }
1184
1185     /// Optionally specified integer width that the output should be
1186     #[stable(feature = "fmt_flags", since = "1.5.0")]
1187     pub fn width(&self) -> Option<usize> { self.width }
1188
1189     /// Optionally specified precision for numeric types
1190     #[stable(feature = "fmt_flags", since = "1.5.0")]
1191     pub fn precision(&self) -> Option<usize> { self.precision }
1192
1193     /// Determines if the `+` flag was specified.
1194     #[stable(feature = "fmt_flags", since = "1.5.0")]
1195     pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1196
1197     /// Determines if the `-` flag was specified.
1198     #[stable(feature = "fmt_flags", since = "1.5.0")]
1199     pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1200
1201     /// Determines if the `#` flag was specified.
1202     #[stable(feature = "fmt_flags", since = "1.5.0")]
1203     pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1204
1205     /// Determines if the `0` flag was specified.
1206     #[stable(feature = "fmt_flags", since = "1.5.0")]
1207     pub fn sign_aware_zero_pad(&self) -> bool {
1208         self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1209     }
1210
1211     /// Creates a `DebugStruct` builder designed to assist with creation of
1212     /// `fmt::Debug` implementations for structs.
1213     ///
1214     /// # Examples
1215     ///
1216     /// ```rust
1217     /// use std::fmt;
1218     ///
1219     /// struct Foo {
1220     ///     bar: i32,
1221     ///     baz: String,
1222     /// }
1223     ///
1224     /// impl fmt::Debug for Foo {
1225     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1226     ///         fmt.debug_struct("Foo")
1227     ///             .field("bar", &self.bar)
1228     ///             .field("baz", &self.baz)
1229     ///             .finish()
1230     ///     }
1231     /// }
1232     ///
1233     /// // prints "Foo { bar: 10, baz: "Hello World" }"
1234     /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1235     /// ```
1236     #[stable(feature = "debug_builders", since = "1.2.0")]
1237     #[inline]
1238     pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1239         builders::debug_struct_new(self, name)
1240     }
1241
1242     /// Creates a `DebugTuple` builder designed to assist with creation of
1243     /// `fmt::Debug` implementations for tuple structs.
1244     ///
1245     /// # Examples
1246     ///
1247     /// ```rust
1248     /// use std::fmt;
1249     ///
1250     /// struct Foo(i32, String);
1251     ///
1252     /// impl fmt::Debug for Foo {
1253     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1254     ///         fmt.debug_tuple("Foo")
1255     ///             .field(&self.0)
1256     ///             .field(&self.1)
1257     ///             .finish()
1258     ///     }
1259     /// }
1260     ///
1261     /// // prints "Foo(10, "Hello World")"
1262     /// println!("{:?}", Foo(10, "Hello World".to_string()));
1263     /// ```
1264     #[stable(feature = "debug_builders", since = "1.2.0")]
1265     #[inline]
1266     pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1267         builders::debug_tuple_new(self, name)
1268     }
1269
1270     /// Creates a `DebugList` builder designed to assist with creation of
1271     /// `fmt::Debug` implementations for list-like structures.
1272     ///
1273     /// # Examples
1274     ///
1275     /// ```rust
1276     /// use std::fmt;
1277     ///
1278     /// struct Foo(Vec<i32>);
1279     ///
1280     /// impl fmt::Debug for Foo {
1281     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1282     ///         fmt.debug_list().entries(self.0.iter()).finish()
1283     ///     }
1284     /// }
1285     ///
1286     /// // prints "[10, 11]"
1287     /// println!("{:?}", Foo(vec![10, 11]));
1288     /// ```
1289     #[stable(feature = "debug_builders", since = "1.2.0")]
1290     #[inline]
1291     pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1292         builders::debug_list_new(self)
1293     }
1294
1295     /// Creates a `DebugSet` builder designed to assist with creation of
1296     /// `fmt::Debug` implementations for set-like structures.
1297     ///
1298     /// # Examples
1299     ///
1300     /// ```rust
1301     /// use std::fmt;
1302     ///
1303     /// struct Foo(Vec<i32>);
1304     ///
1305     /// impl fmt::Debug for Foo {
1306     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1307     ///         fmt.debug_set().entries(self.0.iter()).finish()
1308     ///     }
1309     /// }
1310     ///
1311     /// // prints "{10, 11}"
1312     /// println!("{:?}", Foo(vec![10, 11]));
1313     /// ```
1314     #[stable(feature = "debug_builders", since = "1.2.0")]
1315     #[inline]
1316     pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1317         builders::debug_set_new(self)
1318     }
1319
1320     /// Creates a `DebugMap` builder designed to assist with creation of
1321     /// `fmt::Debug` implementations for map-like structures.
1322     ///
1323     /// # Examples
1324     ///
1325     /// ```rust
1326     /// use std::fmt;
1327     ///
1328     /// struct Foo(Vec<(String, i32)>);
1329     ///
1330     /// impl fmt::Debug for Foo {
1331     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1332     ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1333     ///     }
1334     /// }
1335     ///
1336     /// // prints "{"A": 10, "B": 11}"
1337     /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1338     /// ```
1339     #[stable(feature = "debug_builders", since = "1.2.0")]
1340     #[inline]
1341     pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1342         builders::debug_map_new(self)
1343     }
1344 }
1345
1346 #[stable(since = "1.2.0", feature = "formatter_write")]
1347 impl<'a> Write for Formatter<'a> {
1348     fn write_str(&mut self, s: &str) -> Result {
1349         self.buf.write_str(s)
1350     }
1351
1352     fn write_char(&mut self, c: char) -> Result {
1353         self.buf.write_char(c)
1354     }
1355
1356     fn write_fmt(&mut self, args: Arguments) -> Result {
1357         write(self.buf, args)
1358     }
1359 }
1360
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 impl Display for Error {
1363     fn fmt(&self, f: &mut Formatter) -> Result {
1364         Display::fmt("an error occurred when formatting an argument", f)
1365     }
1366 }
1367
1368 // Implementations of the core formatting traits
1369
1370 macro_rules! fmt_refs {
1371     ($($tr:ident),*) => {
1372         $(
1373         #[stable(feature = "rust1", since = "1.0.0")]
1374         impl<'a, T: ?Sized + $tr> $tr for &'a T {
1375             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1376         }
1377         #[stable(feature = "rust1", since = "1.0.0")]
1378         impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1379             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1380         }
1381         )*
1382     }
1383 }
1384
1385 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1386
1387 #[unstable(feature = "never_type_impls", issue = "35121")]
1388 impl Debug for ! {
1389     fn fmt(&self, _: &mut Formatter) -> Result {
1390         *self
1391     }
1392 }
1393
1394 #[unstable(feature = "never_type_impls", issue = "35121")]
1395 impl Display for ! {
1396     fn fmt(&self, _: &mut Formatter) -> Result {
1397         *self
1398     }
1399 }
1400
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl Debug for bool {
1403     fn fmt(&self, f: &mut Formatter) -> Result {
1404         Display::fmt(self, f)
1405     }
1406 }
1407
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 impl Display for bool {
1410     fn fmt(&self, f: &mut Formatter) -> Result {
1411         Display::fmt(if *self { "true" } else { "false" }, f)
1412     }
1413 }
1414
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 impl Debug for str {
1417     fn fmt(&self, f: &mut Formatter) -> Result {
1418         f.write_char('"')?;
1419         let mut from = 0;
1420         for (i, c) in self.char_indices() {
1421             let esc = c.escape_debug();
1422             // If char needs escaping, flush backlog so far and write, else skip
1423             if esc.len() != 1 {
1424                 f.write_str(&self[from..i])?;
1425                 for c in esc {
1426                     f.write_char(c)?;
1427                 }
1428                 from = i + c.len_utf8();
1429             }
1430         }
1431         f.write_str(&self[from..])?;
1432         f.write_char('"')
1433     }
1434 }
1435
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 impl Display for str {
1438     fn fmt(&self, f: &mut Formatter) -> Result {
1439         f.pad(self)
1440     }
1441 }
1442
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl Debug for char {
1445     fn fmt(&self, f: &mut Formatter) -> Result {
1446         f.write_char('\'')?;
1447         for c in self.escape_debug() {
1448             f.write_char(c)?
1449         }
1450         f.write_char('\'')
1451     }
1452 }
1453
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 impl Display for char {
1456     fn fmt(&self, f: &mut Formatter) -> Result {
1457         if f.width.is_none() && f.precision.is_none() {
1458             f.write_char(*self)
1459         } else {
1460             f.pad(self.encode_utf8(&mut [0; 4]))
1461         }
1462     }
1463 }
1464
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 impl<T: ?Sized> Pointer for *const T {
1467     fn fmt(&self, f: &mut Formatter) -> Result {
1468         let old_width = f.width;
1469         let old_flags = f.flags;
1470
1471         // The alternate flag is already treated by LowerHex as being special-
1472         // it denotes whether to prefix with 0x. We use it to work out whether
1473         // or not to zero extend, and then unconditionally set it to get the
1474         // prefix.
1475         if f.alternate() {
1476             f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1477
1478             if let None = f.width {
1479                 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
1480             }
1481         }
1482         f.flags |= 1 << (FlagV1::Alternate as u32);
1483
1484         let ret = LowerHex::fmt(&(*self as *const () as usize), f);
1485
1486         f.width = old_width;
1487         f.flags = old_flags;
1488
1489         ret
1490     }
1491 }
1492
1493 #[stable(feature = "rust1", since = "1.0.0")]
1494 impl<T: ?Sized> Pointer for *mut T {
1495     fn fmt(&self, f: &mut Formatter) -> Result {
1496         Pointer::fmt(&(*self as *const T), f)
1497     }
1498 }
1499
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 impl<'a, T: ?Sized> Pointer for &'a T {
1502     fn fmt(&self, f: &mut Formatter) -> Result {
1503         Pointer::fmt(&(*self as *const T), f)
1504     }
1505 }
1506
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 impl<'a, T: ?Sized> Pointer for &'a mut T {
1509     fn fmt(&self, f: &mut Formatter) -> Result {
1510         Pointer::fmt(&(&**self as *const T), f)
1511     }
1512 }
1513
1514 // Common code of floating point Debug and Display.
1515 fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
1516     where T: flt2dec::DecodableFloat
1517 {
1518     let force_sign = fmt.sign_plus();
1519     let sign = match (force_sign, negative_zero) {
1520         (false, false) => flt2dec::Sign::Minus,
1521         (false, true)  => flt2dec::Sign::MinusRaw,
1522         (true,  false) => flt2dec::Sign::MinusPlus,
1523         (true,  true)  => flt2dec::Sign::MinusPlusRaw,
1524     };
1525
1526     let mut buf = [0; 1024]; // enough for f32 and f64
1527     let mut parts = [flt2dec::Part::Zero(0); 16];
1528     let formatted = if let Some(precision) = fmt.precision {
1529         flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1530                                     precision, false, &mut buf, &mut parts)
1531     } else {
1532         flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1533                                  0, false, &mut buf, &mut parts)
1534     };
1535     fmt.pad_formatted_parts(&formatted)
1536 }
1537
1538 // Common code of floating point LowerExp and UpperExp.
1539 fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
1540     where T: flt2dec::DecodableFloat
1541 {
1542     let force_sign = fmt.sign_plus();
1543     let sign = match force_sign {
1544         false => flt2dec::Sign::Minus,
1545         true  => flt2dec::Sign::MinusPlus,
1546     };
1547
1548     let mut buf = [0; 1024]; // enough for f32 and f64
1549     let mut parts = [flt2dec::Part::Zero(0); 16];
1550     let formatted = if let Some(precision) = fmt.precision {
1551         // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1552         flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1553                                   precision + 1, upper, &mut buf, &mut parts)
1554     } else {
1555         flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1556                                      (0, 0), upper, &mut buf, &mut parts)
1557     };
1558     fmt.pad_formatted_parts(&formatted)
1559 }
1560
1561 macro_rules! floating { ($ty:ident) => {
1562
1563     #[stable(feature = "rust1", since = "1.0.0")]
1564     impl Debug for $ty {
1565         fn fmt(&self, fmt: &mut Formatter) -> Result {
1566             float_to_decimal_common(fmt, self, true)
1567         }
1568     }
1569
1570     #[stable(feature = "rust1", since = "1.0.0")]
1571     impl Display for $ty {
1572         fn fmt(&self, fmt: &mut Formatter) -> Result {
1573             float_to_decimal_common(fmt, self, false)
1574         }
1575     }
1576
1577     #[stable(feature = "rust1", since = "1.0.0")]
1578     impl LowerExp for $ty {
1579         fn fmt(&self, fmt: &mut Formatter) -> Result {
1580             float_to_exponential_common(fmt, self, false)
1581         }
1582     }
1583
1584     #[stable(feature = "rust1", since = "1.0.0")]
1585     impl UpperExp for $ty {
1586         fn fmt(&self, fmt: &mut Formatter) -> Result {
1587             float_to_exponential_common(fmt, self, true)
1588         }
1589     }
1590 } }
1591 floating! { f32 }
1592 floating! { f64 }
1593
1594 // Implementation of Display/Debug for various core types
1595
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl<T: ?Sized> Debug for *const T {
1598     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1599 }
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl<T: ?Sized> Debug for *mut T {
1602     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1603 }
1604
1605 macro_rules! peel {
1606     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1607 }
1608
1609 macro_rules! tuple {
1610     () => ();
1611     ( $($name:ident,)+ ) => (
1612         #[stable(feature = "rust1", since = "1.0.0")]
1613         impl<$($name:Debug),*> Debug for ($($name,)*) {
1614             #[allow(non_snake_case, unused_assignments, deprecated)]
1615             fn fmt(&self, f: &mut Formatter) -> Result {
1616                 let mut builder = f.debug_tuple("");
1617                 let ($(ref $name,)*) = *self;
1618                 $(
1619                     builder.field($name);
1620                 )*
1621
1622                 builder.finish()
1623             }
1624         }
1625         peel! { $($name,)* }
1626     )
1627 }
1628
1629 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1630
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 impl<T: Debug> Debug for [T] {
1633     fn fmt(&self, f: &mut Formatter) -> Result {
1634         f.debug_list().entries(self.iter()).finish()
1635     }
1636 }
1637
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl Debug for () {
1640     fn fmt(&self, f: &mut Formatter) -> Result {
1641         f.pad("()")
1642     }
1643 }
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 impl<T: ?Sized> Debug for PhantomData<T> {
1646     fn fmt(&self, f: &mut Formatter) -> Result {
1647         f.pad("PhantomData")
1648     }
1649 }
1650
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 impl<T: Copy + Debug> Debug for Cell<T> {
1653     fn fmt(&self, f: &mut Formatter) -> Result {
1654         f.debug_struct("Cell")
1655             .field("value", &self.get())
1656             .finish()
1657     }
1658 }
1659
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1662     fn fmt(&self, f: &mut Formatter) -> Result {
1663         match self.try_borrow() {
1664             Ok(borrow) => {
1665                 f.debug_struct("RefCell")
1666                     .field("value", &borrow)
1667                     .finish()
1668             }
1669             Err(_) => {
1670                 f.debug_struct("RefCell")
1671                     .field("value", &"<borrowed>")
1672                     .finish()
1673             }
1674         }
1675     }
1676 }
1677
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1680     fn fmt(&self, f: &mut Formatter) -> Result {
1681         Debug::fmt(&**self, f)
1682     }
1683 }
1684
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1687     fn fmt(&self, f: &mut Formatter) -> Result {
1688         Debug::fmt(&*(self.deref()), f)
1689     }
1690 }
1691
1692 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1693 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
1694     fn fmt(&self, f: &mut Formatter) -> Result {
1695         f.pad("UnsafeCell")
1696     }
1697 }
1698
1699 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1700 // it's a lot easier than creating all of the rt::Piece structures here.