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