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