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