]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/mod.rs
Improve type size assertions
[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 crate::cell::{UnsafeCell, Cell, RefCell, Ref, RefMut};
6 use crate::marker::PhantomData;
7 use crate::mem;
8 use crate::num::flt2dec;
9 use crate::ops::Deref;
10 use crate::result;
11 use crate::slice;
12 use crate::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 idx = 0;
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(args.pieces.iter()) {
1015                 formatter.buf.write_str(*piece)?;
1016                 (arg.formatter)(arg.value, &mut formatter)?;
1017                 idx += 1;
1018             }
1019         }
1020         Some(fmt) => {
1021             // Every spec has a corresponding argument that is preceded by
1022             // a string piece.
1023             for (arg, piece) in fmt.iter().zip(args.pieces.iter()) {
1024                 formatter.buf.write_str(*piece)?;
1025                 formatter.run(arg)?;
1026                 idx += 1;
1027             }
1028         }
1029     }
1030
1031     // There can be only one trailing string piece left.
1032     if let Some(piece) = args.pieces.get(idx) {
1033         formatter.buf.write_str(*piece)?;
1034     }
1035
1036     Ok(())
1037 }
1038
1039 /// Padding after the end of something. Returned by `Formatter::padding`.
1040 #[must_use = "don't forget to write the post padding"]
1041 struct PostPadding {
1042     fill: char,
1043     padding: usize,
1044 }
1045
1046 impl PostPadding {
1047     fn new(fill: char, padding: usize) -> PostPadding {
1048         PostPadding { fill, padding }
1049     }
1050
1051     /// Write this post padding.
1052     fn write(self, buf: &mut dyn Write) -> Result {
1053         for _ in 0..self.padding {
1054             buf.write_char(self.fill)?;
1055         }
1056         Ok(())
1057     }
1058 }
1059
1060 impl<'a> Formatter<'a> {
1061     fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1062         where 'b: 'c, F: FnOnce(&'b mut (dyn Write+'b)) -> &'c mut (dyn Write+'c)
1063     {
1064         Formatter {
1065             // We want to change this
1066             buf: wrap(self.buf),
1067
1068             // And preserve these
1069             flags: self.flags,
1070             fill: self.fill,
1071             align: self.align,
1072             width: self.width,
1073             precision: self.precision,
1074
1075             // These only exist in the struct for the `run` method,
1076             // which won’t be used together with this method.
1077             curarg: self.curarg.clone(),
1078             args: self.args,
1079         }
1080     }
1081
1082     // First up is the collection of functions used to execute a format string
1083     // at runtime. This consumes all of the compile-time statics generated by
1084     // the format! syntax extension.
1085     fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1086         // Fill in the format parameters into the formatter
1087         self.fill = arg.format.fill;
1088         self.align = arg.format.align;
1089         self.flags = arg.format.flags;
1090         self.width = self.getcount(&arg.format.width);
1091         self.precision = self.getcount(&arg.format.precision);
1092
1093         // Extract the correct argument
1094         let value = match arg.position {
1095             rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1096             rt::v1::Position::At(i) => self.args[i],
1097         };
1098
1099         // Then actually do some printing
1100         (value.formatter)(value.value, self)
1101     }
1102
1103     fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1104         match *cnt {
1105             rt::v1::Count::Is(n) => Some(n),
1106             rt::v1::Count::Implied => None,
1107             rt::v1::Count::Param(i) => {
1108                 self.args[i].as_usize()
1109             }
1110             rt::v1::Count::NextParam => {
1111                 self.curarg.next()?.as_usize()
1112             }
1113         }
1114     }
1115
1116     // Helper methods used for padding and processing formatting arguments that
1117     // all formatting traits can use.
1118
1119     /// Performs the correct padding for an integer which has already been
1120     /// emitted into a str. The str should *not* contain the sign for the
1121     /// integer, that will be added by this method.
1122     ///
1123     /// # Arguments
1124     ///
1125     /// * is_nonnegative - whether the original integer was either positive or zero.
1126     /// * prefix - if the '#' character (Alternate) is provided, this
1127     ///   is the prefix to put in front of the number.
1128     /// * buf - the byte array that the number has been formatted into
1129     ///
1130     /// This function will correctly account for the flags provided as well as
1131     /// the minimum width. It will not take precision into account.
1132     ///
1133     /// # Examples
1134     ///
1135     /// ```
1136     /// use std::fmt;
1137     ///
1138     /// struct Foo { nb: i32 };
1139     ///
1140     /// impl Foo {
1141     ///     fn new(nb: i32) -> Foo {
1142     ///         Foo {
1143     ///             nb,
1144     ///         }
1145     ///     }
1146     /// }
1147     ///
1148     /// impl fmt::Display for Foo {
1149     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1150     ///         // We need to remove "-" from the number output.
1151     ///         let tmp = self.nb.abs().to_string();
1152     ///
1153     ///         formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1154     ///     }
1155     /// }
1156     ///
1157     /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1158     /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1159     /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1160     /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1161     /// ```
1162     #[stable(feature = "rust1", since = "1.0.0")]
1163     pub fn pad_integral(&mut self,
1164                         is_nonnegative: bool,
1165                         prefix: &str,
1166                         buf: &str)
1167                         -> Result {
1168         let mut width = buf.len();
1169
1170         let mut sign = None;
1171         if !is_nonnegative {
1172             sign = Some('-'); width += 1;
1173         } else if self.sign_plus() {
1174             sign = Some('+'); width += 1;
1175         }
1176
1177         let prefix = if self.alternate() {
1178             width += prefix.chars().count();
1179             Some(prefix)
1180         } else {
1181             None
1182         };
1183
1184         // Writes the sign if it exists, and then the prefix if it was requested
1185         #[inline(never)]
1186         fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1187             if let Some(c) = sign {
1188                 f.buf.write_char(c)?;
1189             }
1190             if let Some(prefix) = prefix {
1191                 f.buf.write_str(prefix)
1192             } else {
1193                 Ok(())
1194             }
1195         }
1196
1197         // The `width` field is more of a `min-width` parameter at this point.
1198         match self.width {
1199             // If there's no minimum length requirements then we can just
1200             // write the bytes.
1201             None => {
1202                 write_prefix(self, sign, prefix)?;
1203                 self.buf.write_str(buf)
1204             }
1205             // Check if we're over the minimum width, if so then we can also
1206             // just write the bytes.
1207             Some(min) if width >= min => {
1208                 write_prefix(self, sign, prefix)?;
1209                 self.buf.write_str(buf)
1210             }
1211             // The sign and prefix goes before the padding if the fill character
1212             // is zero
1213             Some(min) if self.sign_aware_zero_pad() => {
1214                 self.fill = '0';
1215                 self.align = rt::v1::Alignment::Right;
1216                 write_prefix(self, sign, prefix)?;
1217                 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1218                 self.buf.write_str(buf)?;
1219                 post_padding.write(self.buf)
1220             }
1221             // Otherwise, the sign and prefix goes after the padding
1222             Some(min) => {
1223                 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1224                 write_prefix(self, sign, prefix)?;
1225                 self.buf.write_str(buf)?;
1226                 post_padding.write(self.buf)
1227             }
1228         }
1229     }
1230
1231     /// This function takes a string slice and emits it to the internal buffer
1232     /// after applying the relevant formatting flags specified. The flags
1233     /// recognized for generic strings are:
1234     ///
1235     /// * width - the minimum width of what to emit
1236     /// * fill/align - what to emit and where to emit it if the string
1237     ///                provided needs to be padded
1238     /// * precision - the maximum length to emit, the string is truncated if it
1239     ///               is longer than this length
1240     ///
1241     /// Notably this function ignores the `flag` parameters.
1242     ///
1243     /// # Examples
1244     ///
1245     /// ```
1246     /// use std::fmt;
1247     ///
1248     /// struct Foo;
1249     ///
1250     /// impl fmt::Display for Foo {
1251     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1252     ///         formatter.pad("Foo")
1253     ///     }
1254     /// }
1255     ///
1256     /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1257     /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1258     /// ```
1259     #[stable(feature = "rust1", since = "1.0.0")]
1260     pub fn pad(&mut self, s: &str) -> Result {
1261         // Make sure there's a fast path up front
1262         if self.width.is_none() && self.precision.is_none() {
1263             return self.buf.write_str(s);
1264         }
1265         // The `precision` field can be interpreted as a `max-width` for the
1266         // string being formatted.
1267         let s = if let Some(max) = self.precision {
1268             // If our string is longer that the precision, then we must have
1269             // truncation. However other flags like `fill`, `width` and `align`
1270             // must act as always.
1271             if let Some((i, _)) = s.char_indices().nth(max) {
1272                 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1273                 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1274                 // `unsafe` and otherwise don't emit any panic-related code
1275                 // here.
1276                 s.get(..i).unwrap_or(&s)
1277             } else {
1278                 &s
1279             }
1280         } else {
1281             &s
1282         };
1283         // The `width` field is more of a `min-width` parameter at this point.
1284         match self.width {
1285             // If we're under the maximum length, and there's no minimum length
1286             // requirements, then we can just emit the string
1287             None => self.buf.write_str(s),
1288             // If we're under the maximum width, check if we're over the minimum
1289             // width, if so it's as easy as just emitting the string.
1290             Some(width) if s.chars().count() >= width => {
1291                 self.buf.write_str(s)
1292             }
1293             // If we're under both the maximum and the minimum width, then fill
1294             // up the minimum width with the specified string + some alignment.
1295             Some(width) => {
1296                 let align = rt::v1::Alignment::Left;
1297                 let post_padding = self.padding(width - s.chars().count(), align)?;
1298                 self.buf.write_str(s)?;
1299                 post_padding.write(self.buf)
1300             }
1301         }
1302     }
1303
1304     /// Write the pre-padding and return the unwritten post-padding. Callers are
1305     /// responsible for ensuring post-padding is written after the thing that is
1306     /// being padded.
1307     fn padding(
1308         &mut self,
1309         padding: usize,
1310         default: rt::v1::Alignment
1311     ) -> result::Result<PostPadding, Error> {
1312         let align = match self.align {
1313             rt::v1::Alignment::Unknown => default,
1314             _ => self.align
1315         };
1316
1317         let (pre_pad, post_pad) = match align {
1318             rt::v1::Alignment::Left => (0, padding),
1319             rt::v1::Alignment::Right |
1320             rt::v1::Alignment::Unknown => (padding, 0),
1321             rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1322         };
1323
1324         for _ in 0..pre_pad {
1325             self.buf.write_char(self.fill)?;
1326         }
1327
1328         Ok(PostPadding::new(self.fill, post_pad))
1329     }
1330
1331     /// Takes the formatted parts and applies the padding.
1332     /// Assumes that the caller already has rendered the parts with required precision,
1333     /// so that `self.precision` can be ignored.
1334     fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted<'_>) -> Result {
1335         if let Some(mut width) = self.width {
1336             // for the sign-aware zero padding, we render the sign first and
1337             // behave as if we had no sign from the beginning.
1338             let mut formatted = formatted.clone();
1339             let old_fill = self.fill;
1340             let old_align = self.align;
1341             let mut align = old_align;
1342             if self.sign_aware_zero_pad() {
1343                 // a sign always goes first
1344                 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1345                 self.buf.write_str(sign)?;
1346
1347                 // remove the sign from the formatted parts
1348                 formatted.sign = b"";
1349                 width = width.saturating_sub(sign.len());
1350                 align = rt::v1::Alignment::Right;
1351                 self.fill = '0';
1352                 self.align = rt::v1::Alignment::Right;
1353             }
1354
1355             // remaining parts go through the ordinary padding process.
1356             let len = formatted.len();
1357             let ret = if width <= len { // no padding
1358                 self.write_formatted_parts(&formatted)
1359             } else {
1360                 let post_padding = self.padding(width - len, align)?;
1361                 self.write_formatted_parts(&formatted)?;
1362                 post_padding.write(self.buf)
1363             };
1364             self.fill = old_fill;
1365             self.align = old_align;
1366             ret
1367         } else {
1368             // this is the common case and we take a shortcut
1369             self.write_formatted_parts(formatted)
1370         }
1371     }
1372
1373     fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted<'_>) -> Result {
1374         fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1375             buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1376         }
1377
1378         if !formatted.sign.is_empty() {
1379             write_bytes(self.buf, formatted.sign)?;
1380         }
1381         for part in formatted.parts {
1382             match *part {
1383                 flt2dec::Part::Zero(mut nzeroes) => {
1384                     const ZEROES: &str = // 64 zeroes
1385                         "0000000000000000000000000000000000000000000000000000000000000000";
1386                     while nzeroes > ZEROES.len() {
1387                         self.buf.write_str(ZEROES)?;
1388                         nzeroes -= ZEROES.len();
1389                     }
1390                     if nzeroes > 0 {
1391                         self.buf.write_str(&ZEROES[..nzeroes])?;
1392                     }
1393                 }
1394                 flt2dec::Part::Num(mut v) => {
1395                     let mut s = [0; 5];
1396                     let len = part.len();
1397                     for c in s[..len].iter_mut().rev() {
1398                         *c = b'0' + (v % 10) as u8;
1399                         v /= 10;
1400                     }
1401                     write_bytes(self.buf, &s[..len])?;
1402                 }
1403                 flt2dec::Part::Copy(buf) => {
1404                     write_bytes(self.buf, buf)?;
1405                 }
1406             }
1407         }
1408         Ok(())
1409     }
1410
1411     /// Writes some data to the underlying buffer contained within this
1412     /// formatter.
1413     ///
1414     /// # Examples
1415     ///
1416     /// ```
1417     /// use std::fmt;
1418     ///
1419     /// struct Foo;
1420     ///
1421     /// impl fmt::Display for Foo {
1422     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1423     ///         formatter.write_str("Foo")
1424     ///         // This is equivalent to:
1425     ///         // write!(formatter, "Foo")
1426     ///     }
1427     /// }
1428     ///
1429     /// assert_eq!(&format!("{}", Foo), "Foo");
1430     /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1431     /// ```
1432     #[stable(feature = "rust1", since = "1.0.0")]
1433     pub fn write_str(&mut self, data: &str) -> Result {
1434         self.buf.write_str(data)
1435     }
1436
1437     /// Writes some formatted information into this instance.
1438     ///
1439     /// # Examples
1440     ///
1441     /// ```
1442     /// use std::fmt;
1443     ///
1444     /// struct Foo(i32);
1445     ///
1446     /// impl fmt::Display for Foo {
1447     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1448     ///         formatter.write_fmt(format_args!("Foo {}", self.0))
1449     ///     }
1450     /// }
1451     ///
1452     /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1453     /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1454     /// ```
1455     #[stable(feature = "rust1", since = "1.0.0")]
1456     pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1457         write(self.buf, fmt)
1458     }
1459
1460     /// Flags for formatting
1461     #[stable(feature = "rust1", since = "1.0.0")]
1462     #[rustc_deprecated(since = "1.24.0",
1463                        reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1464                                  or `sign_aware_zero_pad` methods instead")]
1465     pub fn flags(&self) -> u32 { self.flags }
1466
1467     /// Character used as 'fill' whenever there is alignment.
1468     ///
1469     /// # Examples
1470     ///
1471     /// ```
1472     /// use std::fmt;
1473     ///
1474     /// struct Foo;
1475     ///
1476     /// impl fmt::Display for Foo {
1477     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1478     ///         let c = formatter.fill();
1479     ///         if let Some(width) = formatter.width() {
1480     ///             for _ in 0..width {
1481     ///                 write!(formatter, "{}", c)?;
1482     ///             }
1483     ///             Ok(())
1484     ///         } else {
1485     ///             write!(formatter, "{}", c)
1486     ///         }
1487     ///     }
1488     /// }
1489     ///
1490     /// // We set alignment to the left with ">".
1491     /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1492     /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1493     /// ```
1494     #[stable(feature = "fmt_flags", since = "1.5.0")]
1495     pub fn fill(&self) -> char { self.fill }
1496
1497     /// Flag indicating what form of alignment was requested.
1498     ///
1499     /// # Examples
1500     ///
1501     /// ```
1502     /// extern crate core;
1503     ///
1504     /// use std::fmt::{self, Alignment};
1505     ///
1506     /// struct Foo;
1507     ///
1508     /// impl fmt::Display for Foo {
1509     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1510     ///         let s = if let Some(s) = formatter.align() {
1511     ///             match s {
1512     ///                 Alignment::Left    => "left",
1513     ///                 Alignment::Right   => "right",
1514     ///                 Alignment::Center  => "center",
1515     ///             }
1516     ///         } else {
1517     ///             "into the void"
1518     ///         };
1519     ///         write!(formatter, "{}", s)
1520     ///     }
1521     /// }
1522     ///
1523     /// fn main() {
1524     ///     assert_eq!(&format!("{:<}", Foo), "left");
1525     ///     assert_eq!(&format!("{:>}", Foo), "right");
1526     ///     assert_eq!(&format!("{:^}", Foo), "center");
1527     ///     assert_eq!(&format!("{}", Foo), "into the void");
1528     /// }
1529     /// ```
1530     #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1531     pub fn align(&self) -> Option<Alignment> {
1532         match self.align {
1533             rt::v1::Alignment::Left => Some(Alignment::Left),
1534             rt::v1::Alignment::Right => Some(Alignment::Right),
1535             rt::v1::Alignment::Center => Some(Alignment::Center),
1536             rt::v1::Alignment::Unknown => None,
1537         }
1538     }
1539
1540     /// Optionally specified integer width that the output should be.
1541     ///
1542     /// # Examples
1543     ///
1544     /// ```
1545     /// use std::fmt;
1546     ///
1547     /// struct Foo(i32);
1548     ///
1549     /// impl fmt::Display for Foo {
1550     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1551     ///         if let Some(width) = formatter.width() {
1552     ///             // If we received a width, we use it
1553     ///             write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1554     ///         } else {
1555     ///             // Otherwise we do nothing special
1556     ///             write!(formatter, "Foo({})", self.0)
1557     ///         }
1558     ///     }
1559     /// }
1560     ///
1561     /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23)   ");
1562     /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1563     /// ```
1564     #[stable(feature = "fmt_flags", since = "1.5.0")]
1565     pub fn width(&self) -> Option<usize> { self.width }
1566
1567     /// Optionally specified precision for numeric types.
1568     ///
1569     /// # Examples
1570     ///
1571     /// ```
1572     /// use std::fmt;
1573     ///
1574     /// struct Foo(f32);
1575     ///
1576     /// impl fmt::Display for Foo {
1577     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1578     ///         if let Some(precision) = formatter.precision() {
1579     ///             // If we received a precision, we use it.
1580     ///             write!(formatter, "Foo({1:.*})", precision, self.0)
1581     ///         } else {
1582     ///             // Otherwise we default to 2.
1583     ///             write!(formatter, "Foo({:.2})", self.0)
1584     ///         }
1585     ///     }
1586     /// }
1587     ///
1588     /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1589     /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1590     /// ```
1591     #[stable(feature = "fmt_flags", since = "1.5.0")]
1592     pub fn precision(&self) -> Option<usize> { self.precision }
1593
1594     /// Determines if the `+` flag was specified.
1595     ///
1596     /// # Examples
1597     ///
1598     /// ```
1599     /// use std::fmt;
1600     ///
1601     /// struct Foo(i32);
1602     ///
1603     /// impl fmt::Display for Foo {
1604     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1605     ///         if formatter.sign_plus() {
1606     ///             write!(formatter,
1607     ///                    "Foo({}{})",
1608     ///                    if self.0 < 0 { '-' } else { '+' },
1609     ///                    self.0)
1610     ///         } else {
1611     ///             write!(formatter, "Foo({})", self.0)
1612     ///         }
1613     ///     }
1614     /// }
1615     ///
1616     /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1617     /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1618     /// ```
1619     #[stable(feature = "fmt_flags", since = "1.5.0")]
1620     pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1621
1622     /// Determines if the `-` flag was specified.
1623     ///
1624     /// # Examples
1625     ///
1626     /// ```
1627     /// use std::fmt;
1628     ///
1629     /// struct Foo(i32);
1630     ///
1631     /// impl fmt::Display for Foo {
1632     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1633     ///         if formatter.sign_minus() {
1634     ///             // You want a minus sign? Have one!
1635     ///             write!(formatter, "-Foo({})", self.0)
1636     ///         } else {
1637     ///             write!(formatter, "Foo({})", self.0)
1638     ///         }
1639     ///     }
1640     /// }
1641     ///
1642     /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1643     /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1644     /// ```
1645     #[stable(feature = "fmt_flags", since = "1.5.0")]
1646     pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1647
1648     /// Determines if the `#` 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     ///         if formatter.alternate() {
1660     ///             write!(formatter, "Foo({})", self.0)
1661     ///         } else {
1662     ///             write!(formatter, "{}", self.0)
1663     ///         }
1664     ///     }
1665     /// }
1666     ///
1667     /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1668     /// assert_eq!(&format!("{}", Foo(23)), "23");
1669     /// ```
1670     #[stable(feature = "fmt_flags", since = "1.5.0")]
1671     pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1672
1673     /// Determines if the `0` flag was specified.
1674     ///
1675     /// # Examples
1676     ///
1677     /// ```
1678     /// use std::fmt;
1679     ///
1680     /// struct Foo(i32);
1681     ///
1682     /// impl fmt::Display for Foo {
1683     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1684     ///         assert!(formatter.sign_aware_zero_pad());
1685     ///         assert_eq!(formatter.width(), Some(4));
1686     ///         // We ignore the formatter's options.
1687     ///         write!(formatter, "{}", self.0)
1688     ///     }
1689     /// }
1690     ///
1691     /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1692     /// ```
1693     #[stable(feature = "fmt_flags", since = "1.5.0")]
1694     pub fn sign_aware_zero_pad(&self) -> bool {
1695         self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1696     }
1697
1698     // FIXME: Decide what public API we want for these two flags.
1699     // https://github.com/rust-lang/rust/issues/48584
1700     fn debug_lower_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0 }
1701
1702     fn debug_upper_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0 }
1703
1704     /// Creates a [`DebugStruct`] builder designed to assist with creation of
1705     /// [`fmt::Debug`] implementations for structs.
1706     ///
1707     /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1708     /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1709     ///
1710     /// # Examples
1711     ///
1712     /// ```rust
1713     /// use std::fmt;
1714     /// use std::net::Ipv4Addr;
1715     ///
1716     /// struct Foo {
1717     ///     bar: i32,
1718     ///     baz: String,
1719     ///     addr: Ipv4Addr,
1720     /// }
1721     ///
1722     /// impl fmt::Debug for Foo {
1723     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1724     ///         fmt.debug_struct("Foo")
1725     ///             .field("bar", &self.bar)
1726     ///             .field("baz", &self.baz)
1727     ///             .field("addr", &format_args!("{}", self.addr))
1728     ///             .finish()
1729     ///     }
1730     /// }
1731     ///
1732     /// assert_eq!(
1733     ///     "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1734     ///     format!("{:?}", Foo {
1735     ///         bar: 10,
1736     ///         baz: "Hello World".to_string(),
1737     ///         addr: Ipv4Addr::new(127, 0, 0, 1),
1738     ///     })
1739     /// );
1740     /// ```
1741     #[stable(feature = "debug_builders", since = "1.2.0")]
1742     pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1743         builders::debug_struct_new(self, name)
1744     }
1745
1746     /// Creates a `DebugTuple` builder designed to assist with creation of
1747     /// `fmt::Debug` implementations for tuple structs.
1748     ///
1749     /// # Examples
1750     ///
1751     /// ```rust
1752     /// use std::fmt;
1753     /// use std::marker::PhantomData;
1754     ///
1755     /// struct Foo<T>(i32, String, PhantomData<T>);
1756     ///
1757     /// impl<T> fmt::Debug for Foo<T> {
1758     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1759     ///         fmt.debug_tuple("Foo")
1760     ///             .field(&self.0)
1761     ///             .field(&self.1)
1762     ///             .field(&format_args!("_"))
1763     ///             .finish()
1764     ///     }
1765     /// }
1766     ///
1767     /// assert_eq!(
1768     ///     "Foo(10, \"Hello\", _)",
1769     ///     format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1770     /// );
1771     /// ```
1772     #[stable(feature = "debug_builders", since = "1.2.0")]
1773     pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1774         builders::debug_tuple_new(self, name)
1775     }
1776
1777     /// Creates a `DebugList` builder designed to assist with creation of
1778     /// `fmt::Debug` implementations for list-like structures.
1779     ///
1780     /// # Examples
1781     ///
1782     /// ```rust
1783     /// use std::fmt;
1784     ///
1785     /// struct Foo(Vec<i32>);
1786     ///
1787     /// impl fmt::Debug for Foo {
1788     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1789     ///         fmt.debug_list().entries(self.0.iter()).finish()
1790     ///     }
1791     /// }
1792     ///
1793     /// // prints "[10, 11]"
1794     /// println!("{:?}", Foo(vec![10, 11]));
1795     /// ```
1796     #[stable(feature = "debug_builders", since = "1.2.0")]
1797     pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1798         builders::debug_list_new(self)
1799     }
1800
1801     /// Creates a `DebugSet` builder designed to assist with creation of
1802     /// `fmt::Debug` implementations for set-like structures.
1803     ///
1804     /// # Examples
1805     ///
1806     /// ```rust
1807     /// use std::fmt;
1808     ///
1809     /// struct Foo(Vec<i32>);
1810     ///
1811     /// impl fmt::Debug for Foo {
1812     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1813     ///         fmt.debug_set().entries(self.0.iter()).finish()
1814     ///     }
1815     /// }
1816     ///
1817     /// // prints "{10, 11}"
1818     /// println!("{:?}", Foo(vec![10, 11]));
1819     /// ```
1820     ///
1821     /// [`format_args!`]: ../../std/macro.format_args.html
1822     ///
1823     /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1824     /// to build a list of match arms:
1825     ///
1826     /// ```rust
1827     /// use std::fmt;
1828     ///
1829     /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1830     /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1831     ///
1832     /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1833     /// where
1834     ///     L: 'a + fmt::Debug, R: 'a + fmt::Debug
1835     /// {
1836     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1837     ///         L::fmt(&(self.0).0, fmt)?;
1838     ///         fmt.write_str(" => ")?;
1839     ///         R::fmt(&(self.0).1, fmt)
1840     ///     }
1841     /// }
1842     ///
1843     /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1844     /// where
1845     ///     K: 'a + fmt::Debug, V: 'a + fmt::Debug
1846     /// {
1847     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1848     ///         fmt.debug_set()
1849     ///         .entries(self.0.iter().map(Arm))
1850     ///         .entry(&Arm(&(format_args!("_"), &self.1)))
1851     ///         .finish()
1852     ///     }
1853     /// }
1854     /// ```
1855     #[stable(feature = "debug_builders", since = "1.2.0")]
1856     pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1857         builders::debug_set_new(self)
1858     }
1859
1860     /// Creates a `DebugMap` builder designed to assist with creation of
1861     /// `fmt::Debug` implementations for map-like structures.
1862     ///
1863     /// # Examples
1864     ///
1865     /// ```rust
1866     /// use std::fmt;
1867     ///
1868     /// struct Foo(Vec<(String, i32)>);
1869     ///
1870     /// impl fmt::Debug for Foo {
1871     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1872     ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1873     ///     }
1874     /// }
1875     ///
1876     /// // prints "{"A": 10, "B": 11}"
1877     /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1878     /// ```
1879     #[stable(feature = "debug_builders", since = "1.2.0")]
1880     pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1881         builders::debug_map_new(self)
1882     }
1883 }
1884
1885 #[stable(since = "1.2.0", feature = "formatter_write")]
1886 impl Write for Formatter<'_> {
1887     fn write_str(&mut self, s: &str) -> Result {
1888         self.buf.write_str(s)
1889     }
1890
1891     fn write_char(&mut self, c: char) -> Result {
1892         self.buf.write_char(c)
1893     }
1894
1895     fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
1896         write(self.buf, args)
1897     }
1898 }
1899
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 impl Display for Error {
1902     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1903         Display::fmt("an error occurred when formatting an argument", f)
1904     }
1905 }
1906
1907 // Implementations of the core formatting traits
1908
1909 macro_rules! fmt_refs {
1910     ($($tr:ident),*) => {
1911         $(
1912         #[stable(feature = "rust1", since = "1.0.0")]
1913         impl<T: ?Sized + $tr> $tr for &T {
1914             fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
1915         }
1916         #[stable(feature = "rust1", since = "1.0.0")]
1917         impl<T: ?Sized + $tr> $tr for &mut T {
1918             fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
1919         }
1920         )*
1921     }
1922 }
1923
1924 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1925
1926 #[unstable(feature = "never_type", issue = "35121")]
1927 impl Debug for ! {
1928     fn fmt(&self, _: &mut Formatter<'_>) -> Result {
1929         *self
1930     }
1931 }
1932
1933 #[unstable(feature = "never_type", issue = "35121")]
1934 impl Display for ! {
1935     fn fmt(&self, _: &mut Formatter<'_>) -> Result {
1936         *self
1937     }
1938 }
1939
1940 #[stable(feature = "rust1", since = "1.0.0")]
1941 impl Debug for bool {
1942     #[inline]
1943     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1944         Display::fmt(self, f)
1945     }
1946 }
1947
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 impl Display for bool {
1950     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1951         Display::fmt(if *self { "true" } else { "false" }, f)
1952     }
1953 }
1954
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl Debug for str {
1957     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1958         f.write_char('"')?;
1959         let mut from = 0;
1960         for (i, c) in self.char_indices() {
1961             let esc = c.escape_debug();
1962             // If char needs escaping, flush backlog so far and write, else skip
1963             if esc.len() != 1 {
1964                 f.write_str(&self[from..i])?;
1965                 for c in esc {
1966                     f.write_char(c)?;
1967                 }
1968                 from = i + c.len_utf8();
1969             }
1970         }
1971         f.write_str(&self[from..])?;
1972         f.write_char('"')
1973     }
1974 }
1975
1976 #[stable(feature = "rust1", since = "1.0.0")]
1977 impl Display for str {
1978     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1979         f.pad(self)
1980     }
1981 }
1982
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl Debug for char {
1985     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1986         f.write_char('\'')?;
1987         for c in self.escape_debug() {
1988             f.write_char(c)?
1989         }
1990         f.write_char('\'')
1991     }
1992 }
1993
1994 #[stable(feature = "rust1", since = "1.0.0")]
1995 impl Display for char {
1996     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1997         if f.width.is_none() && f.precision.is_none() {
1998             f.write_char(*self)
1999         } else {
2000             f.pad(self.encode_utf8(&mut [0; 4]))
2001         }
2002     }
2003 }
2004
2005 #[stable(feature = "rust1", since = "1.0.0")]
2006 impl<T: ?Sized> Pointer for *const T {
2007     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2008         let old_width = f.width;
2009         let old_flags = f.flags;
2010
2011         // The alternate flag is already treated by LowerHex as being special-
2012         // it denotes whether to prefix with 0x. We use it to work out whether
2013         // or not to zero extend, and then unconditionally set it to get the
2014         // prefix.
2015         if f.alternate() {
2016             f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2017
2018             if let None = f.width {
2019                 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2020             }
2021         }
2022         f.flags |= 1 << (FlagV1::Alternate as u32);
2023
2024         let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2025
2026         f.width = old_width;
2027         f.flags = old_flags;
2028
2029         ret
2030     }
2031 }
2032
2033 #[stable(feature = "rust1", since = "1.0.0")]
2034 impl<T: ?Sized> Pointer for *mut T {
2035     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2036         Pointer::fmt(&(*self as *const T), f)
2037     }
2038 }
2039
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 impl<T: ?Sized> Pointer for &T {
2042     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2043         Pointer::fmt(&(*self as *const T), f)
2044     }
2045 }
2046
2047 #[stable(feature = "rust1", since = "1.0.0")]
2048 impl<T: ?Sized> Pointer for &mut T {
2049     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2050         Pointer::fmt(&(&**self as *const T), f)
2051     }
2052 }
2053
2054 // Implementation of Display/Debug for various core types
2055
2056 #[stable(feature = "rust1", since = "1.0.0")]
2057 impl<T: ?Sized> Debug for *const T {
2058     fn fmt(&self, f: &mut Formatter<'_>) -> Result { Pointer::fmt(self, f) }
2059 }
2060 #[stable(feature = "rust1", since = "1.0.0")]
2061 impl<T: ?Sized> Debug for *mut T {
2062     fn fmt(&self, f: &mut Formatter<'_>) -> Result { Pointer::fmt(self, f) }
2063 }
2064
2065 macro_rules! peel {
2066     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2067 }
2068
2069 macro_rules! tuple {
2070     () => ();
2071     ( $($name:ident,)+ ) => (
2072         #[stable(feature = "rust1", since = "1.0.0")]
2073         impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
2074             #[allow(non_snake_case, unused_assignments)]
2075             fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2076                 let mut builder = f.debug_tuple("");
2077                 let ($(ref $name,)*) = *self;
2078                 $(
2079                     builder.field(&$name);
2080                 )*
2081
2082                 builder.finish()
2083             }
2084         }
2085         peel! { $($name,)* }
2086     )
2087 }
2088
2089 macro_rules! last_type {
2090     ($a:ident,) => { $a };
2091     ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2092 }
2093
2094 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2095
2096 #[stable(feature = "rust1", since = "1.0.0")]
2097 impl<T: Debug> Debug for [T] {
2098     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2099         f.debug_list().entries(self.iter()).finish()
2100     }
2101 }
2102
2103 #[stable(feature = "rust1", since = "1.0.0")]
2104 impl Debug for () {
2105     #[inline]
2106     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2107         f.pad("()")
2108     }
2109 }
2110 #[stable(feature = "rust1", since = "1.0.0")]
2111 impl<T: ?Sized> Debug for PhantomData<T> {
2112     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2113         f.pad("PhantomData")
2114     }
2115 }
2116
2117 #[stable(feature = "rust1", since = "1.0.0")]
2118 impl<T: Copy + Debug> Debug for Cell<T> {
2119     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2120         f.debug_struct("Cell")
2121             .field("value", &self.get())
2122             .finish()
2123     }
2124 }
2125
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2128     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2129         match self.try_borrow() {
2130             Ok(borrow) => {
2131                 f.debug_struct("RefCell")
2132                     .field("value", &borrow)
2133                     .finish()
2134             }
2135             Err(_) => {
2136                 // The RefCell is mutably borrowed so we can't look at its value
2137                 // here. Show a placeholder instead.
2138                 struct BorrowedPlaceholder;
2139
2140                 impl Debug for BorrowedPlaceholder {
2141                     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2142                         f.write_str("<borrowed>")
2143                     }
2144                 }
2145
2146                 f.debug_struct("RefCell")
2147                     .field("value", &BorrowedPlaceholder)
2148                     .finish()
2149             }
2150         }
2151     }
2152 }
2153
2154 #[stable(feature = "rust1", since = "1.0.0")]
2155 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2156     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2157         Debug::fmt(&**self, f)
2158     }
2159 }
2160
2161 #[stable(feature = "rust1", since = "1.0.0")]
2162 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2163     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2164         Debug::fmt(&*(self.deref()), f)
2165     }
2166 }
2167
2168 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2169 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2170     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2171         f.pad("UnsafeCell")
2172     }
2173 }
2174
2175 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
2176 // it's a lot easier than creating all of the rt::Piece structures here.