]> git.lizzy.rs Git - rust.git/blob - library/core/src/fmt/mod.rs
Rollup merge of #106897 - estebank:issue-99430, r=davidtwco
[rust.git] / library / core / src / fmt / mod.rs
1 //! Utilities for formatting and printing strings.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 use crate::cell::{Cell, Ref, RefCell, RefMut, SyncUnsafeCell, UnsafeCell};
6 use crate::char::EscapeDebugExtArgs;
7 use crate::iter;
8 use crate::marker::PhantomData;
9 use crate::mem;
10 use crate::num::fmt as numfmt;
11 use crate::ops::Deref;
12 use crate::result;
13 use crate::str;
14
15 mod builders;
16 #[cfg(not(no_fp_fmt_parse))]
17 mod float;
18 #[cfg(no_fp_fmt_parse)]
19 mod nofloat;
20 mod num;
21
22 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
23 #[cfg_attr(not(test), rustc_diagnostic_item = "Alignment")]
24 /// Possible alignments returned by `Formatter::align`
25 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
26 pub enum Alignment {
27     #[stable(feature = "fmt_flags_align", since = "1.28.0")]
28     /// Indication that contents should be left-aligned.
29     Left,
30     #[stable(feature = "fmt_flags_align", since = "1.28.0")]
31     /// Indication that contents should be right-aligned.
32     Right,
33     #[stable(feature = "fmt_flags_align", since = "1.28.0")]
34     /// Indication that contents should be center-aligned.
35     Center,
36 }
37
38 #[stable(feature = "debug_builders", since = "1.2.0")]
39 pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
40
41 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
42 #[doc(hidden)]
43 pub mod rt {
44     pub mod v1;
45 }
46
47 /// The type returned by formatter methods.
48 ///
49 /// # Examples
50 ///
51 /// ```
52 /// use std::fmt;
53 ///
54 /// #[derive(Debug)]
55 /// struct Triangle {
56 ///     a: f32,
57 ///     b: f32,
58 ///     c: f32
59 /// }
60 ///
61 /// impl fmt::Display for Triangle {
62 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 ///         write!(f, "({}, {}, {})", self.a, self.b, self.c)
64 ///     }
65 /// }
66 ///
67 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
68 ///
69 /// assert_eq!(format!("{pythagorean_triple}"), "(3, 4, 5)");
70 /// ```
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub type Result = result::Result<(), Error>;
73
74 /// The error type which is returned from formatting a message into a stream.
75 ///
76 /// This type does not support transmission of an error other than that an error
77 /// occurred. Any extra information must be arranged to be transmitted through
78 /// some other means.
79 ///
80 /// An important thing to remember is that the type `fmt::Error` should not be
81 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
82 /// have in scope.
83 ///
84 /// [`std::io::Error`]: ../../std/io/struct.Error.html
85 /// [`std::error::Error`]: ../../std/error/trait.Error.html
86 ///
87 /// # Examples
88 ///
89 /// ```rust
90 /// use std::fmt::{self, write};
91 ///
92 /// let mut output = String::new();
93 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
94 ///     panic!("An error occurred");
95 /// }
96 /// ```
97 #[stable(feature = "rust1", since = "1.0.0")]
98 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
99 pub struct Error;
100
101 /// A trait for writing or formatting into Unicode-accepting buffers or streams.
102 ///
103 /// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
104 /// want to accept Unicode and you don't need flushing, you should implement this trait;
105 /// otherwise you should implement [`std::io::Write`].
106 ///
107 /// [`std::io::Write`]: ../../std/io/trait.Write.html
108 /// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
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     /// The purpose of std::fmt::Error is to abort the formatting operation when the underlying
123     /// destination encounters some error preventing it from accepting more text; it should
124     /// generally be propagated rather than handled, at least when implementing formatting traits.
125     ///
126     /// # Examples
127     ///
128     /// ```
129     /// use std::fmt::{Error, Write};
130     ///
131     /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
132     ///     f.write_str(s)
133     /// }
134     ///
135     /// let mut buf = String::new();
136     /// writer(&mut buf, "hola").unwrap();
137     /// assert_eq!(&buf, "hola");
138     /// ```
139     #[stable(feature = "rust1", since = "1.0.0")]
140     fn write_str(&mut self, s: &str) -> Result;
141
142     /// Writes a [`char`] into this writer, returning whether the write succeeded.
143     ///
144     /// A single [`char`] may be encoded as more than one byte.
145     /// This method can only succeed if the entire byte sequence was successfully
146     /// written, and this method will not return until all data has been
147     /// written or an error occurs.
148     ///
149     /// # Errors
150     ///
151     /// This function will return an instance of [`Error`] on error.
152     ///
153     /// # Examples
154     ///
155     /// ```
156     /// use std::fmt::{Error, Write};
157     ///
158     /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
159     ///     f.write_char(c)
160     /// }
161     ///
162     /// let mut buf = String::new();
163     /// writer(&mut buf, 'a').unwrap();
164     /// writer(&mut buf, 'b').unwrap();
165     /// assert_eq!(&buf, "ab");
166     /// ```
167     #[stable(feature = "fmt_write_char", since = "1.1.0")]
168     fn write_char(&mut self, c: char) -> Result {
169         self.write_str(c.encode_utf8(&mut [0; 4]))
170     }
171
172     /// Glue for usage of the [`write!`] macro with implementors of this trait.
173     ///
174     /// This method should generally not be invoked manually, but rather through
175     /// the [`write!`] macro itself.
176     ///
177     /// # Errors
178     ///
179     /// This function will return an instance of [`Error`] on error. Please see
180     /// [write_str](Write::write_str) for details.
181     ///
182     /// # Examples
183     ///
184     /// ```
185     /// use std::fmt::{Error, Write};
186     ///
187     /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
188     ///     f.write_fmt(format_args!("{s}"))
189     /// }
190     ///
191     /// let mut buf = String::new();
192     /// writer(&mut buf, "world").unwrap();
193     /// assert_eq!(&buf, "world");
194     /// ```
195     #[stable(feature = "rust1", since = "1.0.0")]
196     fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
197         write(&mut self, args)
198     }
199 }
200
201 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
202 impl<W: Write + ?Sized> Write for &mut W {
203     fn write_str(&mut self, s: &str) -> Result {
204         (**self).write_str(s)
205     }
206
207     fn write_char(&mut self, c: char) -> Result {
208         (**self).write_char(c)
209     }
210
211     fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
212         (**self).write_fmt(args)
213     }
214 }
215
216 /// Configuration for formatting.
217 ///
218 /// A `Formatter` represents various options related to formatting. Users do not
219 /// construct `Formatter`s directly; a mutable reference to one is passed to
220 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
221 ///
222 /// To interact with a `Formatter`, you'll call various methods to change the
223 /// various options related to formatting. For examples, please see the
224 /// documentation of the methods defined on `Formatter` below.
225 #[allow(missing_debug_implementations)]
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub struct Formatter<'a> {
228     flags: u32,
229     fill: char,
230     align: rt::v1::Alignment,
231     width: Option<usize>,
232     precision: Option<usize>,
233
234     buf: &'a mut (dyn Write + 'a),
235 }
236
237 impl<'a> Formatter<'a> {
238     /// Creates a new formatter with default settings.
239     ///
240     /// This can be used as a micro-optimization in cases where a full `Arguments`
241     /// structure (as created by `format_args!`) is not necessary; `Arguments`
242     /// is a little more expensive to use in simple formatting scenarios.
243     ///
244     /// Currently not intended for use outside of the standard library.
245     #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
246     #[doc(hidden)]
247     pub fn new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
248         Formatter {
249             flags: 0,
250             fill: ' ',
251             align: rt::v1::Alignment::Unknown,
252             width: None,
253             precision: None,
254             buf,
255         }
256     }
257 }
258
259 // NB. Argument is essentially an optimized partially applied formatting function,
260 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
261
262 extern "C" {
263     type Opaque;
264 }
265
266 /// This struct represents the generic "argument" which is taken by the Xprintf
267 /// family of functions. It contains a function to format the given value. At
268 /// compile time it is ensured that the function and the value have the correct
269 /// types, and then this struct is used to canonicalize arguments to one type.
270 #[derive(Copy, Clone)]
271 #[allow(missing_debug_implementations)]
272 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
273 #[doc(hidden)]
274 pub struct ArgumentV1<'a> {
275     value: &'a Opaque,
276     formatter: fn(&Opaque, &mut Formatter<'_>) -> Result,
277 }
278
279 /// This struct represents the unsafety of constructing an `Arguments`.
280 /// It exists, rather than an unsafe function, in order to simplify the expansion
281 /// of `format_args!(..)` and reduce the scope of the `unsafe` block.
282 #[allow(missing_debug_implementations)]
283 #[doc(hidden)]
284 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
285 pub struct UnsafeArg {
286     _private: (),
287 }
288
289 impl UnsafeArg {
290     /// See documentation where `UnsafeArg` is required to know when it is safe to
291     /// create and use `UnsafeArg`.
292     #[doc(hidden)]
293     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
294     #[inline(always)]
295     pub unsafe fn new() -> Self {
296         Self { _private: () }
297     }
298 }
299
300 // This guarantees a single stable value for the function pointer associated with
301 // indices/counts in the formatting infrastructure.
302 //
303 // Note that a function defined as such would not be correct as functions are
304 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
305 // address is not considered important to LLVM and as such the as_usize cast
306 // could have been miscompiled. In practice, we never call as_usize on non-usize
307 // containing data (as a matter of static generation of the formatting
308 // arguments), so this is merely an additional check.
309 //
310 // We primarily want to ensure that the function pointer at `USIZE_MARKER` has
311 // an address corresponding *only* to functions that also take `&usize` as their
312 // first argument. The read_volatile here ensures that we can safely ready out a
313 // usize from the passed reference and that this address does not point at a
314 // non-usize taking function.
315 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
316 static USIZE_MARKER: fn(&usize, &mut Formatter<'_>) -> Result = |ptr, _| {
317     // SAFETY: ptr is a reference
318     let _v: usize = unsafe { crate::ptr::read_volatile(ptr) };
319     loop {}
320 };
321
322 macro_rules! arg_new {
323     ($f: ident, $t: ident) => {
324         #[doc(hidden)]
325         #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
326         #[inline]
327         pub fn $f<'b, T: $t>(x: &'b T) -> ArgumentV1<'_> {
328             Self::new(x, $t::fmt)
329         }
330     };
331 }
332
333 #[rustc_diagnostic_item = "ArgumentV1Methods"]
334 impl<'a> ArgumentV1<'a> {
335     #[doc(hidden)]
336     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
337     #[inline]
338     pub fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
339         // SAFETY: `mem::transmute(x)` is safe because
340         //     1. `&'b T` keeps the lifetime it originated with `'b`
341         //              (so as to not have an unbounded lifetime)
342         //     2. `&'b T` and `&'b Opaque` have the same memory layout
343         //              (when `T` is `Sized`, as it is here)
344         // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
345         // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
346         // (as long as `T` is `Sized`)
347         unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) } }
348     }
349
350     arg_new!(new_display, Display);
351     arg_new!(new_debug, Debug);
352     arg_new!(new_octal, Octal);
353     arg_new!(new_lower_hex, LowerHex);
354     arg_new!(new_upper_hex, UpperHex);
355     arg_new!(new_pointer, Pointer);
356     arg_new!(new_binary, Binary);
357     arg_new!(new_lower_exp, LowerExp);
358     arg_new!(new_upper_exp, UpperExp);
359
360     #[doc(hidden)]
361     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
362     pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
363         ArgumentV1::new(x, USIZE_MARKER)
364     }
365
366     fn as_usize(&self) -> Option<usize> {
367         // We are type punning a bit here: USIZE_MARKER only takes an &usize but
368         // formatter takes an &Opaque. Rust understandably doesn't think we should compare
369         // the function pointers if they don't have the same signature, so we cast to
370         // usizes to tell it that we just want to compare addresses.
371         if self.formatter as usize == USIZE_MARKER as usize {
372             // SAFETY: The `formatter` field is only set to USIZE_MARKER if
373             // the value is a usize, so this is safe
374             Some(unsafe { *(self.value as *const _ as *const usize) })
375         } else {
376             None
377         }
378     }
379 }
380
381 // flags available in the v1 format of format_args
382 #[derive(Copy, Clone)]
383 enum FlagV1 {
384     SignPlus,
385     SignMinus,
386     Alternate,
387     SignAwareZeroPad,
388     DebugLowerHex,
389     DebugUpperHex,
390 }
391
392 impl<'a> Arguments<'a> {
393     /// When using the format_args!() macro, this function is used to generate the
394     /// Arguments structure.
395     #[doc(hidden)]
396     #[inline]
397     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
398     #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
399     pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
400         if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
401             panic!("invalid args");
402         }
403         Arguments { pieces, fmt: None, args }
404     }
405
406     /// This function is used to specify nonstandard formatting parameters.
407     ///
408     /// An `UnsafeArg` is required because the following invariants must be held
409     /// in order for this function to be safe:
410     /// 1. The `pieces` slice must be at least as long as `fmt`.
411     /// 2. Every [`rt::v1::Argument::position`] value within `fmt` must be a
412     ///    valid index of `args`.
413     /// 3. Every [`rt::v1::Count::Param`] within `fmt` must contain a valid index of
414     ///    `args`.
415     #[doc(hidden)]
416     #[inline]
417     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
418     #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
419     pub const fn new_v1_formatted(
420         pieces: &'a [&'static str],
421         args: &'a [ArgumentV1<'a>],
422         fmt: &'a [rt::v1::Argument],
423         _unsafe_arg: UnsafeArg,
424     ) -> Arguments<'a> {
425         Arguments { pieces, fmt: Some(fmt), args }
426     }
427
428     /// Estimates the length of the formatted text.
429     ///
430     /// This is intended to be used for setting initial `String` capacity
431     /// when using `format!`. Note: this is neither the lower nor upper bound.
432     #[doc(hidden)]
433     #[inline]
434     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
435     pub fn estimated_capacity(&self) -> usize {
436         let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
437
438         if self.args.is_empty() {
439             pieces_length
440         } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
441             // If the format string starts with an argument,
442             // don't preallocate anything, unless length
443             // of pieces is significant.
444             0
445         } else {
446             // There are some arguments, so any additional push
447             // will reallocate the string. To avoid that,
448             // we're "pre-doubling" the capacity here.
449             pieces_length.checked_mul(2).unwrap_or(0)
450         }
451     }
452 }
453
454 /// This structure represents a safely precompiled version of a format string
455 /// and its arguments. This cannot be generated at runtime because it cannot
456 /// safely be done, so no constructors are given and the fields are private
457 /// to prevent modification.
458 ///
459 /// The [`format_args!`] macro will safely create an instance of this structure.
460 /// The macro validates the format string at compile-time so usage of the
461 /// [`write()`] and [`format()`] functions can be safely performed.
462 ///
463 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
464 /// and `Display` contexts as seen below. The example also shows that `Debug`
465 /// and `Display` format to the same thing: the interpolated format string
466 /// in `format_args!`.
467 ///
468 /// ```rust
469 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
470 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
471 /// assert_eq!("1 foo 2", display);
472 /// assert_eq!(display, debug);
473 /// ```
474 ///
475 /// [`format()`]: ../../std/fmt/fn.format.html
476 #[stable(feature = "rust1", since = "1.0.0")]
477 #[cfg_attr(not(test), rustc_diagnostic_item = "Arguments")]
478 #[derive(Copy, Clone)]
479 pub struct Arguments<'a> {
480     // Format string pieces to print.
481     pieces: &'a [&'static str],
482
483     // Placeholder specs, or `None` if all specs are default (as in "{}{}").
484     fmt: Option<&'a [rt::v1::Argument]>,
485
486     // Dynamic arguments for interpolation, to be interleaved with string
487     // pieces. (Every argument is preceded by a string piece.)
488     args: &'a [ArgumentV1<'a>],
489 }
490
491 impl<'a> Arguments<'a> {
492     /// Get the formatted string, if it has no arguments to be formatted at runtime.
493     ///
494     /// This can be used to avoid allocations in some cases.
495     ///
496     /// # Guarantees
497     ///
498     /// For `format_args!("just a literal")`, this function is guaranteed to
499     /// return `Some("just a literal")`.
500     ///
501     /// For most cases with placeholders, this function will return `None`.
502     ///
503     /// However, the compiler may perform optimizations that can cause this
504     /// function to return `Some(_)` even if the format string contains
505     /// placeholders. For example, `format_args!("Hello, {}!", "world")` may be
506     /// optimized to `format_args!("Hello, world!")`, such that `as_str()`
507     /// returns `Some("Hello, world!")`.
508     ///
509     /// The behavior for anything but the trivial case (without placeholders)
510     /// is not guaranteed, and should not be relied upon for anything other
511     /// than optimization.
512     ///
513     /// # Examples
514     ///
515     /// ```rust
516     /// use std::fmt::Arguments;
517     ///
518     /// fn write_str(_: &str) { /* ... */ }
519     ///
520     /// fn write_fmt(args: &Arguments) {
521     ///     if let Some(s) = args.as_str() {
522     ///         write_str(s)
523     ///     } else {
524     ///         write_str(&args.to_string());
525     ///     }
526     /// }
527     /// ```
528     ///
529     /// ```rust
530     /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
531     /// assert_eq!(format_args!("").as_str(), Some(""));
532     /// assert_eq!(format_args!("{:?}", std::env::current_dir()).as_str(), None);
533     /// ```
534     #[stable(feature = "fmt_as_str", since = "1.52.0")]
535     #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")]
536     #[must_use]
537     #[inline]
538     pub const fn as_str(&self) -> Option<&'static str> {
539         match (self.pieces, self.args) {
540             ([], []) => Some(""),
541             ([s], []) => Some(s),
542             _ => None,
543         }
544     }
545 }
546
547 #[stable(feature = "rust1", since = "1.0.0")]
548 impl Debug for Arguments<'_> {
549     fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
550         Display::fmt(self, fmt)
551     }
552 }
553
554 #[stable(feature = "rust1", since = "1.0.0")]
555 impl Display for Arguments<'_> {
556     fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
557         write(fmt.buf, *self)
558     }
559 }
560
561 /// `?` formatting.
562 ///
563 /// `Debug` should format the output in a programmer-facing, debugging context.
564 ///
565 /// Generally speaking, you should just `derive` a `Debug` implementation.
566 ///
567 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
568 ///
569 /// For more information on formatters, see [the module-level documentation][module].
570 ///
571 /// [module]: ../../std/fmt/index.html
572 ///
573 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
574 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
575 /// comma-separated list of each field's name and `Debug` value, then `}`. For
576 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
577 /// `Debug` values of the fields, then `)`.
578 ///
579 /// # Stability
580 ///
581 /// Derived `Debug` formats are not stable, and so may change with future Rust
582 /// versions. Additionally, `Debug` implementations of types provided by the
583 /// standard library (`std`, `core`, `alloc`, etc.) are not stable, and
584 /// may also change with future Rust versions.
585 ///
586 /// # Examples
587 ///
588 /// Deriving an implementation:
589 ///
590 /// ```
591 /// #[derive(Debug)]
592 /// struct Point {
593 ///     x: i32,
594 ///     y: i32,
595 /// }
596 ///
597 /// let origin = Point { x: 0, y: 0 };
598 ///
599 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
600 /// ```
601 ///
602 /// Manually implementing:
603 ///
604 /// ```
605 /// use std::fmt;
606 ///
607 /// struct Point {
608 ///     x: i32,
609 ///     y: i32,
610 /// }
611 ///
612 /// impl fmt::Debug for Point {
613 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 ///         f.debug_struct("Point")
615 ///          .field("x", &self.x)
616 ///          .field("y", &self.y)
617 ///          .finish()
618 ///     }
619 /// }
620 ///
621 /// let origin = Point { x: 0, y: 0 };
622 ///
623 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
624 /// ```
625 ///
626 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
627 /// implementations, such as [`debug_struct`].
628 ///
629 /// [`debug_struct`]: Formatter::debug_struct
630 ///
631 /// Types that do not wish to use the standard suite of debug representations
632 /// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
633 /// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
634 /// manually writing an arbitrary representation to the `Formatter`.
635 ///
636 /// ```
637 /// # use std::fmt;
638 /// # struct Point {
639 /// #     x: i32,
640 /// #     y: i32,
641 /// # }
642 /// #
643 /// impl fmt::Debug for Point {
644 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
645 ///         write!(f, "Point [{} {}]", self.x, self.y)
646 ///     }
647 /// }
648 /// ```
649 ///
650 /// `Debug` implementations using either `derive` or the debug builder API
651 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
652 ///
653 /// Pretty-printing with `#?`:
654 ///
655 /// ```
656 /// #[derive(Debug)]
657 /// struct Point {
658 ///     x: i32,
659 ///     y: i32,
660 /// }
661 ///
662 /// let origin = Point { x: 0, y: 0 };
663 ///
664 /// assert_eq!(format!("The origin is: {origin:#?}"),
665 /// "The origin is: Point {
666 ///     x: 0,
667 ///     y: 0,
668 /// }");
669 /// ```
670
671 #[stable(feature = "rust1", since = "1.0.0")]
672 #[rustc_on_unimplemented(
673     on(
674         crate_local,
675         label = "`{Self}` cannot be formatted using `{{:?}}`",
676         note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
677     ),
678     message = "`{Self}` doesn't implement `{Debug}`",
679     label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
680 )]
681 #[doc(alias = "{:?}")]
682 #[rustc_diagnostic_item = "Debug"]
683 #[rustc_trivial_field_reads]
684 pub trait Debug {
685     /// Formats the value using the given formatter.
686     ///
687     /// # Examples
688     ///
689     /// ```
690     /// use std::fmt;
691     ///
692     /// struct Position {
693     ///     longitude: f32,
694     ///     latitude: f32,
695     /// }
696     ///
697     /// impl fmt::Debug for Position {
698     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699     ///         f.debug_tuple("")
700     ///          .field(&self.longitude)
701     ///          .field(&self.latitude)
702     ///          .finish()
703     ///     }
704     /// }
705     ///
706     /// let position = Position { longitude: 1.987, latitude: 2.983 };
707     /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
708     ///
709     /// assert_eq!(format!("{position:#?}"), "(
710     ///     1.987,
711     ///     2.983,
712     /// )");
713     /// ```
714     #[stable(feature = "rust1", since = "1.0.0")]
715     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
716 }
717
718 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
719 pub(crate) mod macros {
720     /// Derive macro generating an impl of the trait `Debug`.
721     #[rustc_builtin_macro]
722     #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
723     #[allow_internal_unstable(core_intrinsics, fmt_helpers_for_derive)]
724     pub macro Debug($item:item) {
725         /* compiler built-in */
726     }
727 }
728 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
729 #[doc(inline)]
730 pub use macros::Debug;
731
732 /// Format trait for an empty format, `{}`.
733 ///
734 /// Implementing this trait for a type will automatically implement the
735 /// [`ToString`][tostring] trait for the type, allowing the usage
736 /// of the [`.to_string()`][tostring_function] method. Prefer implementing
737 /// the `Display` trait for a type, rather than [`ToString`][tostring].
738 ///
739 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
740 /// output, and so cannot be derived.
741 ///
742 /// For more information on formatters, see [the module-level documentation][module].
743 ///
744 /// [module]: ../../std/fmt/index.html
745 /// [tostring]: ../../std/string/trait.ToString.html
746 /// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
747 ///
748 /// # Examples
749 ///
750 /// Implementing `Display` on a type:
751 ///
752 /// ```
753 /// use std::fmt;
754 ///
755 /// struct Point {
756 ///     x: i32,
757 ///     y: i32,
758 /// }
759 ///
760 /// impl fmt::Display for Point {
761 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762 ///         write!(f, "({}, {})", self.x, self.y)
763 ///     }
764 /// }
765 ///
766 /// let origin = Point { x: 0, y: 0 };
767 ///
768 /// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
769 /// ```
770 #[rustc_on_unimplemented(
771     on(
772         any(_Self = "std::path::Path", _Self = "std::path::PathBuf"),
773         label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
774         note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
775                 as they may contain non-Unicode data"
776     ),
777     message = "`{Self}` doesn't implement `{Display}`",
778     label = "`{Self}` cannot be formatted with the default formatter",
779     note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
780 )]
781 #[doc(alias = "{}")]
782 #[rustc_diagnostic_item = "Display"]
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub trait Display {
785     /// Formats the value using the given formatter.
786     ///
787     /// # Examples
788     ///
789     /// ```
790     /// use std::fmt;
791     ///
792     /// struct Position {
793     ///     longitude: f32,
794     ///     latitude: f32,
795     /// }
796     ///
797     /// impl fmt::Display for Position {
798     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
799     ///         write!(f, "({}, {})", self.longitude, self.latitude)
800     ///     }
801     /// }
802     ///
803     /// assert_eq!("(1.987, 2.983)",
804     ///            format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
805     /// ```
806     #[stable(feature = "rust1", since = "1.0.0")]
807     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
808 }
809
810 /// `o` formatting.
811 ///
812 /// The `Octal` trait should format its output as a number in base-8.
813 ///
814 /// For primitive signed integers (`i8` to `i128`, and `isize`),
815 /// negative values are formatted as the two’s complement representation.
816 ///
817 /// The alternate flag, `#`, adds a `0o` in front of the output.
818 ///
819 /// For more information on formatters, see [the module-level documentation][module].
820 ///
821 /// [module]: ../../std/fmt/index.html
822 ///
823 /// # Examples
824 ///
825 /// Basic usage with `i32`:
826 ///
827 /// ```
828 /// let x = 42; // 42 is '52' in octal
829 ///
830 /// assert_eq!(format!("{x:o}"), "52");
831 /// assert_eq!(format!("{x:#o}"), "0o52");
832 ///
833 /// assert_eq!(format!("{:o}", -16), "37777777760");
834 /// ```
835 ///
836 /// Implementing `Octal` on a type:
837 ///
838 /// ```
839 /// use std::fmt;
840 ///
841 /// struct Length(i32);
842 ///
843 /// impl fmt::Octal for Length {
844 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845 ///         let val = self.0;
846 ///
847 ///         fmt::Octal::fmt(&val, f) // delegate to i32's implementation
848 ///     }
849 /// }
850 ///
851 /// let l = Length(9);
852 ///
853 /// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
854 ///
855 /// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
856 /// ```
857 #[stable(feature = "rust1", since = "1.0.0")]
858 pub trait Octal {
859     /// Formats the value using the given formatter.
860     #[stable(feature = "rust1", since = "1.0.0")]
861     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
862 }
863
864 /// `b` formatting.
865 ///
866 /// The `Binary` trait should format its output as a number in binary.
867 ///
868 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
869 /// negative values are formatted as the two’s complement representation.
870 ///
871 /// The alternate flag, `#`, adds a `0b` in front of the output.
872 ///
873 /// For more information on formatters, see [the module-level documentation][module].
874 ///
875 /// [module]: ../../std/fmt/index.html
876 ///
877 /// # Examples
878 ///
879 /// Basic usage with [`i32`]:
880 ///
881 /// ```
882 /// let x = 42; // 42 is '101010' in binary
883 ///
884 /// assert_eq!(format!("{x:b}"), "101010");
885 /// assert_eq!(format!("{x:#b}"), "0b101010");
886 ///
887 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
888 /// ```
889 ///
890 /// Implementing `Binary` on a type:
891 ///
892 /// ```
893 /// use std::fmt;
894 ///
895 /// struct Length(i32);
896 ///
897 /// impl fmt::Binary for Length {
898 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899 ///         let val = self.0;
900 ///
901 ///         fmt::Binary::fmt(&val, f) // delegate to i32's implementation
902 ///     }
903 /// }
904 ///
905 /// let l = Length(107);
906 ///
907 /// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
908 ///
909 /// assert_eq!(
910 ///     format!("l as binary is: {l:#032b}"),
911 ///     "l as binary is: 0b000000000000000000000001101011"
912 /// );
913 /// ```
914 #[stable(feature = "rust1", since = "1.0.0")]
915 pub trait Binary {
916     /// Formats the value using the given formatter.
917     #[stable(feature = "rust1", since = "1.0.0")]
918     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
919 }
920
921 /// `x` formatting.
922 ///
923 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
924 /// in lower case.
925 ///
926 /// For primitive signed integers (`i8` to `i128`, and `isize`),
927 /// negative values are formatted as the two’s complement representation.
928 ///
929 /// The alternate flag, `#`, adds a `0x` in front of the output.
930 ///
931 /// For more information on formatters, see [the module-level documentation][module].
932 ///
933 /// [module]: ../../std/fmt/index.html
934 ///
935 /// # Examples
936 ///
937 /// Basic usage with `i32`:
938 ///
939 /// ```
940 /// let x = 42; // 42 is '2a' in hex
941 ///
942 /// assert_eq!(format!("{x:x}"), "2a");
943 /// assert_eq!(format!("{x:#x}"), "0x2a");
944 ///
945 /// assert_eq!(format!("{:x}", -16), "fffffff0");
946 /// ```
947 ///
948 /// Implementing `LowerHex` on a type:
949 ///
950 /// ```
951 /// use std::fmt;
952 ///
953 /// struct Length(i32);
954 ///
955 /// impl fmt::LowerHex for Length {
956 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
957 ///         let val = self.0;
958 ///
959 ///         fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
960 ///     }
961 /// }
962 ///
963 /// let l = Length(9);
964 ///
965 /// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
966 ///
967 /// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
968 /// ```
969 #[stable(feature = "rust1", since = "1.0.0")]
970 pub trait LowerHex {
971     /// Formats the value using the given formatter.
972     #[stable(feature = "rust1", since = "1.0.0")]
973     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
974 }
975
976 /// `X` formatting.
977 ///
978 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
979 /// in upper case.
980 ///
981 /// For primitive signed integers (`i8` to `i128`, and `isize`),
982 /// negative values are formatted as the two’s complement representation.
983 ///
984 /// The alternate flag, `#`, adds a `0x` in front of the output.
985 ///
986 /// For more information on formatters, see [the module-level documentation][module].
987 ///
988 /// [module]: ../../std/fmt/index.html
989 ///
990 /// # Examples
991 ///
992 /// Basic usage with `i32`:
993 ///
994 /// ```
995 /// let x = 42; // 42 is '2A' in hex
996 ///
997 /// assert_eq!(format!("{x:X}"), "2A");
998 /// assert_eq!(format!("{x:#X}"), "0x2A");
999 ///
1000 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
1001 /// ```
1002 ///
1003 /// Implementing `UpperHex` on a type:
1004 ///
1005 /// ```
1006 /// use std::fmt;
1007 ///
1008 /// struct Length(i32);
1009 ///
1010 /// impl fmt::UpperHex for Length {
1011 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012 ///         let val = self.0;
1013 ///
1014 ///         fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
1015 ///     }
1016 /// }
1017 ///
1018 /// let l = Length(i32::MAX);
1019 ///
1020 /// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
1021 ///
1022 /// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
1023 /// ```
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 pub trait UpperHex {
1026     /// Formats the value using the given formatter.
1027     #[stable(feature = "rust1", since = "1.0.0")]
1028     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1029 }
1030
1031 /// `p` formatting.
1032 ///
1033 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
1034 /// as hexadecimal.
1035 ///
1036 /// For more information on formatters, see [the module-level documentation][module].
1037 ///
1038 /// [module]: ../../std/fmt/index.html
1039 ///
1040 /// # Examples
1041 ///
1042 /// Basic usage with `&i32`:
1043 ///
1044 /// ```
1045 /// let x = &42;
1046 ///
1047 /// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
1048 /// ```
1049 ///
1050 /// Implementing `Pointer` on a type:
1051 ///
1052 /// ```
1053 /// use std::fmt;
1054 ///
1055 /// struct Length(i32);
1056 ///
1057 /// impl fmt::Pointer for Length {
1058 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1059 ///         // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1060 ///
1061 ///         let ptr = self as *const Self;
1062 ///         fmt::Pointer::fmt(&ptr, f)
1063 ///     }
1064 /// }
1065 ///
1066 /// let l = Length(42);
1067 ///
1068 /// println!("l is in memory here: {l:p}");
1069 ///
1070 /// let l_ptr = format!("{l:018p}");
1071 /// assert_eq!(l_ptr.len(), 18);
1072 /// assert_eq!(&l_ptr[..2], "0x");
1073 /// ```
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 #[rustc_diagnostic_item = "Pointer"]
1076 pub trait Pointer {
1077     /// Formats the value using the given formatter.
1078     #[stable(feature = "rust1", since = "1.0.0")]
1079     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1080 }
1081
1082 /// `e` formatting.
1083 ///
1084 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1085 ///
1086 /// For more information on formatters, see [the module-level documentation][module].
1087 ///
1088 /// [module]: ../../std/fmt/index.html
1089 ///
1090 /// # Examples
1091 ///
1092 /// Basic usage with `f64`:
1093 ///
1094 /// ```
1095 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1096 ///
1097 /// assert_eq!(format!("{x:e}"), "4.2e1");
1098 /// ```
1099 ///
1100 /// Implementing `LowerExp` on a type:
1101 ///
1102 /// ```
1103 /// use std::fmt;
1104 ///
1105 /// struct Length(i32);
1106 ///
1107 /// impl fmt::LowerExp for Length {
1108 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 ///         let val = f64::from(self.0);
1110 ///         fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1111 ///     }
1112 /// }
1113 ///
1114 /// let l = Length(100);
1115 ///
1116 /// assert_eq!(
1117 ///     format!("l in scientific notation is: {l:e}"),
1118 ///     "l in scientific notation is: 1e2"
1119 /// );
1120 ///
1121 /// assert_eq!(
1122 ///     format!("l in scientific notation is: {l:05e}"),
1123 ///     "l in scientific notation is: 001e2"
1124 /// );
1125 /// ```
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 pub trait LowerExp {
1128     /// Formats the value using the given formatter.
1129     #[stable(feature = "rust1", since = "1.0.0")]
1130     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1131 }
1132
1133 /// `E` formatting.
1134 ///
1135 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1136 ///
1137 /// For more information on formatters, see [the module-level documentation][module].
1138 ///
1139 /// [module]: ../../std/fmt/index.html
1140 ///
1141 /// # Examples
1142 ///
1143 /// Basic usage with `f64`:
1144 ///
1145 /// ```
1146 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1147 ///
1148 /// assert_eq!(format!("{x:E}"), "4.2E1");
1149 /// ```
1150 ///
1151 /// Implementing `UpperExp` on a type:
1152 ///
1153 /// ```
1154 /// use std::fmt;
1155 ///
1156 /// struct Length(i32);
1157 ///
1158 /// impl fmt::UpperExp for Length {
1159 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1160 ///         let val = f64::from(self.0);
1161 ///         fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1162 ///     }
1163 /// }
1164 ///
1165 /// let l = Length(100);
1166 ///
1167 /// assert_eq!(
1168 ///     format!("l in scientific notation is: {l:E}"),
1169 ///     "l in scientific notation is: 1E2"
1170 /// );
1171 ///
1172 /// assert_eq!(
1173 ///     format!("l in scientific notation is: {l:05E}"),
1174 ///     "l in scientific notation is: 001E2"
1175 /// );
1176 /// ```
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 pub trait UpperExp {
1179     /// Formats the value using the given formatter.
1180     #[stable(feature = "rust1", since = "1.0.0")]
1181     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1182 }
1183
1184 /// The `write` function takes an output stream, and an `Arguments` struct
1185 /// that can be precompiled with the `format_args!` macro.
1186 ///
1187 /// The arguments will be formatted according to the specified format string
1188 /// into the output stream provided.
1189 ///
1190 /// # Examples
1191 ///
1192 /// Basic usage:
1193 ///
1194 /// ```
1195 /// use std::fmt;
1196 ///
1197 /// let mut output = String::new();
1198 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1199 ///     .expect("Error occurred while trying to write in String");
1200 /// assert_eq!(output, "Hello world!");
1201 /// ```
1202 ///
1203 /// Please note that using [`write!`] might be preferable. Example:
1204 ///
1205 /// ```
1206 /// use std::fmt::Write;
1207 ///
1208 /// let mut output = String::new();
1209 /// write!(&mut output, "Hello {}!", "world")
1210 ///     .expect("Error occurred while trying to write in String");
1211 /// assert_eq!(output, "Hello world!");
1212 /// ```
1213 ///
1214 /// [`write!`]: crate::write!
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1217     let mut formatter = Formatter::new(output);
1218     let mut idx = 0;
1219
1220     match args.fmt {
1221         None => {
1222             // We can use default formatting parameters for all arguments.
1223             for (i, arg) in args.args.iter().enumerate() {
1224                 // SAFETY: args.args and args.pieces come from the same Arguments,
1225                 // which guarantees the indexes are always within bounds.
1226                 let piece = unsafe { args.pieces.get_unchecked(i) };
1227                 if !piece.is_empty() {
1228                     formatter.buf.write_str(*piece)?;
1229                 }
1230                 (arg.formatter)(arg.value, &mut formatter)?;
1231                 idx += 1;
1232             }
1233         }
1234         Some(fmt) => {
1235             // Every spec has a corresponding argument that is preceded by
1236             // a string piece.
1237             for (i, arg) in fmt.iter().enumerate() {
1238                 // SAFETY: fmt and args.pieces come from the same Arguments,
1239                 // which guarantees the indexes are always within bounds.
1240                 let piece = unsafe { args.pieces.get_unchecked(i) };
1241                 if !piece.is_empty() {
1242                     formatter.buf.write_str(*piece)?;
1243                 }
1244                 // SAFETY: arg and args.args come from the same Arguments,
1245                 // which guarantees the indexes are always within bounds.
1246                 unsafe { run(&mut formatter, arg, args.args) }?;
1247                 idx += 1;
1248             }
1249         }
1250     }
1251
1252     // There can be only one trailing string piece left.
1253     if let Some(piece) = args.pieces.get(idx) {
1254         formatter.buf.write_str(*piece)?;
1255     }
1256
1257     Ok(())
1258 }
1259
1260 unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1261     fmt.fill = arg.format.fill;
1262     fmt.align = arg.format.align;
1263     fmt.flags = arg.format.flags;
1264     // SAFETY: arg and args come from the same Arguments,
1265     // which guarantees the indexes are always within bounds.
1266     unsafe {
1267         fmt.width = getcount(args, &arg.format.width);
1268         fmt.precision = getcount(args, &arg.format.precision);
1269     }
1270
1271     // Extract the correct argument
1272     debug_assert!(arg.position < args.len());
1273     // SAFETY: arg and args come from the same Arguments,
1274     // which guarantees its index is always within bounds.
1275     let value = unsafe { args.get_unchecked(arg.position) };
1276
1277     // Then actually do some printing
1278     (value.formatter)(value.value, fmt)
1279 }
1280
1281 unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1282     match *cnt {
1283         rt::v1::Count::Is(n) => Some(n),
1284         rt::v1::Count::Implied => None,
1285         rt::v1::Count::Param(i) => {
1286             debug_assert!(i < args.len());
1287             // SAFETY: cnt and args come from the same Arguments,
1288             // which guarantees this index is always within bounds.
1289             unsafe { args.get_unchecked(i).as_usize() }
1290         }
1291     }
1292 }
1293
1294 /// Padding after the end of something. Returned by `Formatter::padding`.
1295 #[must_use = "don't forget to write the post padding"]
1296 pub(crate) struct PostPadding {
1297     fill: char,
1298     padding: usize,
1299 }
1300
1301 impl PostPadding {
1302     fn new(fill: char, padding: usize) -> PostPadding {
1303         PostPadding { fill, padding }
1304     }
1305
1306     /// Write this post padding.
1307     pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1308         for _ in 0..self.padding {
1309             f.buf.write_char(self.fill)?;
1310         }
1311         Ok(())
1312     }
1313 }
1314
1315 impl<'a> Formatter<'a> {
1316     fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1317     where
1318         'b: 'c,
1319         F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1320     {
1321         Formatter {
1322             // We want to change this
1323             buf: wrap(self.buf),
1324
1325             // And preserve these
1326             flags: self.flags,
1327             fill: self.fill,
1328             align: self.align,
1329             width: self.width,
1330             precision: self.precision,
1331         }
1332     }
1333
1334     // Helper methods used for padding and processing formatting arguments that
1335     // all formatting traits can use.
1336
1337     /// Performs the correct padding for an integer which has already been
1338     /// emitted into a str. The str should *not* contain the sign for the
1339     /// integer, that will be added by this method.
1340     ///
1341     /// # Arguments
1342     ///
1343     /// * is_nonnegative - whether the original integer was either positive or zero.
1344     /// * prefix - if the '#' character (Alternate) is provided, this
1345     ///   is the prefix to put in front of the number.
1346     /// * buf - the byte array that the number has been formatted into
1347     ///
1348     /// This function will correctly account for the flags provided as well as
1349     /// the minimum width. It will not take precision into account.
1350     ///
1351     /// # Examples
1352     ///
1353     /// ```
1354     /// use std::fmt;
1355     ///
1356     /// struct Foo { nb: i32 }
1357     ///
1358     /// impl Foo {
1359     ///     fn new(nb: i32) -> Foo {
1360     ///         Foo {
1361     ///             nb,
1362     ///         }
1363     ///     }
1364     /// }
1365     ///
1366     /// impl fmt::Display for Foo {
1367     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1368     ///         // We need to remove "-" from the number output.
1369     ///         let tmp = self.nb.abs().to_string();
1370     ///
1371     ///         formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1372     ///     }
1373     /// }
1374     ///
1375     /// assert_eq!(format!("{}", Foo::new(2)), "2");
1376     /// assert_eq!(format!("{}", Foo::new(-1)), "-1");
1377     /// assert_eq!(format!("{}", Foo::new(0)), "0");
1378     /// assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
1379     /// assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1380     /// ```
1381     #[stable(feature = "rust1", since = "1.0.0")]
1382     pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1383         let mut width = buf.len();
1384
1385         let mut sign = None;
1386         if !is_nonnegative {
1387             sign = Some('-');
1388             width += 1;
1389         } else if self.sign_plus() {
1390             sign = Some('+');
1391             width += 1;
1392         }
1393
1394         let prefix = if self.alternate() {
1395             width += prefix.chars().count();
1396             Some(prefix)
1397         } else {
1398             None
1399         };
1400
1401         // Writes the sign if it exists, and then the prefix if it was requested
1402         #[inline(never)]
1403         fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1404             if let Some(c) = sign {
1405                 f.buf.write_char(c)?;
1406             }
1407             if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1408         }
1409
1410         // The `width` field is more of a `min-width` parameter at this point.
1411         match self.width {
1412             // If there's no minimum length requirements then we can just
1413             // write the bytes.
1414             None => {
1415                 write_prefix(self, sign, prefix)?;
1416                 self.buf.write_str(buf)
1417             }
1418             // Check if we're over the minimum width, if so then we can also
1419             // just write the bytes.
1420             Some(min) if width >= min => {
1421                 write_prefix(self, sign, prefix)?;
1422                 self.buf.write_str(buf)
1423             }
1424             // The sign and prefix goes before the padding if the fill character
1425             // is zero
1426             Some(min) if self.sign_aware_zero_pad() => {
1427                 let old_fill = crate::mem::replace(&mut self.fill, '0');
1428                 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1429                 write_prefix(self, sign, prefix)?;
1430                 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1431                 self.buf.write_str(buf)?;
1432                 post_padding.write(self)?;
1433                 self.fill = old_fill;
1434                 self.align = old_align;
1435                 Ok(())
1436             }
1437             // Otherwise, the sign and prefix goes after the padding
1438             Some(min) => {
1439                 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1440                 write_prefix(self, sign, prefix)?;
1441                 self.buf.write_str(buf)?;
1442                 post_padding.write(self)
1443             }
1444         }
1445     }
1446
1447     /// This function takes a string slice and emits it to the internal buffer
1448     /// after applying the relevant formatting flags specified. The flags
1449     /// recognized for generic strings are:
1450     ///
1451     /// * width - the minimum width of what to emit
1452     /// * fill/align - what to emit and where to emit it if the string
1453     ///                provided needs to be padded
1454     /// * precision - the maximum length to emit, the string is truncated if it
1455     ///               is longer than this length
1456     ///
1457     /// Notably this function ignores the `flag` parameters.
1458     ///
1459     /// # Examples
1460     ///
1461     /// ```
1462     /// use std::fmt;
1463     ///
1464     /// struct Foo;
1465     ///
1466     /// impl fmt::Display for Foo {
1467     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1468     ///         formatter.pad("Foo")
1469     ///     }
1470     /// }
1471     ///
1472     /// assert_eq!(format!("{Foo:<4}"), "Foo ");
1473     /// assert_eq!(format!("{Foo:0>4}"), "0Foo");
1474     /// ```
1475     #[stable(feature = "rust1", since = "1.0.0")]
1476     pub fn pad(&mut self, s: &str) -> Result {
1477         // Make sure there's a fast path up front
1478         if self.width.is_none() && self.precision.is_none() {
1479             return self.buf.write_str(s);
1480         }
1481         // The `precision` field can be interpreted as a `max-width` for the
1482         // string being formatted.
1483         let s = if let Some(max) = self.precision {
1484             // If our string is longer that the precision, then we must have
1485             // truncation. However other flags like `fill`, `width` and `align`
1486             // must act as always.
1487             if let Some((i, _)) = s.char_indices().nth(max) {
1488                 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1489                 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1490                 // `unsafe` and otherwise don't emit any panic-related code
1491                 // here.
1492                 s.get(..i).unwrap_or(s)
1493             } else {
1494                 &s
1495             }
1496         } else {
1497             &s
1498         };
1499         // The `width` field is more of a `min-width` parameter at this point.
1500         match self.width {
1501             // If we're under the maximum length, and there's no minimum length
1502             // requirements, then we can just emit the string
1503             None => self.buf.write_str(s),
1504             Some(width) => {
1505                 let chars_count = s.chars().count();
1506                 // If we're under the maximum width, check if we're over the minimum
1507                 // width, if so it's as easy as just emitting the string.
1508                 if chars_count >= width {
1509                     self.buf.write_str(s)
1510                 }
1511                 // If we're under both the maximum and the minimum width, then fill
1512                 // up the minimum width with the specified string + some alignment.
1513                 else {
1514                     let align = rt::v1::Alignment::Left;
1515                     let post_padding = self.padding(width - chars_count, align)?;
1516                     self.buf.write_str(s)?;
1517                     post_padding.write(self)
1518                 }
1519             }
1520         }
1521     }
1522
1523     /// Write the pre-padding and return the unwritten post-padding. Callers are
1524     /// responsible for ensuring post-padding is written after the thing that is
1525     /// being padded.
1526     pub(crate) fn padding(
1527         &mut self,
1528         padding: usize,
1529         default: rt::v1::Alignment,
1530     ) -> result::Result<PostPadding, Error> {
1531         let align = match self.align {
1532             rt::v1::Alignment::Unknown => default,
1533             _ => self.align,
1534         };
1535
1536         let (pre_pad, post_pad) = match align {
1537             rt::v1::Alignment::Left => (0, padding),
1538             rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1539             rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1540         };
1541
1542         for _ in 0..pre_pad {
1543             self.buf.write_char(self.fill)?;
1544         }
1545
1546         Ok(PostPadding::new(self.fill, post_pad))
1547     }
1548
1549     /// Takes the formatted parts and applies the padding.
1550     /// Assumes that the caller already has rendered the parts with required precision,
1551     /// so that `self.precision` can be ignored.
1552     fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1553         if let Some(mut width) = self.width {
1554             // for the sign-aware zero padding, we render the sign first and
1555             // behave as if we had no sign from the beginning.
1556             let mut formatted = formatted.clone();
1557             let old_fill = self.fill;
1558             let old_align = self.align;
1559             let mut align = old_align;
1560             if self.sign_aware_zero_pad() {
1561                 // a sign always goes first
1562                 let sign = formatted.sign;
1563                 self.buf.write_str(sign)?;
1564
1565                 // remove the sign from the formatted parts
1566                 formatted.sign = "";
1567                 width = width.saturating_sub(sign.len());
1568                 align = rt::v1::Alignment::Right;
1569                 self.fill = '0';
1570                 self.align = rt::v1::Alignment::Right;
1571             }
1572
1573             // remaining parts go through the ordinary padding process.
1574             let len = formatted.len();
1575             let ret = if width <= len {
1576                 // no padding
1577                 self.write_formatted_parts(&formatted)
1578             } else {
1579                 let post_padding = self.padding(width - len, align)?;
1580                 self.write_formatted_parts(&formatted)?;
1581                 post_padding.write(self)
1582             };
1583             self.fill = old_fill;
1584             self.align = old_align;
1585             ret
1586         } else {
1587             // this is the common case and we take a shortcut
1588             self.write_formatted_parts(formatted)
1589         }
1590     }
1591
1592     fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1593         fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1594             // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1595             // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1596             // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1597             // It's also probably safe in practice to use for `numfmt::Part::Copy(buf)`
1598             // since `buf` should be plain ASCII, but it's possible for someone to pass
1599             // in a bad value for `buf` into `numfmt::to_shortest_str` since it is a
1600             // public function.
1601             // FIXME: Determine whether this could result in UB.
1602             buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1603         }
1604
1605         if !formatted.sign.is_empty() {
1606             self.buf.write_str(formatted.sign)?;
1607         }
1608         for part in formatted.parts {
1609             match *part {
1610                 numfmt::Part::Zero(mut nzeroes) => {
1611                     const ZEROES: &str = // 64 zeroes
1612                         "0000000000000000000000000000000000000000000000000000000000000000";
1613                     while nzeroes > ZEROES.len() {
1614                         self.buf.write_str(ZEROES)?;
1615                         nzeroes -= ZEROES.len();
1616                     }
1617                     if nzeroes > 0 {
1618                         self.buf.write_str(&ZEROES[..nzeroes])?;
1619                     }
1620                 }
1621                 numfmt::Part::Num(mut v) => {
1622                     let mut s = [0; 5];
1623                     let len = part.len();
1624                     for c in s[..len].iter_mut().rev() {
1625                         *c = b'0' + (v % 10) as u8;
1626                         v /= 10;
1627                     }
1628                     write_bytes(self.buf, &s[..len])?;
1629                 }
1630                 numfmt::Part::Copy(buf) => {
1631                     write_bytes(self.buf, buf)?;
1632                 }
1633             }
1634         }
1635         Ok(())
1636     }
1637
1638     /// Writes some data to the underlying buffer contained within this
1639     /// formatter.
1640     ///
1641     /// # Examples
1642     ///
1643     /// ```
1644     /// use std::fmt;
1645     ///
1646     /// struct Foo;
1647     ///
1648     /// impl fmt::Display for Foo {
1649     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1650     ///         formatter.write_str("Foo")
1651     ///         // This is equivalent to:
1652     ///         // write!(formatter, "Foo")
1653     ///     }
1654     /// }
1655     ///
1656     /// assert_eq!(format!("{Foo}"), "Foo");
1657     /// assert_eq!(format!("{Foo:0>8}"), "Foo");
1658     /// ```
1659     #[stable(feature = "rust1", since = "1.0.0")]
1660     pub fn write_str(&mut self, data: &str) -> Result {
1661         self.buf.write_str(data)
1662     }
1663
1664     /// Writes some formatted information into this instance.
1665     ///
1666     /// # Examples
1667     ///
1668     /// ```
1669     /// use std::fmt;
1670     ///
1671     /// struct Foo(i32);
1672     ///
1673     /// impl fmt::Display for Foo {
1674     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1675     ///         formatter.write_fmt(format_args!("Foo {}", self.0))
1676     ///     }
1677     /// }
1678     ///
1679     /// assert_eq!(format!("{}", Foo(-1)), "Foo -1");
1680     /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
1681     /// ```
1682     #[stable(feature = "rust1", since = "1.0.0")]
1683     pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1684         write(self.buf, fmt)
1685     }
1686
1687     /// Flags for formatting
1688     #[must_use]
1689     #[stable(feature = "rust1", since = "1.0.0")]
1690     #[deprecated(
1691         since = "1.24.0",
1692         note = "use the `sign_plus`, `sign_minus`, `alternate`, \
1693                 or `sign_aware_zero_pad` methods instead"
1694     )]
1695     pub fn flags(&self) -> u32 {
1696         self.flags
1697     }
1698
1699     /// Character used as 'fill' whenever there is alignment.
1700     ///
1701     /// # Examples
1702     ///
1703     /// ```
1704     /// use std::fmt;
1705     ///
1706     /// struct Foo;
1707     ///
1708     /// impl fmt::Display for Foo {
1709     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1710     ///         let c = formatter.fill();
1711     ///         if let Some(width) = formatter.width() {
1712     ///             for _ in 0..width {
1713     ///                 write!(formatter, "{c}")?;
1714     ///             }
1715     ///             Ok(())
1716     ///         } else {
1717     ///             write!(formatter, "{c}")
1718     ///         }
1719     ///     }
1720     /// }
1721     ///
1722     /// // We set alignment to the right with ">".
1723     /// assert_eq!(format!("{Foo:G>3}"), "GGG");
1724     /// assert_eq!(format!("{Foo:t>6}"), "tttttt");
1725     /// ```
1726     #[must_use]
1727     #[stable(feature = "fmt_flags", since = "1.5.0")]
1728     pub fn fill(&self) -> char {
1729         self.fill
1730     }
1731
1732     /// Flag indicating what form of alignment was requested.
1733     ///
1734     /// # Examples
1735     ///
1736     /// ```
1737     /// extern crate core;
1738     ///
1739     /// use std::fmt::{self, Alignment};
1740     ///
1741     /// struct Foo;
1742     ///
1743     /// impl fmt::Display for Foo {
1744     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1745     ///         let s = if let Some(s) = formatter.align() {
1746     ///             match s {
1747     ///                 Alignment::Left    => "left",
1748     ///                 Alignment::Right   => "right",
1749     ///                 Alignment::Center  => "center",
1750     ///             }
1751     ///         } else {
1752     ///             "into the void"
1753     ///         };
1754     ///         write!(formatter, "{s}")
1755     ///     }
1756     /// }
1757     ///
1758     /// assert_eq!(format!("{Foo:<}"), "left");
1759     /// assert_eq!(format!("{Foo:>}"), "right");
1760     /// assert_eq!(format!("{Foo:^}"), "center");
1761     /// assert_eq!(format!("{Foo}"), "into the void");
1762     /// ```
1763     #[must_use]
1764     #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1765     pub fn align(&self) -> Option<Alignment> {
1766         match self.align {
1767             rt::v1::Alignment::Left => Some(Alignment::Left),
1768             rt::v1::Alignment::Right => Some(Alignment::Right),
1769             rt::v1::Alignment::Center => Some(Alignment::Center),
1770             rt::v1::Alignment::Unknown => None,
1771         }
1772     }
1773
1774     /// Optionally specified integer width that the output should be.
1775     ///
1776     /// # Examples
1777     ///
1778     /// ```
1779     /// use std::fmt;
1780     ///
1781     /// struct Foo(i32);
1782     ///
1783     /// impl fmt::Display for Foo {
1784     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1785     ///         if let Some(width) = formatter.width() {
1786     ///             // If we received a width, we use it
1787     ///             write!(formatter, "{:width$}", format!("Foo({})", self.0), width = width)
1788     ///         } else {
1789     ///             // Otherwise we do nothing special
1790     ///             write!(formatter, "Foo({})", self.0)
1791     ///         }
1792     ///     }
1793     /// }
1794     ///
1795     /// assert_eq!(format!("{:10}", Foo(23)), "Foo(23)   ");
1796     /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
1797     /// ```
1798     #[must_use]
1799     #[stable(feature = "fmt_flags", since = "1.5.0")]
1800     pub fn width(&self) -> Option<usize> {
1801         self.width
1802     }
1803
1804     /// Optionally specified precision for numeric types. Alternatively, the
1805     /// maximum width for string types.
1806     ///
1807     /// # Examples
1808     ///
1809     /// ```
1810     /// use std::fmt;
1811     ///
1812     /// struct Foo(f32);
1813     ///
1814     /// impl fmt::Display for Foo {
1815     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1816     ///         if let Some(precision) = formatter.precision() {
1817     ///             // If we received a precision, we use it.
1818     ///             write!(formatter, "Foo({1:.*})", precision, self.0)
1819     ///         } else {
1820     ///             // Otherwise we default to 2.
1821     ///             write!(formatter, "Foo({:.2})", self.0)
1822     ///         }
1823     ///     }
1824     /// }
1825     ///
1826     /// assert_eq!(format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1827     /// assert_eq!(format!("{}", Foo(23.2)), "Foo(23.20)");
1828     /// ```
1829     #[must_use]
1830     #[stable(feature = "fmt_flags", since = "1.5.0")]
1831     pub fn precision(&self) -> Option<usize> {
1832         self.precision
1833     }
1834
1835     /// Determines if the `+` flag was specified.
1836     ///
1837     /// # Examples
1838     ///
1839     /// ```
1840     /// use std::fmt;
1841     ///
1842     /// struct Foo(i32);
1843     ///
1844     /// impl fmt::Display for Foo {
1845     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1846     ///         if formatter.sign_plus() {
1847     ///             write!(formatter,
1848     ///                    "Foo({}{})",
1849     ///                    if self.0 < 0 { '-' } else { '+' },
1850     ///                    self.0.abs())
1851     ///         } else {
1852     ///             write!(formatter, "Foo({})", self.0)
1853     ///         }
1854     ///     }
1855     /// }
1856     ///
1857     /// assert_eq!(format!("{:+}", Foo(23)), "Foo(+23)");
1858     /// assert_eq!(format!("{:+}", Foo(-23)), "Foo(-23)");
1859     /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
1860     /// ```
1861     #[must_use]
1862     #[stable(feature = "fmt_flags", since = "1.5.0")]
1863     pub fn sign_plus(&self) -> bool {
1864         self.flags & (1 << FlagV1::SignPlus as u32) != 0
1865     }
1866
1867     /// Determines if the `-` flag was specified.
1868     ///
1869     /// # Examples
1870     ///
1871     /// ```
1872     /// use std::fmt;
1873     ///
1874     /// struct Foo(i32);
1875     ///
1876     /// impl fmt::Display for Foo {
1877     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1878     ///         if formatter.sign_minus() {
1879     ///             // You want a minus sign? Have one!
1880     ///             write!(formatter, "-Foo({})", self.0)
1881     ///         } else {
1882     ///             write!(formatter, "Foo({})", self.0)
1883     ///         }
1884     ///     }
1885     /// }
1886     ///
1887     /// assert_eq!(format!("{:-}", Foo(23)), "-Foo(23)");
1888     /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
1889     /// ```
1890     #[must_use]
1891     #[stable(feature = "fmt_flags", since = "1.5.0")]
1892     pub fn sign_minus(&self) -> bool {
1893         self.flags & (1 << FlagV1::SignMinus as u32) != 0
1894     }
1895
1896     /// Determines if the `#` flag was specified.
1897     ///
1898     /// # Examples
1899     ///
1900     /// ```
1901     /// use std::fmt;
1902     ///
1903     /// struct Foo(i32);
1904     ///
1905     /// impl fmt::Display for Foo {
1906     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1907     ///         if formatter.alternate() {
1908     ///             write!(formatter, "Foo({})", self.0)
1909     ///         } else {
1910     ///             write!(formatter, "{}", self.0)
1911     ///         }
1912     ///     }
1913     /// }
1914     ///
1915     /// assert_eq!(format!("{:#}", Foo(23)), "Foo(23)");
1916     /// assert_eq!(format!("{}", Foo(23)), "23");
1917     /// ```
1918     #[must_use]
1919     #[stable(feature = "fmt_flags", since = "1.5.0")]
1920     pub fn alternate(&self) -> bool {
1921         self.flags & (1 << FlagV1::Alternate as u32) != 0
1922     }
1923
1924     /// Determines if the `0` flag was specified.
1925     ///
1926     /// # Examples
1927     ///
1928     /// ```
1929     /// use std::fmt;
1930     ///
1931     /// struct Foo(i32);
1932     ///
1933     /// impl fmt::Display for Foo {
1934     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1935     ///         assert!(formatter.sign_aware_zero_pad());
1936     ///         assert_eq!(formatter.width(), Some(4));
1937     ///         // We ignore the formatter's options.
1938     ///         write!(formatter, "{}", self.0)
1939     ///     }
1940     /// }
1941     ///
1942     /// assert_eq!(format!("{:04}", Foo(23)), "23");
1943     /// ```
1944     #[must_use]
1945     #[stable(feature = "fmt_flags", since = "1.5.0")]
1946     pub fn sign_aware_zero_pad(&self) -> bool {
1947         self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1948     }
1949
1950     // FIXME: Decide what public API we want for these two flags.
1951     // https://github.com/rust-lang/rust/issues/48584
1952     fn debug_lower_hex(&self) -> bool {
1953         self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1954     }
1955
1956     fn debug_upper_hex(&self) -> bool {
1957         self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1958     }
1959
1960     /// Creates a [`DebugStruct`] builder designed to assist with creation of
1961     /// [`fmt::Debug`] implementations for structs.
1962     ///
1963     /// [`fmt::Debug`]: self::Debug
1964     ///
1965     /// # Examples
1966     ///
1967     /// ```rust
1968     /// use std::fmt;
1969     /// use std::net::Ipv4Addr;
1970     ///
1971     /// struct Foo {
1972     ///     bar: i32,
1973     ///     baz: String,
1974     ///     addr: Ipv4Addr,
1975     /// }
1976     ///
1977     /// impl fmt::Debug for Foo {
1978     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1979     ///         fmt.debug_struct("Foo")
1980     ///             .field("bar", &self.bar)
1981     ///             .field("baz", &self.baz)
1982     ///             .field("addr", &format_args!("{}", self.addr))
1983     ///             .finish()
1984     ///     }
1985     /// }
1986     ///
1987     /// assert_eq!(
1988     ///     "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1989     ///     format!("{:?}", Foo {
1990     ///         bar: 10,
1991     ///         baz: "Hello World".to_string(),
1992     ///         addr: Ipv4Addr::new(127, 0, 0, 1),
1993     ///     })
1994     /// );
1995     /// ```
1996     #[stable(feature = "debug_builders", since = "1.2.0")]
1997     pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1998         builders::debug_struct_new(self, name)
1999     }
2000
2001     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2002     /// `debug_struct_fields_finish` is more general, but this is faster for 1 field.
2003     #[doc(hidden)]
2004     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2005     pub fn debug_struct_field1_finish<'b>(
2006         &'b mut self,
2007         name: &str,
2008         name1: &str,
2009         value1: &dyn Debug,
2010     ) -> Result {
2011         let mut builder = builders::debug_struct_new(self, name);
2012         builder.field(name1, value1);
2013         builder.finish()
2014     }
2015
2016     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2017     /// `debug_struct_fields_finish` is more general, but this is faster for 2 fields.
2018     #[doc(hidden)]
2019     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2020     pub fn debug_struct_field2_finish<'b>(
2021         &'b mut self,
2022         name: &str,
2023         name1: &str,
2024         value1: &dyn Debug,
2025         name2: &str,
2026         value2: &dyn Debug,
2027     ) -> Result {
2028         let mut builder = builders::debug_struct_new(self, name);
2029         builder.field(name1, value1);
2030         builder.field(name2, value2);
2031         builder.finish()
2032     }
2033
2034     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2035     /// `debug_struct_fields_finish` is more general, but this is faster for 3 fields.
2036     #[doc(hidden)]
2037     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2038     pub fn debug_struct_field3_finish<'b>(
2039         &'b mut self,
2040         name: &str,
2041         name1: &str,
2042         value1: &dyn Debug,
2043         name2: &str,
2044         value2: &dyn Debug,
2045         name3: &str,
2046         value3: &dyn Debug,
2047     ) -> Result {
2048         let mut builder = builders::debug_struct_new(self, name);
2049         builder.field(name1, value1);
2050         builder.field(name2, value2);
2051         builder.field(name3, value3);
2052         builder.finish()
2053     }
2054
2055     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2056     /// `debug_struct_fields_finish` is more general, but this is faster for 4 fields.
2057     #[doc(hidden)]
2058     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2059     pub fn debug_struct_field4_finish<'b>(
2060         &'b mut self,
2061         name: &str,
2062         name1: &str,
2063         value1: &dyn Debug,
2064         name2: &str,
2065         value2: &dyn Debug,
2066         name3: &str,
2067         value3: &dyn Debug,
2068         name4: &str,
2069         value4: &dyn Debug,
2070     ) -> Result {
2071         let mut builder = builders::debug_struct_new(self, name);
2072         builder.field(name1, value1);
2073         builder.field(name2, value2);
2074         builder.field(name3, value3);
2075         builder.field(name4, value4);
2076         builder.finish()
2077     }
2078
2079     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2080     /// `debug_struct_fields_finish` is more general, but this is faster for 5 fields.
2081     #[doc(hidden)]
2082     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2083     pub fn debug_struct_field5_finish<'b>(
2084         &'b mut self,
2085         name: &str,
2086         name1: &str,
2087         value1: &dyn Debug,
2088         name2: &str,
2089         value2: &dyn Debug,
2090         name3: &str,
2091         value3: &dyn Debug,
2092         name4: &str,
2093         value4: &dyn Debug,
2094         name5: &str,
2095         value5: &dyn Debug,
2096     ) -> Result {
2097         let mut builder = builders::debug_struct_new(self, name);
2098         builder.field(name1, value1);
2099         builder.field(name2, value2);
2100         builder.field(name3, value3);
2101         builder.field(name4, value4);
2102         builder.field(name5, value5);
2103         builder.finish()
2104     }
2105
2106     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2107     /// For the cases not covered by `debug_struct_field[12345]_finish`.
2108     #[doc(hidden)]
2109     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2110     pub fn debug_struct_fields_finish<'b>(
2111         &'b mut self,
2112         name: &str,
2113         names: &[&str],
2114         values: &[&dyn Debug],
2115     ) -> Result {
2116         assert_eq!(names.len(), values.len());
2117         let mut builder = builders::debug_struct_new(self, name);
2118         for (name, value) in iter::zip(names, values) {
2119             builder.field(name, value);
2120         }
2121         builder.finish()
2122     }
2123
2124     /// Creates a `DebugTuple` builder designed to assist with creation of
2125     /// `fmt::Debug` implementations for tuple structs.
2126     ///
2127     /// # Examples
2128     ///
2129     /// ```rust
2130     /// use std::fmt;
2131     /// use std::marker::PhantomData;
2132     ///
2133     /// struct Foo<T>(i32, String, PhantomData<T>);
2134     ///
2135     /// impl<T> fmt::Debug for Foo<T> {
2136     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2137     ///         fmt.debug_tuple("Foo")
2138     ///             .field(&self.0)
2139     ///             .field(&self.1)
2140     ///             .field(&format_args!("_"))
2141     ///             .finish()
2142     ///     }
2143     /// }
2144     ///
2145     /// assert_eq!(
2146     ///     "Foo(10, \"Hello\", _)",
2147     ///     format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
2148     /// );
2149     /// ```
2150     #[stable(feature = "debug_builders", since = "1.2.0")]
2151     pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
2152         builders::debug_tuple_new(self, name)
2153     }
2154
2155     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2156     /// `debug_tuple_fields_finish` is more general, but this is faster for 1 field.
2157     #[doc(hidden)]
2158     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2159     pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result {
2160         let mut builder = builders::debug_tuple_new(self, name);
2161         builder.field(value1);
2162         builder.finish()
2163     }
2164
2165     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2166     /// `debug_tuple_fields_finish` is more general, but this is faster for 2 fields.
2167     #[doc(hidden)]
2168     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2169     pub fn debug_tuple_field2_finish<'b>(
2170         &'b mut self,
2171         name: &str,
2172         value1: &dyn Debug,
2173         value2: &dyn Debug,
2174     ) -> Result {
2175         let mut builder = builders::debug_tuple_new(self, name);
2176         builder.field(value1);
2177         builder.field(value2);
2178         builder.finish()
2179     }
2180
2181     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2182     /// `debug_tuple_fields_finish` is more general, but this is faster for 3 fields.
2183     #[doc(hidden)]
2184     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2185     pub fn debug_tuple_field3_finish<'b>(
2186         &'b mut self,
2187         name: &str,
2188         value1: &dyn Debug,
2189         value2: &dyn Debug,
2190         value3: &dyn Debug,
2191     ) -> Result {
2192         let mut builder = builders::debug_tuple_new(self, name);
2193         builder.field(value1);
2194         builder.field(value2);
2195         builder.field(value3);
2196         builder.finish()
2197     }
2198
2199     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2200     /// `debug_tuple_fields_finish` is more general, but this is faster for 4 fields.
2201     #[doc(hidden)]
2202     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2203     pub fn debug_tuple_field4_finish<'b>(
2204         &'b mut self,
2205         name: &str,
2206         value1: &dyn Debug,
2207         value2: &dyn Debug,
2208         value3: &dyn Debug,
2209         value4: &dyn Debug,
2210     ) -> Result {
2211         let mut builder = builders::debug_tuple_new(self, name);
2212         builder.field(value1);
2213         builder.field(value2);
2214         builder.field(value3);
2215         builder.field(value4);
2216         builder.finish()
2217     }
2218
2219     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2220     /// `debug_tuple_fields_finish` is more general, but this is faster for 5 fields.
2221     #[doc(hidden)]
2222     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2223     pub fn debug_tuple_field5_finish<'b>(
2224         &'b mut self,
2225         name: &str,
2226         value1: &dyn Debug,
2227         value2: &dyn Debug,
2228         value3: &dyn Debug,
2229         value4: &dyn Debug,
2230         value5: &dyn Debug,
2231     ) -> Result {
2232         let mut builder = builders::debug_tuple_new(self, name);
2233         builder.field(value1);
2234         builder.field(value2);
2235         builder.field(value3);
2236         builder.field(value4);
2237         builder.field(value5);
2238         builder.finish()
2239     }
2240
2241     /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2242     /// For the cases not covered by `debug_tuple_field[12345]_finish`.
2243     #[doc(hidden)]
2244     #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2245     pub fn debug_tuple_fields_finish<'b>(
2246         &'b mut self,
2247         name: &str,
2248         values: &[&dyn Debug],
2249     ) -> Result {
2250         let mut builder = builders::debug_tuple_new(self, name);
2251         for value in values {
2252             builder.field(value);
2253         }
2254         builder.finish()
2255     }
2256
2257     /// Creates a `DebugList` builder designed to assist with creation of
2258     /// `fmt::Debug` implementations for list-like structures.
2259     ///
2260     /// # Examples
2261     ///
2262     /// ```rust
2263     /// use std::fmt;
2264     ///
2265     /// struct Foo(Vec<i32>);
2266     ///
2267     /// impl fmt::Debug for Foo {
2268     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2269     ///         fmt.debug_list().entries(self.0.iter()).finish()
2270     ///     }
2271     /// }
2272     ///
2273     /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2274     /// ```
2275     #[stable(feature = "debug_builders", since = "1.2.0")]
2276     pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2277         builders::debug_list_new(self)
2278     }
2279
2280     /// Creates a `DebugSet` builder designed to assist with creation of
2281     /// `fmt::Debug` implementations for set-like structures.
2282     ///
2283     /// # Examples
2284     ///
2285     /// ```rust
2286     /// use std::fmt;
2287     ///
2288     /// struct Foo(Vec<i32>);
2289     ///
2290     /// impl fmt::Debug for Foo {
2291     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2292     ///         fmt.debug_set().entries(self.0.iter()).finish()
2293     ///     }
2294     /// }
2295     ///
2296     /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2297     /// ```
2298     ///
2299     /// [`format_args!`]: crate::format_args
2300     ///
2301     /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2302     /// to build a list of match arms:
2303     ///
2304     /// ```rust
2305     /// use std::fmt;
2306     ///
2307     /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
2308     /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
2309     ///
2310     /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2311     /// where
2312     ///     L: 'a + fmt::Debug, R: 'a + fmt::Debug
2313     /// {
2314     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2315     ///         L::fmt(&(self.0).0, fmt)?;
2316     ///         fmt.write_str(" => ")?;
2317     ///         R::fmt(&(self.0).1, fmt)
2318     ///     }
2319     /// }
2320     ///
2321     /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2322     /// where
2323     ///     K: 'a + fmt::Debug, V: 'a + fmt::Debug
2324     /// {
2325     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2326     ///         fmt.debug_set()
2327     ///         .entries(self.0.iter().map(Arm))
2328     ///         .entry(&Arm(&(format_args!("_"), &self.1)))
2329     ///         .finish()
2330     ///     }
2331     /// }
2332     /// ```
2333     #[stable(feature = "debug_builders", since = "1.2.0")]
2334     pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2335         builders::debug_set_new(self)
2336     }
2337
2338     /// Creates a `DebugMap` builder designed to assist with creation of
2339     /// `fmt::Debug` implementations for map-like structures.
2340     ///
2341     /// # Examples
2342     ///
2343     /// ```rust
2344     /// use std::fmt;
2345     ///
2346     /// struct Foo(Vec<(String, i32)>);
2347     ///
2348     /// impl fmt::Debug for Foo {
2349     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2350     ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2351     ///     }
2352     /// }
2353     ///
2354     /// assert_eq!(
2355     ///     format!("{:?}",  Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2356     ///     r#"{"A": 10, "B": 11}"#
2357     ///  );
2358     /// ```
2359     #[stable(feature = "debug_builders", since = "1.2.0")]
2360     pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2361         builders::debug_map_new(self)
2362     }
2363 }
2364
2365 #[stable(since = "1.2.0", feature = "formatter_write")]
2366 impl Write for Formatter<'_> {
2367     fn write_str(&mut self, s: &str) -> Result {
2368         self.buf.write_str(s)
2369     }
2370
2371     fn write_char(&mut self, c: char) -> Result {
2372         self.buf.write_char(c)
2373     }
2374
2375     fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2376         write(self.buf, args)
2377     }
2378 }
2379
2380 #[stable(feature = "rust1", since = "1.0.0")]
2381 impl Display for Error {
2382     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2383         Display::fmt("an error occurred when formatting an argument", f)
2384     }
2385 }
2386
2387 // Implementations of the core formatting traits
2388
2389 macro_rules! fmt_refs {
2390     ($($tr:ident),*) => {
2391         $(
2392         #[stable(feature = "rust1", since = "1.0.0")]
2393         impl<T: ?Sized + $tr> $tr for &T {
2394             fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2395         }
2396         #[stable(feature = "rust1", since = "1.0.0")]
2397         impl<T: ?Sized + $tr> $tr for &mut T {
2398             fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2399         }
2400         )*
2401     }
2402 }
2403
2404 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2405
2406 #[unstable(feature = "never_type", issue = "35121")]
2407 impl Debug for ! {
2408     fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2409         *self
2410     }
2411 }
2412
2413 #[unstable(feature = "never_type", issue = "35121")]
2414 impl Display for ! {
2415     fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2416         *self
2417     }
2418 }
2419
2420 #[stable(feature = "rust1", since = "1.0.0")]
2421 impl Debug for bool {
2422     #[inline]
2423     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2424         Display::fmt(self, f)
2425     }
2426 }
2427
2428 #[stable(feature = "rust1", since = "1.0.0")]
2429 impl Display for bool {
2430     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2431         Display::fmt(if *self { "true" } else { "false" }, f)
2432     }
2433 }
2434
2435 #[stable(feature = "rust1", since = "1.0.0")]
2436 impl Debug for str {
2437     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2438         f.write_char('"')?;
2439         let mut from = 0;
2440         for (i, c) in self.char_indices() {
2441             let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2442                 escape_grapheme_extended: true,
2443                 escape_single_quote: false,
2444                 escape_double_quote: true,
2445             });
2446             // If char needs escaping, flush backlog so far and write, else skip
2447             if esc.len() != 1 {
2448                 f.write_str(&self[from..i])?;
2449                 for c in esc {
2450                     f.write_char(c)?;
2451                 }
2452                 from = i + c.len_utf8();
2453             }
2454         }
2455         f.write_str(&self[from..])?;
2456         f.write_char('"')
2457     }
2458 }
2459
2460 #[stable(feature = "rust1", since = "1.0.0")]
2461 impl Display for str {
2462     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2463         f.pad(self)
2464     }
2465 }
2466
2467 #[stable(feature = "rust1", since = "1.0.0")]
2468 impl Debug for char {
2469     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2470         f.write_char('\'')?;
2471         for c in self.escape_debug_ext(EscapeDebugExtArgs {
2472             escape_grapheme_extended: true,
2473             escape_single_quote: true,
2474             escape_double_quote: false,
2475         }) {
2476             f.write_char(c)?
2477         }
2478         f.write_char('\'')
2479     }
2480 }
2481
2482 #[stable(feature = "rust1", since = "1.0.0")]
2483 impl Display for char {
2484     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2485         if f.width.is_none() && f.precision.is_none() {
2486             f.write_char(*self)
2487         } else {
2488             f.pad(self.encode_utf8(&mut [0; 4]))
2489         }
2490     }
2491 }
2492
2493 #[stable(feature = "rust1", since = "1.0.0")]
2494 impl<T: ?Sized> Pointer for *const T {
2495     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2496         // Cast is needed here because `.expose_addr()` requires `T: Sized`.
2497         pointer_fmt_inner((*self as *const ()).expose_addr(), f)
2498     }
2499 }
2500
2501 /// Since the formatting will be identical for all pointer types, use a non-monomorphized
2502 /// implementation for the actual formatting to reduce the amount of codegen work needed.
2503 ///
2504 /// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
2505 /// `fn(...) -> ...` without using [problematic] "Oxford Casts".
2506 ///
2507 /// [problematic]: https://github.com/rust-lang/rust/issues/95489
2508 pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
2509     let old_width = f.width;
2510     let old_flags = f.flags;
2511
2512     // The alternate flag is already treated by LowerHex as being special-
2513     // it denotes whether to prefix with 0x. We use it to work out whether
2514     // or not to zero extend, and then unconditionally set it to get the
2515     // prefix.
2516     if f.alternate() {
2517         f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2518
2519         if f.width.is_none() {
2520             f.width = Some((usize::BITS / 4) as usize + 2);
2521         }
2522     }
2523     f.flags |= 1 << (FlagV1::Alternate as u32);
2524
2525     let ret = LowerHex::fmt(&ptr_addr, f);
2526
2527     f.width = old_width;
2528     f.flags = old_flags;
2529
2530     ret
2531 }
2532
2533 #[stable(feature = "rust1", since = "1.0.0")]
2534 impl<T: ?Sized> Pointer for *mut T {
2535     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2536         Pointer::fmt(&(*self as *const T), f)
2537     }
2538 }
2539
2540 #[stable(feature = "rust1", since = "1.0.0")]
2541 impl<T: ?Sized> Pointer for &T {
2542     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2543         Pointer::fmt(&(*self as *const T), f)
2544     }
2545 }
2546
2547 #[stable(feature = "rust1", since = "1.0.0")]
2548 impl<T: ?Sized> Pointer for &mut T {
2549     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2550         Pointer::fmt(&(&**self as *const T), f)
2551     }
2552 }
2553
2554 // Implementation of Display/Debug for various core types
2555
2556 #[stable(feature = "rust1", since = "1.0.0")]
2557 impl<T: ?Sized> Debug for *const T {
2558     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2559         Pointer::fmt(self, f)
2560     }
2561 }
2562 #[stable(feature = "rust1", since = "1.0.0")]
2563 impl<T: ?Sized> Debug for *mut T {
2564     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2565         Pointer::fmt(self, f)
2566     }
2567 }
2568
2569 macro_rules! peel {
2570     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2571 }
2572
2573 macro_rules! tuple {
2574     () => ();
2575     ( $($name:ident,)+ ) => (
2576         maybe_tuple_doc! {
2577             $($name)+ @
2578             #[stable(feature = "rust1", since = "1.0.0")]
2579             impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2580                 #[allow(non_snake_case, unused_assignments)]
2581                 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2582                     let mut builder = f.debug_tuple("");
2583                     let ($(ref $name,)+) = *self;
2584                     $(
2585                         builder.field(&$name);
2586                     )+
2587
2588                     builder.finish()
2589                 }
2590             }
2591         }
2592         peel! { $($name,)+ }
2593     )
2594 }
2595
2596 macro_rules! maybe_tuple_doc {
2597     ($a:ident @ #[$meta:meta] $item:item) => {
2598         #[doc(fake_variadic)]
2599         #[doc = "This trait is implemented for tuples up to twelve items long."]
2600         #[$meta]
2601         $item
2602     };
2603     ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
2604         #[doc(hidden)]
2605         #[$meta]
2606         $item
2607     };
2608 }
2609
2610 macro_rules! last_type {
2611     ($a:ident,) => { $a };
2612     ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2613 }
2614
2615 tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
2616
2617 #[stable(feature = "rust1", since = "1.0.0")]
2618 impl<T: Debug> Debug for [T] {
2619     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2620         f.debug_list().entries(self.iter()).finish()
2621     }
2622 }
2623
2624 #[stable(feature = "rust1", since = "1.0.0")]
2625 impl Debug for () {
2626     #[inline]
2627     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2628         f.pad("()")
2629     }
2630 }
2631 #[stable(feature = "rust1", since = "1.0.0")]
2632 impl<T: ?Sized> Debug for PhantomData<T> {
2633     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2634         write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
2635     }
2636 }
2637
2638 #[stable(feature = "rust1", since = "1.0.0")]
2639 impl<T: Copy + Debug> Debug for Cell<T> {
2640     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2641         f.debug_struct("Cell").field("value", &self.get()).finish()
2642     }
2643 }
2644
2645 #[stable(feature = "rust1", since = "1.0.0")]
2646 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2647     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2648         match self.try_borrow() {
2649             Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2650             Err(_) => {
2651                 // The RefCell is mutably borrowed so we can't look at its value
2652                 // here. Show a placeholder instead.
2653                 struct BorrowedPlaceholder;
2654
2655                 impl Debug for BorrowedPlaceholder {
2656                     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2657                         f.write_str("<borrowed>")
2658                     }
2659                 }
2660
2661                 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2662             }
2663         }
2664     }
2665 }
2666
2667 #[stable(feature = "rust1", since = "1.0.0")]
2668 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2669     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2670         Debug::fmt(&**self, f)
2671     }
2672 }
2673
2674 #[stable(feature = "rust1", since = "1.0.0")]
2675 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2676     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2677         Debug::fmt(&*(self.deref()), f)
2678     }
2679 }
2680
2681 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2682 impl<T: ?Sized> Debug for UnsafeCell<T> {
2683     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2684         f.debug_struct("UnsafeCell").finish_non_exhaustive()
2685     }
2686 }
2687
2688 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2689 impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
2690     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2691         f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
2692     }
2693 }
2694
2695 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2696 // it's a lot easier than creating all of the rt::Piece structures here.
2697 // There are also tests in the alloc crate, for those that need allocations.