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