Skip to main content

core/fmt/
mod.rs

1//! Utilities for formatting and printing strings.
2
3#![stable(feature = "rust1", since = "1.0.0")]
4
5use crate::cell::{Cell, Ref, RefCell, RefMut, SyncUnsafeCell, UnsafeCell};
6use crate::char::EscapeDebugExtArgs;
7use crate::hint::assert_unchecked;
8use crate::marker::{PhantomData, PointeeSized};
9use crate::num::imp::fmt as numfmt;
10use crate::ops::Deref;
11use crate::ptr::NonNull;
12use crate::{iter, mem, result, str};
13
14mod builders;
15#[cfg(not(no_fp_fmt_parse))]
16mod float;
17#[cfg(no_fp_fmt_parse)]
18mod nofloat;
19mod num;
20mod num_buffer;
21mod rt;
22
23#[stable(feature = "fmt_flags_align", since = "1.28.0")]
24#[rustc_diagnostic_item = "Alignment"]
25/// Possible alignments returned by `Formatter::align`
26#[derive(Copy, Clone, Debug, PartialEq, Eq)]
27pub enum Alignment {
28    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
29    /// Indication that contents should be left-aligned.
30    Left,
31    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
32    /// Indication that contents should be right-aligned.
33    Right,
34    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
35    /// Indication that contents should be center-aligned.
36    Center,
37}
38
39#[unstable(feature = "int_format_into", issue = "138215")]
40pub use num_buffer::{NumBuffer, NumBufferTrait};
41
42#[stable(feature = "debug_builders", since = "1.2.0")]
43pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
44#[stable(feature = "fmt_from_fn", since = "1.93.0")]
45pub use self::builders::{FromFn, from_fn};
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")]
72pub 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. This is because, despite the existence of this error,
78/// string formatting is considered an infallible operation.
79/// `fmt()` implementors should not return this `Error` unless they received it from their
80/// [`Formatter`]. The only time your code should create a new instance of this
81/// error is when implementing `fmt::Write`, in order to cancel the formatting operation when
82/// writing to the underlying stream fails.
83///
84/// Any extra information must be arranged to be transmitted through some other means,
85/// such as storing it in a field to be consulted after the formatting operation has been
86/// cancelled. (For example, this is how [`std::io::Write::write_fmt()`] propagates IO errors
87/// during writing.)
88///
89/// This type, `fmt::Error`, should not be
90/// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
91/// have in scope.
92///
93/// [`std::io::Error`]: ../../std/io/struct.Error.html
94/// [`std::io::Write::write_fmt()`]: ../../std/io/trait.Write.html#method.write_fmt
95/// [`std::error::Error`]: ../../std/error/trait.Error.html
96///
97/// # Examples
98///
99/// ```rust
100/// use std::fmt::{self, write};
101///
102/// let mut output = String::new();
103/// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
104///     panic!("An error occurred");
105/// }
106/// ```
107#[stable(feature = "rust1", since = "1.0.0")]
108#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
109pub struct Error;
110
111/// A trait for writing or formatting into Unicode-accepting buffers or streams.
112///
113/// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
114/// want to accept Unicode and you don't need flushing, you should implement this trait;
115/// otherwise you should implement [`std::io::Write`].
116///
117/// [`std::io::Write`]: ../../std/io/trait.Write.html
118/// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
119#[stable(feature = "rust1", since = "1.0.0")]
120#[rustc_diagnostic_item = "FmtWrite"]
121pub trait Write {
122    /// Writes a string slice into this writer, returning whether the write
123    /// succeeded.
124    ///
125    /// This method can only succeed if the entire string slice was successfully
126    /// written, and this method will not return until all data has been
127    /// written or an error occurs.
128    ///
129    /// # Errors
130    ///
131    /// This function will return an instance of [`std::fmt::Error`][Error] on error.
132    ///
133    /// The purpose of that error is to abort the formatting operation when the underlying
134    /// destination encounters some error preventing it from accepting more text;
135    /// in particular, it does not communicate any information about *what* error occurred.
136    /// It should generally be propagated rather than handled, at least when implementing
137    /// formatting traits.
138    ///
139    /// # Examples
140    ///
141    /// ```
142    /// use std::fmt::{Error, Write};
143    ///
144    /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
145    ///     f.write_str(s)
146    /// }
147    ///
148    /// let mut buf = String::new();
149    /// writer(&mut buf, "hola")?;
150    /// assert_eq!(&buf, "hola");
151    /// # std::fmt::Result::Ok(())
152    /// ```
153    #[stable(feature = "rust1", since = "1.0.0")]
154    fn write_str(&mut self, s: &str) -> Result;
155
156    /// Writes a [`char`] into this writer, returning whether the write succeeded.
157    ///
158    /// A single [`char`] may be encoded as more than one byte.
159    /// This method can only succeed if the entire byte sequence was successfully
160    /// written, and this method will not return until all data has been
161    /// written or an error occurs.
162    ///
163    /// # Errors
164    ///
165    /// This function will return an instance of [`Error`] on error.
166    ///
167    /// # Examples
168    ///
169    /// ```
170    /// use std::fmt::{Error, Write};
171    ///
172    /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
173    ///     f.write_char(c)
174    /// }
175    ///
176    /// let mut buf = String::new();
177    /// writer(&mut buf, 'a')?;
178    /// writer(&mut buf, 'b')?;
179    /// assert_eq!(&buf, "ab");
180    /// # std::fmt::Result::Ok(())
181    /// ```
182    #[stable(feature = "fmt_write_char", since = "1.1.0")]
183    fn write_char(&mut self, c: char) -> Result {
184        self.write_str(c.encode_utf8(&mut [0; char::MAX_LEN_UTF8]))
185    }
186
187    /// Glue for usage of the [`write!`] macro with implementors of this trait.
188    ///
189    /// This method should generally not be invoked manually, but rather through
190    /// the [`write!`] macro itself.
191    ///
192    /// # Errors
193    ///
194    /// This function will return an instance of [`Error`] on error. Please see
195    /// [write_str](Write::write_str) for details.
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// use std::fmt::{Error, Write};
201    ///
202    /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
203    ///     f.write_fmt(format_args!("{s}"))
204    /// }
205    ///
206    /// let mut buf = String::new();
207    /// writer(&mut buf, "world")?;
208    /// assert_eq!(&buf, "world");
209    /// # std::fmt::Result::Ok(())
210    /// ```
211    #[stable(feature = "rust1", since = "1.0.0")]
212    fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
213        // We use a specialization for `Sized` types to avoid an indirection
214        // through `&mut self`
215        trait SpecWriteFmt {
216            fn spec_write_fmt(self, args: Arguments<'_>) -> Result;
217        }
218
219        impl<W: Write + ?Sized> SpecWriteFmt for &mut W {
220            #[inline]
221            default fn spec_write_fmt(mut self, args: Arguments<'_>) -> Result {
222                if let Some(s) = args.as_statically_known_str() {
223                    self.write_str(s)
224                } else {
225                    write(&mut self, args)
226                }
227            }
228        }
229
230        impl<W: Write> SpecWriteFmt for &mut W {
231            #[inline]
232            fn spec_write_fmt(self, args: Arguments<'_>) -> Result {
233                if let Some(s) = args.as_statically_known_str() {
234                    self.write_str(s)
235                } else {
236                    write(self, args)
237                }
238            }
239        }
240
241        self.spec_write_fmt(args)
242    }
243}
244
245#[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
246impl<W: Write + ?Sized> Write for &mut W {
247    fn write_str(&mut self, s: &str) -> Result {
248        (**self).write_str(s)
249    }
250
251    fn write_char(&mut self, c: char) -> Result {
252        (**self).write_char(c)
253    }
254
255    fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
256        (**self).write_fmt(args)
257    }
258}
259
260/// The signedness of a [`Formatter`] (or of a [`FormattingOptions`]).
261#[derive(Copy, Clone, Debug, PartialEq, Eq)]
262#[unstable(feature = "formatting_options", issue = "118117")]
263pub enum Sign {
264    /// Represents the `+` flag.
265    Plus,
266    /// Represents the `-` flag.
267    Minus,
268}
269
270/// Specifies whether the [`Debug`] trait should use lower-/upper-case
271/// hexadecimal or normal integers.
272#[derive(Copy, Clone, Debug, PartialEq, Eq)]
273#[unstable(feature = "formatting_options", issue = "118117")]
274pub enum DebugAsHex {
275    /// Use lower-case hexadecimal integers for the `Debug` trait (like [the `x?` type](../../std/fmt/index.html#formatting-traits)).
276    Lower,
277    /// Use upper-case hexadecimal integers for the `Debug` trait (like [the `X?` type](../../std/fmt/index.html#formatting-traits)).
278    Upper,
279}
280
281/// Options for formatting.
282///
283/// `FormattingOptions` is a [`Formatter`] without an attached [`Write`] trait.
284/// It is mainly used to construct `Formatter` instances.
285#[derive(Copy, Clone, Debug, PartialEq, Eq)]
286#[unstable(feature = "formatting_options", issue = "118117")]
287pub struct FormattingOptions {
288    /// Flags, with the following bit fields:
289    ///
290    /// ```text
291    ///   31  30  29  28  27  26  25  24  23  22  21  20                              0
292    /// ┌───┬───────┬───┬───┬───┬───┬───┬───┬───┬───┬──────────────────────────────────┐
293    /// │ 0 │ align │ p │ w │ X?│ x?│'0'│ # │ - │ + │               fill               │
294    /// └───┴───────┴───┴───┴───┴───┴───┴───┴───┴───┴──────────────────────────────────┘
295    ///   │     │     │   │  └─┬───────────────────┘ └─┬──────────────────────────────┘
296    ///   │     │     │   │    │                       └─ The fill character (21 bits char).
297    ///   │     │     │   │    └─ The debug upper/lower hex, zero pad, alternate, and plus/minus flags.
298    ///   │     │     │   └─ Whether a width is set. (The value is stored separately.)
299    ///   │     │     └─ Whether a precision is set. (The value is stored separately.)
300    ///   │     ├─ 0: Align left. (<)
301    ///   │     ├─ 1: Align right. (>)
302    ///   │     ├─ 2: Align center. (^)
303    ///   │     └─ 3: Alignment not set. (default)
304    ///   └─ Always zero.
305    /// ```
306    // Note: This could use a pattern type with range 0x0000_0000..=0x7dd0ffff.
307    // It's unclear if that's useful, though.
308    flags: u32,
309    /// Width if width flag (bit 27) above is set. Otherwise, always 0.
310    width: u16,
311    /// Precision if precision flag (bit 28) above is set. Otherwise, always 0.
312    precision: u16,
313}
314
315// This needs to match with compiler/rustc_ast_lowering/src/format.rs.
316mod flags {
317    pub(super) const SIGN_PLUS_FLAG: u32 = 1 << 21;
318    pub(super) const SIGN_MINUS_FLAG: u32 = 1 << 22;
319    pub(super) const ALTERNATE_FLAG: u32 = 1 << 23;
320    pub(super) const SIGN_AWARE_ZERO_PAD_FLAG: u32 = 1 << 24;
321    pub(super) const DEBUG_LOWER_HEX_FLAG: u32 = 1 << 25;
322    pub(super) const DEBUG_UPPER_HEX_FLAG: u32 = 1 << 26;
323    pub(super) const WIDTH_FLAG: u32 = 1 << 27;
324    pub(super) const PRECISION_FLAG: u32 = 1 << 28;
325    pub(super) const ALIGN_BITS: u32 = 0b11 << 29;
326    pub(super) const ALIGN_LEFT: u32 = 0 << 29;
327    pub(super) const ALIGN_RIGHT: u32 = 1 << 29;
328    pub(super) const ALIGN_CENTER: u32 = 2 << 29;
329    pub(super) const ALIGN_UNKNOWN: u32 = 3 << 29;
330}
331
332impl FormattingOptions {
333    /// Construct a new `FormatterBuilder` with the supplied `Write` trait
334    /// object for output that is equivalent to the `{}` formatting
335    /// specifier:
336    ///
337    /// - no flags,
338    /// - filled with spaces,
339    /// - no alignment,
340    /// - no width,
341    /// - no precision, and
342    /// - no [`DebugAsHex`] output mode.
343    #[unstable(feature = "formatting_options", issue = "118117")]
344    pub const fn new() -> Self {
345        Self { flags: ' ' as u32 | flags::ALIGN_UNKNOWN, width: 0, precision: 0 }
346    }
347
348    /// Sets or removes the sign (the `+` or the `-` flag).
349    ///
350    /// - `+`: This is intended for numeric types and indicates that the sign
351    ///   should always be printed. By default only the negative sign of signed
352    ///   values is printed, and the sign of positive or unsigned values is
353    ///   omitted. This flag indicates that the correct sign (+ or -) should
354    ///   always be printed.
355    /// - `-`: Currently not used
356    #[unstable(feature = "formatting_options", issue = "118117")]
357    pub const fn sign(&mut self, sign: Option<Sign>) -> &mut Self {
358        let sign = match sign {
359            None => 0,
360            Some(Sign::Plus) => flags::SIGN_PLUS_FLAG,
361            Some(Sign::Minus) => flags::SIGN_MINUS_FLAG,
362        };
363        self.flags = self.flags & !(flags::SIGN_PLUS_FLAG | flags::SIGN_MINUS_FLAG) | sign;
364        self
365    }
366    /// Sets or unsets the `0` flag.
367    ///
368    /// This is used to indicate for integer formats that the padding to width should both be done with a 0 character as well as be sign-aware
369    #[unstable(feature = "formatting_options", issue = "118117")]
370    pub const fn sign_aware_zero_pad(&mut self, sign_aware_zero_pad: bool) -> &mut Self {
371        if sign_aware_zero_pad {
372            self.flags |= flags::SIGN_AWARE_ZERO_PAD_FLAG;
373        } else {
374            self.flags &= !flags::SIGN_AWARE_ZERO_PAD_FLAG;
375        }
376        self
377    }
378    /// Sets or unsets the `#` flag.
379    ///
380    /// This flag indicates that the "alternate" form of printing should be
381    /// used. The alternate forms are:
382    /// - [`Debug`] : pretty-print the [`Debug`] formatting (adds linebreaks and indentation)
383    /// - [`LowerHex`] as well as [`UpperHex`] - precedes the argument with a `0x`
384    /// - [`Octal`] - precedes the argument with a `0o`
385    /// - [`Binary`] - precedes the argument with a `0b`
386    #[unstable(feature = "formatting_options", issue = "118117")]
387    pub const fn alternate(&mut self, alternate: bool) -> &mut Self {
388        if alternate {
389            self.flags |= flags::ALTERNATE_FLAG;
390        } else {
391            self.flags &= !flags::ALTERNATE_FLAG;
392        }
393        self
394    }
395    /// Sets the fill character.
396    ///
397    /// The optional fill character and alignment is provided normally in
398    /// conjunction with the width parameter. This indicates that if the value
399    /// being formatted is smaller than width some extra characters will be
400    /// printed around it.
401    #[unstable(feature = "formatting_options", issue = "118117")]
402    pub const fn fill(&mut self, fill: char) -> &mut Self {
403        self.flags = self.flags & (u32::MAX << 21) | fill as u32;
404        self
405    }
406    /// Sets or removes the alignment.
407    ///
408    /// The alignment specifies how the value being formatted should be
409    /// positioned if it is smaller than the width of the formatter.
410    #[unstable(feature = "formatting_options", issue = "118117")]
411    pub const fn align(&mut self, align: Option<Alignment>) -> &mut Self {
412        let align: u32 = match align {
413            Some(Alignment::Left) => flags::ALIGN_LEFT,
414            Some(Alignment::Right) => flags::ALIGN_RIGHT,
415            Some(Alignment::Center) => flags::ALIGN_CENTER,
416            None => flags::ALIGN_UNKNOWN,
417        };
418        self.flags = self.flags & !flags::ALIGN_BITS | align;
419        self
420    }
421    /// Sets or removes the width.
422    ///
423    /// This is a parameter for the “minimum width” that the format should take
424    /// up. If the value’s string does not fill up this many characters, then
425    /// the padding specified by [`FormattingOptions::fill`]/[`FormattingOptions::align`]
426    /// will be used to take up the required space.
427    #[unstable(feature = "formatting_options", issue = "118117")]
428    pub const fn width(&mut self, width: Option<u16>) -> &mut Self {
429        if let Some(width) = width {
430            self.flags |= flags::WIDTH_FLAG;
431            self.width = width;
432        } else {
433            self.flags &= !flags::WIDTH_FLAG;
434            self.width = 0;
435        }
436        self
437    }
438    /// Sets or removes the precision.
439    ///
440    /// - For non-numeric types, this can be considered a “maximum width”. If
441    ///   the resulting string is longer than this width, then it is truncated
442    ///   down to this many characters and that truncated value is emitted with
443    ///   proper fill, alignment and width if those parameters are set.
444    /// - For integral types, this is ignored.
445    /// - For floating-point types, this indicates how many digits after the
446    /// decimal point should be printed.
447    #[unstable(feature = "formatting_options", issue = "118117")]
448    pub const fn precision(&mut self, precision: Option<u16>) -> &mut Self {
449        if let Some(precision) = precision {
450            self.flags |= flags::PRECISION_FLAG;
451            self.precision = precision;
452        } else {
453            self.flags &= !flags::PRECISION_FLAG;
454            self.precision = 0;
455        }
456        self
457    }
458    /// Specifies whether the [`Debug`] trait should use lower-/upper-case
459    /// hexadecimal or normal integers
460    #[unstable(feature = "formatting_options", issue = "118117")]
461    pub const fn debug_as_hex(&mut self, debug_as_hex: Option<DebugAsHex>) -> &mut Self {
462        let debug_as_hex = match debug_as_hex {
463            None => 0,
464            Some(DebugAsHex::Lower) => flags::DEBUG_LOWER_HEX_FLAG,
465            Some(DebugAsHex::Upper) => flags::DEBUG_UPPER_HEX_FLAG,
466        };
467        self.flags = self.flags & !(flags::DEBUG_LOWER_HEX_FLAG | flags::DEBUG_UPPER_HEX_FLAG)
468            | debug_as_hex;
469        self
470    }
471
472    /// Returns the current sign (the `+` or the `-` flag).
473    #[unstable(feature = "formatting_options", issue = "118117")]
474    pub const fn get_sign(&self) -> Option<Sign> {
475        if self.flags & flags::SIGN_PLUS_FLAG != 0 {
476            Some(Sign::Plus)
477        } else if self.flags & flags::SIGN_MINUS_FLAG != 0 {
478            Some(Sign::Minus)
479        } else {
480            None
481        }
482    }
483    /// Returns the current `0` flag.
484    #[unstable(feature = "formatting_options", issue = "118117")]
485    pub const fn get_sign_aware_zero_pad(&self) -> bool {
486        self.flags & flags::SIGN_AWARE_ZERO_PAD_FLAG != 0
487    }
488    /// Returns the current `#` flag.
489    #[unstable(feature = "formatting_options", issue = "118117")]
490    pub const fn get_alternate(&self) -> bool {
491        self.flags & flags::ALTERNATE_FLAG != 0
492    }
493    /// Returns the current fill character.
494    #[unstable(feature = "formatting_options", issue = "118117")]
495    pub const fn get_fill(&self) -> char {
496        // SAFETY: We only ever put a valid `char` in the lower 21 bits of the flags field.
497        unsafe { char::from_u32_unchecked(self.flags & 0x1FFFFF) }
498    }
499    /// Returns the current alignment.
500    #[unstable(feature = "formatting_options", issue = "118117")]
501    pub const fn get_align(&self) -> Option<Alignment> {
502        match self.flags & flags::ALIGN_BITS {
503            flags::ALIGN_LEFT => Some(Alignment::Left),
504            flags::ALIGN_RIGHT => Some(Alignment::Right),
505            flags::ALIGN_CENTER => Some(Alignment::Center),
506            _ => None,
507        }
508    }
509    /// Returns the current width.
510    #[unstable(feature = "formatting_options", issue = "118117")]
511    pub const fn get_width(&self) -> Option<u16> {
512        if self.flags & flags::WIDTH_FLAG != 0 { Some(self.width) } else { None }
513    }
514    /// Returns the current precision.
515    #[unstable(feature = "formatting_options", issue = "118117")]
516    pub const fn get_precision(&self) -> Option<u16> {
517        if self.flags & flags::PRECISION_FLAG != 0 { Some(self.precision) } else { None }
518    }
519    /// Returns the current precision.
520    #[unstable(feature = "formatting_options", issue = "118117")]
521    pub const fn get_debug_as_hex(&self) -> Option<DebugAsHex> {
522        if self.flags & flags::DEBUG_LOWER_HEX_FLAG != 0 {
523            Some(DebugAsHex::Lower)
524        } else if self.flags & flags::DEBUG_UPPER_HEX_FLAG != 0 {
525            Some(DebugAsHex::Upper)
526        } else {
527            None
528        }
529    }
530
531    /// Creates a [`Formatter`] that writes its output to the given [`Write`] trait.
532    ///
533    /// You may alternatively use [`Formatter::new()`].
534    #[unstable(feature = "formatting_options", issue = "118117")]
535    pub const fn create_formatter<'a>(self, write: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
536        Formatter { options: self, buf: write }
537    }
538}
539
540#[unstable(feature = "formatting_options", issue = "118117")]
541impl Default for FormattingOptions {
542    /// Same as [`FormattingOptions::new()`].
543    fn default() -> Self {
544        // The `#[derive(Default)]` implementation would set `fill` to `\0` instead of space.
545        Self::new()
546    }
547}
548
549/// Configuration for formatting.
550///
551/// A `Formatter` represents various options related to formatting. Users do not
552/// construct `Formatter`s directly; a mutable reference to one is passed to
553/// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
554///
555/// To interact with a `Formatter`, you'll call various methods to change the
556/// various options related to formatting. For examples, please see the
557/// documentation of the methods defined on `Formatter` below.
558#[allow(missing_debug_implementations)]
559#[stable(feature = "rust1", since = "1.0.0")]
560#[rustc_diagnostic_item = "Formatter"]
561pub struct Formatter<'a> {
562    options: FormattingOptions,
563
564    buf: &'a mut (dyn Write + 'a),
565}
566
567impl<'a> Formatter<'a> {
568    /// Creates a new formatter with given [`FormattingOptions`].
569    ///
570    /// If `write` is a reference to a formatter, it is recommended to use
571    /// [`Formatter::with_options`] instead as this can borrow the underlying
572    /// `write`, thereby bypassing one layer of indirection.
573    ///
574    /// You may alternatively use [`FormattingOptions::create_formatter()`].
575    #[unstable(feature = "formatting_options", issue = "118117")]
576    pub const fn new(write: &'a mut (dyn Write + 'a), options: FormattingOptions) -> Self {
577        Formatter { options, buf: write }
578    }
579
580    /// Creates a new formatter based on this one with given [`FormattingOptions`].
581    #[unstable(feature = "formatting_options", issue = "118117")]
582    pub const fn with_options<'b>(&'b mut self, options: FormattingOptions) -> Formatter<'b> {
583        Formatter { options, buf: self.buf }
584    }
585}
586
587/// This structure represents a safely precompiled version of a format string
588/// and its arguments. This cannot be generated at runtime because it cannot
589/// safely be done, so no constructors are given and the fields are private
590/// to prevent modification.
591///
592/// The [`format_args!`] macro will safely create an instance of this structure.
593/// The macro validates the format string at compile-time so usage of the
594/// [`write()`] and [`format()`] functions can be safely performed.
595///
596/// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
597/// and `Display` contexts as seen below. The example also shows that `Debug`
598/// and `Display` format to the same thing: the interpolated format string
599/// in `format_args!`.
600///
601/// ```rust
602/// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
603/// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
604/// assert_eq!("1 foo 2", display);
605/// assert_eq!(display, debug);
606/// ```
607///
608/// [`format()`]: ../../std/fmt/fn.format.html
609//
610// Internal representation:
611//
612// fmt::Arguments is represented in one of two ways:
613//
614// 1) String literal representation (e.g. format_args!("hello"))
615//             ┌────────────────────────────────┐
616//   template: │           *const u8            │ ─▷ "hello"
617//             ├──────────────────────────────┬─┤
618//   args:     │             len              │1│ (lowest bit is 1; field contains `len << 1 | 1`)
619//             └──────────────────────────────┴─┘
620//   In this representation, there are no placeholders and `fmt::Arguments::as_str()` returns Some.
621//   The pointer points to the start of a static `str`. The length is given by `args as usize >> 1`.
622//   (The length of a `&str` is isize::MAX at most, so it always fits in a usize minus one bit.)
623//
624//   `fmt::Arguments::from_str()` constructs this representation from a `&'static str`.
625//
626// 2) Placeholders representation (e.g. format_args!("hello {name}\n"))
627//             ┌────────────────────────────────┐
628//   template: │           *const u8            │ ─▷ b"\x06hello \xC0\x01\n\x00"
629//             ├────────────────────────────────┤
630//   args:     │     &'a [Argument<'a>; _]     0│ (lower bit is 0 due to alignment of Argument type)
631//             └────────────────────────────────┘
632//   In this representation, the template is a byte sequence encoding both the literal string pieces
633//   and the placeholders (including their options/flags).
634//
635//   The `args` pointer points to an array of `fmt::Argument<'a>` values, of sufficient length to
636//   match the placeholders in the template.
637//
638//   `fmt::Arguments::new()` constructs this representation from a template byte slice and a slice
639//   of arguments. This function is unsafe, as the template is assumed to be valid and the args
640//   slice is assumed to have elements matching the template.
641//
642//   The template byte sequence is the concatenation of parts of the following types:
643//
644//   - Literal string piece:
645//         Pieces that must be formatted verbatim (e.g. "hello " and "\n" in "hello {name}\n")
646//         appear literally in the template byte sequence, prefixed by their length.
647//
648//         For pieces of up to 127 bytes, these are  represented as a single byte containing the
649//         length followed directly by the bytes of the string:
650//         ┌───┬────────────────────────────┐
651//         │len│    `len` bytes (utf-8)     │ (e.g. b"\x06hello ")
652//         └───┴────────────────────────────┘
653//
654//         For larger pieces up to u16::MAX bytes, these are  represented as a 0x80 followed by
655//         their length in 16-bit little endian, followed by the bytes of the string:
656//         ┌────┬─────────┬───────────────────────────┐
657//         │0x80│   len   │   `len` bytes (utf-8)     │ (e.g. b"\x80\x00\x01hello … ")
658//         └────┴─────────┴───────────────────────────┘
659//
660//         Longer pieces are split into multiple pieces of max u16::MAX bytes (at utf-8 boundaries).
661//
662//   - Placeholder:
663//         Placeholders (e.g. `{name}` in "hello {name}") are represented as a byte with the highest
664//         two bits set, followed by zero or more fields depending on the flags in the first byte:
665//         ┌──────────┬┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┬┄┄┄┄┄┄┄┄┄┄┄┬┄┄┄┄┄┄┄┄┄┄┄┬┄┄┄┄┄┄┄┄┄┄┄┐
666//         │0b11______│       flags       ┊   width   ┊ precision ┊ arg_index ┊ (e.g. b"\xC2\x05\0")
667//         └────││││││┴┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┴┄┄┄┄┄┄┄┄┄┄┄┴┄┄┄┄┄┄┄┄┄┄┄┴┄┄┄┄┄┄┄┄┄┄┄┘
668//              ││││││        32 bit          16 bit      16 bit      16 bit
669//              │││││└─ flags present
670//              ││││└─ width present
671//              │││└─ precision present
672//              ││└─ arg_index present
673//              │└─ width indirect
674//              └─ precision indirect
675//
676//         All fields other than the first byte are optional and only present when their
677//         corresponding flag is set in the first byte.
678//
679//         So, a fully default placeholder without any options is just a single byte:
680//         ┌──────────┐
681//         │0b11000000│ (b"\xC0")
682//         └──────────┘
683//
684//         The fields are stored as little endian.
685//
686//         The `flags` fields corresponds to the `flags` field of `FormattingOptions`.
687//         See doc comment of `FormattingOptions::flags` for details.
688//
689//         The `width` and `precision` fields correspond to their respective fields in
690//         `FormattingOptions`. However, if their "indirect" flag is set, the field contains the
691//         index in the `args` array where the dynamic width or precision is stored, rather than the
692//         value directly.
693//
694//         The `arg_index` field is the index into the `args` array for the argument to be
695//         formatted.
696//
697//         If omitted, the flags, width and precision of the default FormattingOptions::new() are
698//         used.
699//
700//         If the `arg_index` is omitted, the next argument in the `args` array is used (starting
701//         at 0).
702//
703//   - End:
704//         A single zero byte marks the end of the template:
705//         ┌───┐
706//         │ 0 │ ("\0")
707//         └───┘
708//
709//         (Note that a zero byte may also occur naturally as part of the string pieces or flags,
710//         width, precision and arg_index fields above. That is, the template byte sequence ends
711//         with a 0 byte, but isn't terminated by the first 0 byte.)
712//
713#[lang = "format_arguments"]
714#[stable(feature = "rust1", since = "1.0.0")]
715#[derive(Copy, Clone)]
716pub struct Arguments<'a> {
717    template: NonNull<u8>,
718    args: NonNull<rt::Argument<'a>>,
719}
720
721/// Used by the format_args!() macro to create a fmt::Arguments object.
722#[doc(hidden)]
723#[rustc_diagnostic_item = "FmtArgumentsNew"]
724#[unstable(feature = "fmt_internals", issue = "none")]
725impl<'a> Arguments<'a> {
726    // SAFETY: The caller must ensure that the provided template and args encode a valid
727    // fmt::Arguments, as documented above.
728    #[inline]
729    pub unsafe fn new<const N: usize, const M: usize>(
730        template: &'a [u8; N],
731        args: &'a [rt::Argument<'a>; M],
732    ) -> Arguments<'a> {
733        // SAFETY: Responsibility of the caller.
734        unsafe { Arguments { template: mem::transmute(template), args: mem::transmute(args) } }
735    }
736
737    // Same as `from_str`, but not const.
738    // Used by format_args!() expansion when arguments are inlined,
739    // e.g. format_args!("{}", 123), which is not allowed in const.
740    #[inline]
741    pub fn from_str_nonconst(s: &'static str) -> Arguments<'a> {
742        Arguments::from_str(s)
743    }
744}
745
746#[doc(hidden)]
747#[unstable(feature = "fmt_internals", issue = "none")]
748impl<'a> Arguments<'a> {
749    /// Estimates the length of the formatted text.
750    ///
751    /// This is intended to be used for setting initial `String` capacity
752    /// when using `format!`. Note: this is neither the lower nor upper bound.
753    #[inline]
754    pub fn estimated_capacity(&self) -> usize {
755        if let Some(s) = self.as_str() {
756            return s.len();
757        }
758        // Iterate over the template, counting the length of literal pieces.
759        let mut length = 0usize;
760        let mut starts_with_placeholder = false;
761        let mut template = self.template;
762        loop {
763            // SAFETY: We can assume the template is valid.
764            unsafe {
765                let n = template.read();
766                template = template.add(1);
767                if n == 0 {
768                    // End of template.
769                    break;
770                } else if n < 128 {
771                    // Short literal string piece.
772                    length += n as usize;
773                    template = template.add(n as usize);
774                } else if n == 128 {
775                    // Long literal string piece.
776                    let len = usize::from(u16::from_le_bytes(template.cast_array().read()));
777                    length += len;
778                    template = template.add(2 + len);
779                } else {
780                    assert_unchecked(n >= 0xC0);
781                    // Placeholder piece.
782                    if length == 0 {
783                        starts_with_placeholder = true;
784                    }
785                    // Skip remainder of placeholder:
786                    let skip = (n & 1 != 0) as usize * 4 // flags (32 bit)
787                        + (n & 2 != 0) as usize * 2  // width     (16 bit)
788                        + (n & 4 != 0) as usize * 2  // precision (16 bit)
789                        + (n & 8 != 0) as usize * 2; // arg_index (16 bit)
790                    template = template.add(skip as usize);
791                }
792            }
793        }
794
795        if starts_with_placeholder && length < 16 {
796            // If the format string starts with a placeholder,
797            // don't preallocate anything, unless length
798            // of literal pieces is significant.
799            0
800        } else {
801            // There are some placeholders, so any additional push
802            // will reallocate the string. To avoid that,
803            // we're "pre-doubling" the capacity here.
804            length.wrapping_mul(2)
805        }
806    }
807}
808
809impl<'a> Arguments<'a> {
810    /// Create a `fmt::Arguments` object for a single static string.
811    ///
812    /// Formatting this `fmt::Arguments` will just produce the string as-is.
813    #[inline]
814    #[unstable(feature = "fmt_arguments_from_str", issue = "148905")]
815    pub const fn from_str(s: &'static str) -> Arguments<'a> {
816        // SAFETY: This is the "static str" representation of fmt::Arguments; see above.
817        unsafe {
818            Arguments {
819                template: mem::transmute(s.as_ptr()),
820                args: mem::transmute(s.len() << 1 | 1),
821            }
822        }
823    }
824
825    /// Gets the formatted string, if it has no arguments to be formatted at runtime.
826    ///
827    /// This can be used to avoid allocations in some cases.
828    ///
829    /// # Guarantees
830    ///
831    /// For `format_args!("just a literal")`, this function is guaranteed to
832    /// return `Some("just a literal")`.
833    ///
834    /// For most cases with placeholders, this function will return `None`.
835    ///
836    /// However, the compiler may perform optimizations that can cause this
837    /// function to return `Some(_)` even if the format string contains
838    /// placeholders. For example, `format_args!("Hello, {}!", "world")` may be
839    /// optimized to `format_args!("Hello, world!")`, such that `as_str()`
840    /// returns `Some("Hello, world!")`.
841    ///
842    /// The behavior for anything but the trivial case (without placeholders)
843    /// is not guaranteed, and should not be relied upon for anything other
844    /// than optimization.
845    ///
846    /// # Examples
847    ///
848    /// ```rust
849    /// use std::fmt::Arguments;
850    ///
851    /// fn write_str(_: &str) { /* ... */ }
852    ///
853    /// fn write_fmt(args: &Arguments<'_>) {
854    ///     if let Some(s) = args.as_str() {
855    ///         write_str(s)
856    ///     } else {
857    ///         write_str(&args.to_string());
858    ///     }
859    /// }
860    /// ```
861    ///
862    /// ```rust
863    /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
864    /// assert_eq!(format_args!("").as_str(), Some(""));
865    /// assert_eq!(format_args!("{:?}", std::env::current_dir()).as_str(), None);
866    /// ```
867    #[stable(feature = "fmt_as_str", since = "1.52.0")]
868    #[rustc_const_stable(feature = "const_arguments_as_str", since = "1.84.0")]
869    #[must_use]
870    #[inline]
871    pub const fn as_str(&self) -> Option<&'static str> {
872        // SAFETY: During const eval, `self.args` must have come from a usize,
873        // not a pointer, because that's the only way to create a fmt::Arguments in const.
874        // (I.e. only fmt::Arguments::from_str is const, fmt::Arguments::new is not.)
875        //
876        // Outside const eval, transmuting a pointer to a usize is fine.
877        let bits: usize = unsafe { mem::transmute(self.args) };
878        if bits & 1 == 1 {
879            // SAFETY: This fmt::Arguments stores a &'static str. See encoding documentation above.
880            Some(unsafe {
881                str::from_utf8_unchecked(crate::slice::from_raw_parts(
882                    self.template.as_ptr(),
883                    bits >> 1,
884                ))
885            })
886        } else {
887            None
888        }
889    }
890
891    /// Same as [`Arguments::as_str`], but will only return `Some(s)` if it can be determined at compile time.
892    #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
893    #[must_use]
894    #[inline]
895    #[doc(hidden)]
896    pub fn as_statically_known_str(&self) -> Option<&'static str> {
897        let s = self.as_str();
898        if core::intrinsics::is_val_statically_known(s.is_some()) { s } else { None }
899    }
900}
901
902// Manually implementing these results in better error messages.
903#[stable(feature = "rust1", since = "1.0.0")]
904impl !Send for Arguments<'_> {}
905#[stable(feature = "rust1", since = "1.0.0")]
906impl !Sync for Arguments<'_> {}
907
908#[stable(feature = "rust1", since = "1.0.0")]
909impl Debug for Arguments<'_> {
910    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
911        Display::fmt(self, fmt)
912    }
913}
914
915#[stable(feature = "rust1", since = "1.0.0")]
916impl Display for Arguments<'_> {
917    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
918        write(fmt.buf, *self)
919    }
920}
921
922/// `?` formatting.
923///
924/// `Debug` should format the output in a programmer-facing, debugging context.
925///
926/// Generally speaking, you should just `derive` a `Debug` implementation.
927///
928/// When used with the alternate format specifier `#?`, the output is pretty-printed.
929///
930/// For more information on formatters, see [the module-level documentation][module].
931///
932/// [module]: ../../std/fmt/index.html
933///
934/// This trait can be used with `#[derive]` if all fields implement `Debug`. When
935/// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
936/// comma-separated list of each field's name and `Debug` value, then `}`. For
937/// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
938/// `Debug` values of the fields, then `)`.
939///
940/// # Stability
941///
942/// Derived `Debug` formats are not stable, and so may change with future Rust
943/// versions. Additionally, `Debug` implementations of types provided by the
944/// standard library (`std`, `core`, `alloc`, etc.) are not stable, and
945/// may also change with future Rust versions.
946///
947/// # Examples
948///
949/// Deriving an implementation:
950///
951/// ```
952/// #[derive(Debug)]
953/// struct Point {
954///     x: i32,
955///     y: i32,
956/// }
957///
958/// let origin = Point { x: 0, y: 0 };
959///
960/// assert_eq!(
961///     format!("The origin is: {origin:?}"),
962///     "The origin is: Point { x: 0, y: 0 }",
963/// );
964/// ```
965///
966/// Manually implementing:
967///
968/// ```
969/// use std::fmt;
970///
971/// struct Point {
972///     x: i32,
973///     y: i32,
974/// }
975///
976/// impl fmt::Debug for Point {
977///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
978///         f.debug_struct("Point")
979///          .field("x", &self.x)
980///          .field("y", &self.y)
981///          .finish()
982///     }
983/// }
984///
985/// let origin = Point { x: 0, y: 0 };
986///
987/// assert_eq!(
988///     format!("The origin is: {origin:?}"),
989///     "The origin is: Point { x: 0, y: 0 }",
990/// );
991/// ```
992///
993/// There are a number of helper methods on the [`Formatter`] struct to help you with manual
994/// implementations, such as [`debug_struct`].
995///
996/// [`debug_struct`]: Formatter::debug_struct
997///
998/// Types that do not wish to use the standard suite of debug representations
999/// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
1000/// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
1001/// manually writing an arbitrary representation to the `Formatter`.
1002///
1003/// ```
1004/// # use std::fmt;
1005/// # struct Point {
1006/// #     x: i32,
1007/// #     y: i32,
1008/// # }
1009/// #
1010/// impl fmt::Debug for Point {
1011///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012///         write!(f, "Point [{} {}]", self.x, self.y)
1013///     }
1014/// }
1015/// ```
1016///
1017/// `Debug` implementations using either `derive` or the debug builder API
1018/// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
1019///
1020/// Pretty-printing with `#?`:
1021///
1022/// ```
1023/// #[derive(Debug)]
1024/// struct Point {
1025///     x: i32,
1026///     y: i32,
1027/// }
1028///
1029/// let origin = Point { x: 0, y: 0 };
1030///
1031/// let expected = "The origin is: Point {
1032///     x: 0,
1033///     y: 0,
1034/// }";
1035/// assert_eq!(format!("The origin is: {origin:#?}"), expected);
1036/// ```
1037#[stable(feature = "rust1", since = "1.0.0")]
1038#[rustc_on_unimplemented(
1039    on(
1040        all(crate_local, not(Self = "{union}")),
1041        note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {This} for {Self}`"
1042    ),
1043    on(all(crate_local, Self = "{union}"), note = "manually `impl {This} for {Self}`"),
1044    on(
1045        from_desugaring = "FormatLiteral",
1046        label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{This}`"
1047    ),
1048    message = "`{Self}` doesn't implement `{This}`"
1049)]
1050#[doc(alias = "{:?}")]
1051#[rustc_diagnostic_item = "Debug"]
1052#[rustc_trivial_field_reads]
1053pub trait Debug: PointeeSized {
1054    #[doc = include_str!("fmt_trait_method_doc.md")]
1055    ///
1056    /// # Examples
1057    ///
1058    /// ```
1059    /// use std::fmt;
1060    ///
1061    /// struct Position {
1062    ///     longitude: f32,
1063    ///     latitude: f32,
1064    /// }
1065    ///
1066    /// impl fmt::Debug for Position {
1067    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1068    ///         f.debug_tuple("")
1069    ///          .field(&self.longitude)
1070    ///          .field(&self.latitude)
1071    ///          .finish()
1072    ///     }
1073    /// }
1074    ///
1075    /// let position = Position { longitude: 1.987, latitude: 2.983 };
1076    /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
1077    ///
1078    /// assert_eq!(format!("{position:#?}"), "(
1079    ///     1.987,
1080    ///     2.983,
1081    /// )");
1082    /// ```
1083    #[stable(feature = "rust1", since = "1.0.0")]
1084    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1085}
1086
1087// Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
1088pub(crate) mod macros {
1089    /// Derive macro generating an impl of the trait `Debug`.
1090    #[rustc_builtin_macro]
1091    #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1092    #[allow_internal_unstable(core_intrinsics, fmt_helpers_for_derive)]
1093    pub macro Debug($item:item) {
1094        /* compiler built-in */
1095    }
1096}
1097#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1098#[doc(inline)]
1099pub use macros::Debug;
1100
1101/// Format trait for an empty format, `{}`.
1102///
1103/// Implementing this trait for a type will automatically implement the
1104/// [`ToString`][tostring] trait for the type, allowing the usage
1105/// of the [`.to_string()`][tostring_function] method. Prefer implementing
1106/// the `Display` trait for a type, rather than [`ToString`][tostring].
1107///
1108/// `Display` is similar to [`Debug`], but `Display` is for user-facing
1109/// output, and so cannot be derived.
1110///
1111/// For more information on formatters, see [the module-level documentation][module].
1112///
1113/// [module]: ../../std/fmt/index.html
1114/// [tostring]: ../../std/string/trait.ToString.html
1115/// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
1116///
1117/// # Completeness and parseability
1118///
1119/// `Display` for a type might not necessarily be a lossless or complete representation of the type.
1120/// It may omit internal state, precision, or other information the type does not consider important
1121/// for user-facing output, as determined by the type. As such, the output of `Display` might not be
1122/// possible to parse, and even if it is, the result of parsing might not exactly match the original
1123/// value.
1124///
1125/// However, if a type has a lossless `Display` implementation whose output is meant to be
1126/// conveniently machine-parseable and not just meant for human consumption, then the type may wish
1127/// to accept the same format in `FromStr`, and document that usage. Having both `Display` and
1128/// `FromStr` implementations where the result of `Display` cannot be parsed with `FromStr` may
1129/// surprise users.
1130///
1131/// # Internationalization
1132///
1133/// Because a type can only have one `Display` implementation, it is often preferable
1134/// to only implement `Display` when there is a single most "obvious" way that
1135/// values can be formatted as text. This could mean formatting according to the
1136/// "invariant" culture and "undefined" locale, or it could mean that the type
1137/// display is designed for a specific culture/locale, such as developer logs.
1138///
1139/// If not all values have a justifiably canonical textual format or if you want
1140/// to support alternative formats not covered by the standard set of possible
1141/// [formatting traits], the most flexible approach is display adapters: methods
1142/// like [`str::escape_default`] or [`Path::display`] which create a wrapper
1143/// implementing `Display` to output the specific display format.
1144///
1145/// [formatting traits]: ../../std/fmt/index.html#formatting-traits
1146/// [`Path::display`]: ../../std/path/struct.Path.html#method.display
1147///
1148/// # Examples
1149///
1150/// Implementing `Display` on a type:
1151///
1152/// ```
1153/// use std::fmt;
1154///
1155/// struct Point {
1156///     x: i32,
1157///     y: i32,
1158/// }
1159///
1160/// impl fmt::Display for Point {
1161///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1162///         write!(f, "({}, {})", self.x, self.y)
1163///     }
1164/// }
1165///
1166/// let origin = Point { x: 0, y: 0 };
1167///
1168/// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
1169/// ```
1170#[rustc_on_unimplemented(
1171    on(
1172        any(Self = "std::path::Path", Self = "std::path::PathBuf"),
1173        label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
1174        note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
1175                as they may contain non-Unicode data",
1176    ),
1177    on(
1178        from_desugaring = "FormatLiteral",
1179        note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead",
1180        label = "`{Self}` cannot be formatted with the default formatter",
1181    ),
1182    message = "`{Self}` doesn't implement `{This}`"
1183)]
1184#[doc(alias = "{}")]
1185#[rustc_diagnostic_item = "Display"]
1186#[stable(feature = "rust1", since = "1.0.0")]
1187pub trait Display: PointeeSized {
1188    #[doc = include_str!("fmt_trait_method_doc.md")]
1189    ///
1190    /// # Examples
1191    ///
1192    /// ```
1193    /// use std::fmt;
1194    ///
1195    /// struct Position {
1196    ///     longitude: f32,
1197    ///     latitude: f32,
1198    /// }
1199    ///
1200    /// impl fmt::Display for Position {
1201    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1202    ///         write!(f, "({}, {})", self.longitude, self.latitude)
1203    ///     }
1204    /// }
1205    ///
1206    /// assert_eq!(
1207    ///     "(1.987, 2.983)",
1208    ///     format!("{}", Position { longitude: 1.987, latitude: 2.983, }),
1209    /// );
1210    /// ```
1211    #[stable(feature = "rust1", since = "1.0.0")]
1212    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1213}
1214
1215/// `o` formatting.
1216///
1217/// The `Octal` trait should format its output as a number in base-8.
1218///
1219/// For primitive signed integers (`i8` to `i128`, and `isize`),
1220/// negative values are formatted as the two’s complement representation.
1221///
1222/// The alternate flag, `#`, adds a `0o` in front of the output.
1223///
1224/// For more information on formatters, see [the module-level documentation][module].
1225///
1226/// [module]: ../../std/fmt/index.html
1227///
1228/// # Examples
1229///
1230/// Basic usage with `i32`:
1231///
1232/// ```
1233/// let x = 42; // 42 is '52' in octal
1234///
1235/// assert_eq!(format!("{x:o}"), "52");
1236/// assert_eq!(format!("{x:#o}"), "0o52");
1237///
1238/// assert_eq!(format!("{:o}", -16), "37777777760");
1239/// ```
1240///
1241/// Implementing `Octal` on a type:
1242///
1243/// ```
1244/// use std::fmt;
1245///
1246/// struct Length(i32);
1247///
1248/// impl fmt::Octal for Length {
1249///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1250///         let val = self.0;
1251///
1252///         fmt::Octal::fmt(&val, f) // delegate to i32's implementation
1253///     }
1254/// }
1255///
1256/// let l = Length(9);
1257///
1258/// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
1259///
1260/// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
1261/// ```
1262#[stable(feature = "rust1", since = "1.0.0")]
1263pub trait Octal: PointeeSized {
1264    #[doc = include_str!("fmt_trait_method_doc.md")]
1265    #[stable(feature = "rust1", since = "1.0.0")]
1266    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1267}
1268
1269/// `b` formatting.
1270///
1271/// The `Binary` trait should format its output as a number in binary.
1272///
1273/// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
1274/// negative values are formatted as the two’s complement representation.
1275///
1276/// The alternate flag, `#`, adds a `0b` in front of the output.
1277///
1278/// For more information on formatters, see [the module-level documentation][module].
1279///
1280/// [module]: ../../std/fmt/index.html
1281///
1282/// # Examples
1283///
1284/// Basic usage with [`i32`]:
1285///
1286/// ```
1287/// let x = 42; // 42 is '101010' in binary
1288///
1289/// assert_eq!(format!("{x:b}"), "101010");
1290/// assert_eq!(format!("{x:#b}"), "0b101010");
1291///
1292/// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
1293/// ```
1294///
1295/// Implementing `Binary` on a type:
1296///
1297/// ```
1298/// use std::fmt;
1299///
1300/// struct Length(i32);
1301///
1302/// impl fmt::Binary for Length {
1303///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1304///         let val = self.0;
1305///
1306///         fmt::Binary::fmt(&val, f) // delegate to i32's implementation
1307///     }
1308/// }
1309///
1310/// let l = Length(107);
1311///
1312/// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
1313///
1314/// assert_eq!(
1315///     // Note that the `0b` prefix added by `#` is included in the total width, so we
1316///     // need to add two to correctly display all 32 bits.
1317///     format!("l as binary is: {l:#034b}"),
1318///     "l as binary is: 0b00000000000000000000000001101011"
1319/// );
1320/// ```
1321#[stable(feature = "rust1", since = "1.0.0")]
1322pub trait Binary: PointeeSized {
1323    #[doc = include_str!("fmt_trait_method_doc.md")]
1324    #[stable(feature = "rust1", since = "1.0.0")]
1325    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1326}
1327
1328/// `x` formatting.
1329///
1330/// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
1331/// in lower case.
1332///
1333/// For primitive signed integers (`i8` to `i128`, and `isize`),
1334/// negative values are formatted as the two’s complement representation.
1335///
1336/// The alternate flag, `#`, adds a `0x` in front of the output.
1337///
1338/// For more information on formatters, see [the module-level documentation][module].
1339///
1340/// [module]: ../../std/fmt/index.html
1341///
1342/// # Examples
1343///
1344/// Basic usage with `i32`:
1345///
1346/// ```
1347/// let y = 42; // 42 is '2a' in hex
1348///
1349/// assert_eq!(format!("{y:x}"), "2a");
1350/// assert_eq!(format!("{y:#x}"), "0x2a");
1351///
1352/// assert_eq!(format!("{:x}", -16), "fffffff0");
1353/// ```
1354///
1355/// Implementing `LowerHex` on a type:
1356///
1357/// ```
1358/// use std::fmt;
1359///
1360/// struct Length(i32);
1361///
1362/// impl fmt::LowerHex for Length {
1363///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1364///         let val = self.0;
1365///
1366///         fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
1367///     }
1368/// }
1369///
1370/// let l = Length(9);
1371///
1372/// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
1373///
1374/// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
1375/// ```
1376#[stable(feature = "rust1", since = "1.0.0")]
1377pub trait LowerHex: PointeeSized {
1378    #[doc = include_str!("fmt_trait_method_doc.md")]
1379    #[stable(feature = "rust1", since = "1.0.0")]
1380    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1381}
1382
1383/// `X` formatting.
1384///
1385/// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
1386/// in upper case.
1387///
1388/// For primitive signed integers (`i8` to `i128`, and `isize`),
1389/// negative values are formatted as the two’s complement representation.
1390///
1391/// The alternate flag, `#`, adds a `0x` in front of the output.
1392///
1393/// For more information on formatters, see [the module-level documentation][module].
1394///
1395/// [module]: ../../std/fmt/index.html
1396///
1397/// # Examples
1398///
1399/// Basic usage with `i32`:
1400///
1401/// ```
1402/// let y = 42; // 42 is '2A' in hex
1403///
1404/// assert_eq!(format!("{y:X}"), "2A");
1405/// assert_eq!(format!("{y:#X}"), "0x2A");
1406///
1407/// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
1408/// ```
1409///
1410/// Implementing `UpperHex` on a type:
1411///
1412/// ```
1413/// use std::fmt;
1414///
1415/// struct Length(i32);
1416///
1417/// impl fmt::UpperHex for Length {
1418///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1419///         let val = self.0;
1420///
1421///         fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
1422///     }
1423/// }
1424///
1425/// let l = Length(i32::MAX);
1426///
1427/// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
1428///
1429/// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
1430/// ```
1431#[stable(feature = "rust1", since = "1.0.0")]
1432pub trait UpperHex: PointeeSized {
1433    #[doc = include_str!("fmt_trait_method_doc.md")]
1434    #[stable(feature = "rust1", since = "1.0.0")]
1435    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1436}
1437
1438/// `p` formatting.
1439///
1440/// The `Pointer` trait should format its output as a memory location. This is commonly presented
1441/// as hexadecimal. For more information on formatters, see [the module-level documentation][module].
1442///
1443/// Printing of pointers is not a reliable way to discover how Rust programs are implemented.
1444/// The act of reading an address changes the program itself, and may change how the data is represented
1445/// in memory, and may affect which optimizations are applied to the code.
1446///
1447/// The printed pointer values are not guaranteed to be stable nor unique identifiers of objects.
1448/// Rust allows moving values to different memory locations, and may reuse the same memory locations
1449/// for different purposes.
1450///
1451/// There is no guarantee that the printed value can be converted back to a pointer.
1452///
1453/// [module]: ../../std/fmt/index.html
1454///
1455/// # Examples
1456///
1457/// Basic usage with `&i32`:
1458///
1459/// ```
1460/// let x = &42;
1461///
1462/// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
1463/// ```
1464///
1465/// Implementing `Pointer` on a type:
1466///
1467/// ```
1468/// use std::fmt;
1469///
1470/// struct Length(i32);
1471///
1472/// impl fmt::Pointer for Length {
1473///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1474///         // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1475///
1476///         let ptr = self as *const Self;
1477///         fmt::Pointer::fmt(&ptr, f)
1478///     }
1479/// }
1480///
1481/// let l = Length(42);
1482///
1483/// println!("l is in memory here: {l:p}");
1484///
1485/// let l_ptr = format!("{l:018p}");
1486/// assert_eq!(l_ptr.len(), 18);
1487/// assert_eq!(&l_ptr[..2], "0x");
1488/// ```
1489#[stable(feature = "rust1", since = "1.0.0")]
1490#[rustc_diagnostic_item = "Pointer"]
1491pub trait Pointer: PointeeSized {
1492    #[doc = include_str!("fmt_trait_method_doc.md")]
1493    #[stable(feature = "rust1", since = "1.0.0")]
1494    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1495}
1496
1497/// `e` formatting.
1498///
1499/// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1500///
1501/// For more information on formatters, see [the module-level documentation][module].
1502///
1503/// [module]: ../../std/fmt/index.html
1504///
1505/// # Examples
1506///
1507/// Basic usage with `f64`:
1508///
1509/// ```
1510/// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1511///
1512/// assert_eq!(format!("{x:e}"), "4.2e1");
1513/// ```
1514///
1515/// Implementing `LowerExp` on a type:
1516///
1517/// ```
1518/// use std::fmt;
1519///
1520/// struct Length(i32);
1521///
1522/// impl fmt::LowerExp for Length {
1523///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1524///         let val = f64::from(self.0);
1525///         fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1526///     }
1527/// }
1528///
1529/// let l = Length(100);
1530///
1531/// assert_eq!(
1532///     format!("l in scientific notation is: {l:e}"),
1533///     "l in scientific notation is: 1e2"
1534/// );
1535///
1536/// assert_eq!(
1537///     format!("l in scientific notation is: {l:05e}"),
1538///     "l in scientific notation is: 001e2"
1539/// );
1540/// ```
1541#[stable(feature = "rust1", since = "1.0.0")]
1542pub trait LowerExp: PointeeSized {
1543    #[doc = include_str!("fmt_trait_method_doc.md")]
1544    #[stable(feature = "rust1", since = "1.0.0")]
1545    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1546}
1547
1548/// `E` formatting.
1549///
1550/// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1551///
1552/// For more information on formatters, see [the module-level documentation][module].
1553///
1554/// [module]: ../../std/fmt/index.html
1555///
1556/// # Examples
1557///
1558/// Basic usage with `f64`:
1559///
1560/// ```
1561/// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1562///
1563/// assert_eq!(format!("{x:E}"), "4.2E1");
1564/// ```
1565///
1566/// Implementing `UpperExp` on a type:
1567///
1568/// ```
1569/// use std::fmt;
1570///
1571/// struct Length(i32);
1572///
1573/// impl fmt::UpperExp for Length {
1574///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1575///         let val = f64::from(self.0);
1576///         fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1577///     }
1578/// }
1579///
1580/// let l = Length(100);
1581///
1582/// assert_eq!(
1583///     format!("l in scientific notation is: {l:E}"),
1584///     "l in scientific notation is: 1E2"
1585/// );
1586///
1587/// assert_eq!(
1588///     format!("l in scientific notation is: {l:05E}"),
1589///     "l in scientific notation is: 001E2"
1590/// );
1591/// ```
1592#[stable(feature = "rust1", since = "1.0.0")]
1593pub trait UpperExp: PointeeSized {
1594    #[doc = include_str!("fmt_trait_method_doc.md")]
1595    #[stable(feature = "rust1", since = "1.0.0")]
1596    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1597}
1598
1599/// Takes an output stream and an `Arguments` struct that can be precompiled with
1600/// the `format_args!` macro.
1601///
1602/// The arguments will be formatted according to the specified format string
1603/// into the output stream provided.
1604///
1605/// # Examples
1606///
1607/// Basic usage:
1608///
1609/// ```
1610/// use std::fmt;
1611///
1612/// let mut output = String::new();
1613/// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1614///     .expect("Error occurred while trying to write in String");
1615/// assert_eq!(output, "Hello world!");
1616/// ```
1617///
1618/// Please note that using [`write!`] might be preferable. Example:
1619///
1620/// ```
1621/// use std::fmt::Write;
1622///
1623/// let mut output = String::new();
1624/// write!(&mut output, "Hello {}!", "world")
1625///     .expect("Error occurred while trying to write in String");
1626/// assert_eq!(output, "Hello world!");
1627/// ```
1628///
1629/// [`write!`]: crate::write!
1630#[stable(feature = "rust1", since = "1.0.0")]
1631pub fn write(output: &mut dyn Write, fmt: Arguments<'_>) -> Result {
1632    if let Some(s) = fmt.as_str() {
1633        return output.write_str(s);
1634    }
1635
1636    let mut template = fmt.template;
1637    let args = fmt.args;
1638
1639    let mut arg_index = 0;
1640
1641    // See comment on `fmt::Arguments` for the details of how the template is encoded.
1642
1643    // This must match the encoding from `expand_format_args` in
1644    // compiler/rustc_ast_lowering/src/format.rs.
1645    loop {
1646        // SAFETY: We can assume the template is valid.
1647        let n = unsafe {
1648            let n = template.read();
1649            template = template.add(1);
1650            n
1651        };
1652
1653        if n == 0 {
1654            // End of template.
1655            return Ok(());
1656        } else if n < 0x80 {
1657            // Literal string piece of length `n`.
1658
1659            // SAFETY: We can assume the strings in the template are valid.
1660            let s = unsafe {
1661                let s = crate::str::from_raw_parts(template.as_ptr(), n as usize);
1662                template = template.add(n as usize);
1663                s
1664            };
1665            output.write_str(s)?;
1666        } else if n == 0x80 {
1667            // Literal string piece with a 16-bit length.
1668
1669            // SAFETY: We can assume the strings in the template are valid.
1670            let s = unsafe {
1671                let len = usize::from(u16::from_le_bytes(template.cast_array().read()));
1672                template = template.add(2);
1673                let s = crate::str::from_raw_parts(template.as_ptr(), len);
1674                template = template.add(len);
1675                s
1676            };
1677            output.write_str(s)?;
1678        } else if n == 0xC0 {
1679            // Placeholder for next argument with default options.
1680            //
1681            // Having this as a separate case improves performance for the common case.
1682
1683            // SAFETY: We can assume the template only refers to arguments that exist.
1684            unsafe {
1685                args.add(arg_index)
1686                    .as_ref()
1687                    .fmt(&mut Formatter::new(output, FormattingOptions::new()))?;
1688            }
1689            arg_index += 1;
1690        } else {
1691            // SAFETY: We can assume the template is valid.
1692            unsafe { assert_unchecked(n > 0xC0) };
1693
1694            // Placeholder with custom options.
1695
1696            let mut opt = FormattingOptions::new();
1697
1698            // SAFETY: We can assume the template is valid.
1699            unsafe {
1700                if n & 1 != 0 {
1701                    opt.flags = u32::from_le_bytes(template.cast_array().read());
1702                    template = template.add(4);
1703                }
1704                if n & 2 != 0 {
1705                    opt.width = u16::from_le_bytes(template.cast_array().read());
1706                    template = template.add(2);
1707                }
1708                if n & 4 != 0 {
1709                    opt.precision = u16::from_le_bytes(template.cast_array().read());
1710                    template = template.add(2);
1711                }
1712                if n & 8 != 0 {
1713                    arg_index = usize::from(u16::from_le_bytes(template.cast_array().read()));
1714                    template = template.add(2);
1715                }
1716            }
1717            if n & 16 != 0 {
1718                // Dynamic width from a usize argument.
1719                // SAFETY: We can assume the template only refers to arguments that exist.
1720                unsafe {
1721                    opt.width = args.add(opt.width as usize).as_ref().as_u16().unwrap_unchecked();
1722                }
1723            }
1724            if n & 32 != 0 {
1725                // Dynamic precision from a usize argument.
1726                // SAFETY: We can assume the template only refers to arguments that exist.
1727                unsafe {
1728                    opt.precision =
1729                        args.add(opt.precision as usize).as_ref().as_u16().unwrap_unchecked();
1730                }
1731            }
1732
1733            // SAFETY: We can assume the template only refers to arguments that exist.
1734            unsafe {
1735                args.add(arg_index).as_ref().fmt(&mut Formatter::new(output, opt))?;
1736            }
1737            arg_index += 1;
1738        }
1739    }
1740}
1741
1742/// Padding after the end of something. Returned by `Formatter::padding`.
1743#[must_use = "don't forget to write the post padding"]
1744pub(crate) struct PostPadding {
1745    fill: char,
1746    padding: u16,
1747}
1748
1749impl PostPadding {
1750    fn new(fill: char, padding: u16) -> PostPadding {
1751        PostPadding { fill, padding }
1752    }
1753
1754    /// Writes this post padding.
1755    pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1756        for _ in 0..self.padding {
1757            f.buf.write_char(self.fill)?;
1758        }
1759        Ok(())
1760    }
1761}
1762
1763impl<'a> Formatter<'a> {
1764    fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1765    where
1766        'b: 'c,
1767        F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1768    {
1769        Formatter {
1770            // We want to change this
1771            buf: wrap(self.buf),
1772
1773            // And preserve these
1774            options: self.options,
1775        }
1776    }
1777
1778    // Helper methods used for padding and processing formatting arguments that
1779    // all formatting traits can use.
1780
1781    /// Performs the correct padding for an integer which has already been
1782    /// emitted into a str. The str should *not* contain the sign for the
1783    /// integer, that will be added by this method.
1784    ///
1785    /// # Arguments
1786    ///
1787    /// * is_nonnegative - whether the original integer was either positive or zero.
1788    /// * prefix - if the '#' character (Alternate) is provided, this
1789    ///   is the prefix to put in front of the number.
1790    /// * buf - the byte array that the number has been formatted into
1791    ///
1792    /// This function will correctly account for the flags provided as well as
1793    /// the minimum width. It will not take precision into account.
1794    ///
1795    /// # Examples
1796    ///
1797    /// ```
1798    /// use std::fmt;
1799    ///
1800    /// struct Foo { nb: i32 }
1801    ///
1802    /// impl Foo {
1803    ///     fn new(nb: i32) -> Foo {
1804    ///         Foo {
1805    ///             nb,
1806    ///         }
1807    ///     }
1808    /// }
1809    ///
1810    /// impl fmt::Display for Foo {
1811    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1812    ///         // We need to remove "-" from the number output.
1813    ///         let tmp = self.nb.abs().to_string();
1814    ///
1815    ///         formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1816    ///     }
1817    /// }
1818    ///
1819    /// assert_eq!(format!("{}", Foo::new(2)), "2");
1820    /// assert_eq!(format!("{}", Foo::new(-1)), "-1");
1821    /// assert_eq!(format!("{}", Foo::new(0)), "0");
1822    /// assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
1823    /// assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1824    /// ```
1825    #[stable(feature = "rust1", since = "1.0.0")]
1826    pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1827        let mut width = buf.len();
1828
1829        let mut sign = None;
1830        if !is_nonnegative {
1831            sign = Some('-');
1832            width += 1;
1833        } else if self.sign_plus() {
1834            sign = Some('+');
1835            width += 1;
1836        }
1837
1838        let prefix = if self.alternate() {
1839            width += prefix.chars().count();
1840            Some(prefix)
1841        } else {
1842            None
1843        };
1844
1845        // Writes the sign if it exists, and then the prefix if it was requested
1846        #[inline(never)]
1847        fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1848            if let Some(c) = sign {
1849                f.buf.write_char(c)?;
1850            }
1851            if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1852        }
1853
1854        // The `width` field is more of a `min-width` parameter at this point.
1855        let min = self.options.width;
1856        if width >= usize::from(min) {
1857            // We're over the minimum width, so then we can just write the bytes.
1858            write_prefix(self, sign, prefix)?;
1859            self.buf.write_str(buf)
1860        } else if self.sign_aware_zero_pad() {
1861            // The sign and prefix goes before the padding if the fill character
1862            // is zero
1863            let old_options = self.options;
1864            self.options.fill('0').align(Some(Alignment::Right));
1865            write_prefix(self, sign, prefix)?;
1866            let post_padding = self.padding(min - width as u16, Alignment::Right)?;
1867            self.buf.write_str(buf)?;
1868            post_padding.write(self)?;
1869            self.options = old_options;
1870            Ok(())
1871        } else {
1872            // Otherwise, the sign and prefix goes after the padding
1873            let post_padding = self.padding(min - width as u16, Alignment::Right)?;
1874            write_prefix(self, sign, prefix)?;
1875            self.buf.write_str(buf)?;
1876            post_padding.write(self)
1877        }
1878    }
1879
1880    /// Takes a string slice and emits it to the internal buffer after applying
1881    /// the relevant formatting flags specified.
1882    ///
1883    /// The flags recognized for generic strings are:
1884    ///
1885    /// * width - the minimum width of what to emit
1886    /// * fill/align - what to emit and where to emit it if the string
1887    ///                provided needs to be padded
1888    /// * precision - the maximum length to emit, the string is truncated if it
1889    ///               is longer than this length
1890    ///
1891    /// Notably this function ignores the `flag` parameters.
1892    ///
1893    /// # Examples
1894    ///
1895    /// ```
1896    /// use std::fmt;
1897    ///
1898    /// struct Foo;
1899    ///
1900    /// impl fmt::Display for Foo {
1901    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1902    ///         formatter.pad("Foo")
1903    ///     }
1904    /// }
1905    ///
1906    /// assert_eq!(format!("{Foo:<4}"), "Foo ");
1907    /// assert_eq!(format!("{Foo:0>4}"), "0Foo");
1908    /// ```
1909    #[stable(feature = "rust1", since = "1.0.0")]
1910    pub fn pad(&mut self, s: &str) -> Result {
1911        // Make sure there's a fast path up front.
1912        if self.options.flags & (flags::WIDTH_FLAG | flags::PRECISION_FLAG) == 0 {
1913            return self.buf.write_str(s);
1914        }
1915
1916        // The `precision` field can be interpreted as a maximum width for the
1917        // string being formatted.
1918        let (s, char_count) = if let Some(max_char_count) = self.options.get_precision() {
1919            let mut iter = s.char_indices();
1920            let remaining = match iter.advance_by(usize::from(max_char_count)) {
1921                Ok(()) => 0,
1922                Err(remaining) => remaining.get(),
1923            };
1924            // SAFETY: The offset of `.char_indices()` is guaranteed to be
1925            // in-bounds and between character boundaries.
1926            let truncated = unsafe { s.get_unchecked(..iter.offset()) };
1927            (truncated, usize::from(max_char_count) - remaining)
1928        } else {
1929            // Use the optimized char counting algorithm for the full string.
1930            (s, s.chars().count())
1931        };
1932
1933        // The `width` field is more of a minimum width parameter at this point.
1934        if char_count < usize::from(self.options.width) {
1935            // If we're under the minimum width, then fill up the minimum width
1936            // with the specified string + some alignment.
1937            let post_padding =
1938                self.padding(self.options.width - char_count as u16, Alignment::Left)?;
1939            self.buf.write_str(s)?;
1940            post_padding.write(self)
1941        } else {
1942            // If we're over the minimum width or there is no minimum width, we
1943            // can just emit the string.
1944            self.buf.write_str(s)
1945        }
1946    }
1947
1948    /// Writes the pre-padding and returns the unwritten post-padding.
1949    ///
1950    /// Callers are responsible for ensuring post-padding is written after the
1951    /// thing that is being padded.
1952    pub(crate) fn padding(
1953        &mut self,
1954        padding: u16,
1955        default: Alignment,
1956    ) -> result::Result<PostPadding, Error> {
1957        let align = self.options.get_align().unwrap_or(default);
1958        let fill = self.options.get_fill();
1959
1960        let padding_left = match align {
1961            Alignment::Left => 0,
1962            Alignment::Right => padding,
1963            Alignment::Center => padding / 2,
1964        };
1965
1966        for _ in 0..padding_left {
1967            self.buf.write_char(fill)?;
1968        }
1969
1970        Ok(PostPadding::new(fill, padding - padding_left))
1971    }
1972
1973    /// Takes the formatted parts and applies the padding.
1974    ///
1975    /// Assumes that the caller already has rendered the parts with required precision,
1976    /// so that `self.precision` can be ignored.
1977    ///
1978    /// # Safety
1979    ///
1980    /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
1981    unsafe fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1982        if self.options.width == 0 {
1983            // this is the common case and we take a shortcut
1984            // SAFETY: Per the precondition.
1985            unsafe { self.write_formatted_parts(formatted) }
1986        } else {
1987            // for the sign-aware zero padding, we render the sign first and
1988            // behave as if we had no sign from the beginning.
1989            let mut formatted = formatted.clone();
1990            let mut width = self.options.width;
1991            let old_options = self.options;
1992            if self.sign_aware_zero_pad() {
1993                // a sign always goes first
1994                let sign = formatted.sign;
1995                self.buf.write_str(sign)?;
1996
1997                // remove the sign from the formatted parts
1998                formatted.sign = "";
1999                width = width.saturating_sub(sign.len() as u16);
2000                self.options.fill('0').align(Some(Alignment::Right));
2001            }
2002
2003            // remaining parts go through the ordinary padding process.
2004            let len = formatted.len();
2005            let ret = if usize::from(width) <= len {
2006                // no padding
2007                // SAFETY: Per the precondition.
2008                unsafe { self.write_formatted_parts(&formatted) }
2009            } else {
2010                let post_padding = self.padding(width - len as u16, Alignment::Right)?;
2011                // SAFETY: Per the precondition.
2012                unsafe {
2013                    self.write_formatted_parts(&formatted)?;
2014                }
2015                post_padding.write(self)
2016            };
2017            self.options = old_options;
2018            ret
2019        }
2020    }
2021
2022    /// # Safety
2023    ///
2024    /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
2025    unsafe fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
2026        unsafe fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
2027            // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
2028            // It's safe to use for `numfmt::Part::Num` since every char `c` is between
2029            // `b'0'` and `b'9'`, which means `s` is valid UTF-8. It's safe to use for
2030            // `numfmt::Part::Copy` due to this function's precondition.
2031            buf.write_str(unsafe { str::from_utf8_unchecked(s) })
2032        }
2033
2034        if !formatted.sign.is_empty() {
2035            self.buf.write_str(formatted.sign)?;
2036        }
2037        for part in formatted.parts {
2038            match *part {
2039                numfmt::Part::Zero(mut nzeroes) => {
2040                    const ZEROES: &str = // 64 zeroes
2041                        "0000000000000000000000000000000000000000000000000000000000000000";
2042                    while nzeroes > ZEROES.len() {
2043                        self.buf.write_str(ZEROES)?;
2044                        nzeroes -= ZEROES.len();
2045                    }
2046                    if nzeroes > 0 {
2047                        self.buf.write_str(&ZEROES[..nzeroes])?;
2048                    }
2049                }
2050                numfmt::Part::Num(mut v) => {
2051                    let mut s = [0; 5];
2052                    let len = part.len();
2053                    for c in s[..len].iter_mut().rev() {
2054                        *c = b'0' + (v % 10) as u8;
2055                        v /= 10;
2056                    }
2057                    // SAFETY: Per the precondition.
2058                    unsafe {
2059                        write_bytes(self.buf, &s[..len])?;
2060                    }
2061                }
2062                // SAFETY: Per the precondition.
2063                numfmt::Part::Copy(buf) => unsafe {
2064                    write_bytes(self.buf, buf)?;
2065                },
2066            }
2067        }
2068        Ok(())
2069    }
2070
2071    /// Writes some data to the underlying buffer contained within this
2072    /// formatter.
2073    ///
2074    /// # Examples
2075    ///
2076    /// ```
2077    /// use std::fmt;
2078    ///
2079    /// struct Foo;
2080    ///
2081    /// impl fmt::Display for Foo {
2082    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2083    ///         formatter.write_str("Foo")
2084    ///         // This is equivalent to:
2085    ///         // write!(formatter, "Foo")
2086    ///     }
2087    /// }
2088    ///
2089    /// assert_eq!(format!("{Foo}"), "Foo");
2090    /// assert_eq!(format!("{Foo:0>8}"), "Foo");
2091    /// ```
2092    #[stable(feature = "rust1", since = "1.0.0")]
2093    pub fn write_str(&mut self, data: &str) -> Result {
2094        self.buf.write_str(data)
2095    }
2096
2097    /// Glue for usage of the [`write!`] macro with implementors of this trait.
2098    ///
2099    /// This method should generally not be invoked manually, but rather through
2100    /// the [`write!`] macro itself.
2101    ///
2102    /// Writes some formatted information into this instance.
2103    ///
2104    /// # Examples
2105    ///
2106    /// ```
2107    /// use std::fmt;
2108    ///
2109    /// struct Foo(i32);
2110    ///
2111    /// impl fmt::Display for Foo {
2112    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2113    ///         formatter.write_fmt(format_args!("Foo {}", self.0))
2114    ///     }
2115    /// }
2116    ///
2117    /// assert_eq!(format!("{}", Foo(-1)), "Foo -1");
2118    /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
2119    /// ```
2120    #[stable(feature = "rust1", since = "1.0.0")]
2121    #[inline]
2122    pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
2123        if let Some(s) = fmt.as_statically_known_str() {
2124            self.buf.write_str(s)
2125        } else {
2126            write(self.buf, fmt)
2127        }
2128    }
2129
2130    /// Returns flags for formatting.
2131    #[must_use]
2132    #[stable(feature = "rust1", since = "1.0.0")]
2133    #[deprecated(
2134        since = "1.24.0",
2135        note = "use the `sign_plus`, `sign_minus`, `alternate`, \
2136                or `sign_aware_zero_pad` methods instead"
2137    )]
2138    pub fn flags(&self) -> u32 {
2139        // Extract the debug upper/lower hex, zero pad, alternate, and plus/minus flags
2140        // to stay compatible with older versions of Rust.
2141        self.options.flags >> 21 & 0x3F
2142    }
2143
2144    /// Returns the character used as 'fill' whenever there is alignment.
2145    ///
2146    /// # Examples
2147    ///
2148    /// ```
2149    /// use std::fmt;
2150    ///
2151    /// struct Foo;
2152    ///
2153    /// impl fmt::Display for Foo {
2154    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2155    ///         let c = formatter.fill();
2156    ///         if let Some(width) = formatter.width() {
2157    ///             for _ in 0..width {
2158    ///                 write!(formatter, "{c}")?;
2159    ///             }
2160    ///             Ok(())
2161    ///         } else {
2162    ///             write!(formatter, "{c}")
2163    ///         }
2164    ///     }
2165    /// }
2166    ///
2167    /// // We set alignment to the right with ">".
2168    /// assert_eq!(format!("{Foo:G>3}"), "GGG");
2169    /// assert_eq!(format!("{Foo:t>6}"), "tttttt");
2170    /// ```
2171    #[must_use]
2172    #[stable(feature = "fmt_flags", since = "1.5.0")]
2173    pub fn fill(&self) -> char {
2174        self.options.get_fill()
2175    }
2176
2177    /// Returns a flag indicating what form of alignment was requested.
2178    ///
2179    /// # Examples
2180    ///
2181    /// ```
2182    /// use std::fmt::{self, Alignment};
2183    ///
2184    /// struct Foo;
2185    ///
2186    /// impl fmt::Display for Foo {
2187    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2188    ///         let s = if let Some(s) = formatter.align() {
2189    ///             match s {
2190    ///                 Alignment::Left    => "left",
2191    ///                 Alignment::Right   => "right",
2192    ///                 Alignment::Center  => "center",
2193    ///             }
2194    ///         } else {
2195    ///             "into the void"
2196    ///         };
2197    ///         write!(formatter, "{s}")
2198    ///     }
2199    /// }
2200    ///
2201    /// assert_eq!(format!("{Foo:<}"), "left");
2202    /// assert_eq!(format!("{Foo:>}"), "right");
2203    /// assert_eq!(format!("{Foo:^}"), "center");
2204    /// assert_eq!(format!("{Foo}"), "into the void");
2205    /// ```
2206    #[must_use]
2207    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
2208    pub fn align(&self) -> Option<Alignment> {
2209        self.options.get_align()
2210    }
2211
2212    /// Returns the optionally specified integer width that the output should be.
2213    ///
2214    /// # Examples
2215    ///
2216    /// ```
2217    /// use std::fmt;
2218    ///
2219    /// struct Foo(i32);
2220    ///
2221    /// impl fmt::Display for Foo {
2222    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2223    ///         if let Some(width) = formatter.width() {
2224    ///             // If we received a width, we use it
2225    ///             write!(formatter, "{:width$}", format!("Foo({})", self.0), width = width)
2226    ///         } else {
2227    ///             // Otherwise we do nothing special
2228    ///             write!(formatter, "Foo({})", self.0)
2229    ///         }
2230    ///     }
2231    /// }
2232    ///
2233    /// assert_eq!(format!("{:10}", Foo(23)), "Foo(23)   ");
2234    /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2235    /// ```
2236    #[must_use]
2237    #[stable(feature = "fmt_flags", since = "1.5.0")]
2238    pub fn width(&self) -> Option<usize> {
2239        if self.options.flags & flags::WIDTH_FLAG == 0 {
2240            None
2241        } else {
2242            Some(self.options.width as usize)
2243        }
2244    }
2245
2246    /// Returns the optionally specified precision for numeric types.
2247    /// Alternatively, the maximum width for string types.
2248    ///
2249    /// # Examples
2250    ///
2251    /// ```
2252    /// use std::fmt;
2253    ///
2254    /// struct Foo(f32);
2255    ///
2256    /// impl fmt::Display for Foo {
2257    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2258    ///         if let Some(precision) = formatter.precision() {
2259    ///             // If we received a precision, we use it.
2260    ///             write!(formatter, "Foo({1:.*})", precision, self.0)
2261    ///         } else {
2262    ///             // Otherwise we default to 2.
2263    ///             write!(formatter, "Foo({:.2})", self.0)
2264    ///         }
2265    ///     }
2266    /// }
2267    ///
2268    /// assert_eq!(format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
2269    /// assert_eq!(format!("{}", Foo(23.2)), "Foo(23.20)");
2270    /// ```
2271    #[must_use]
2272    #[stable(feature = "fmt_flags", since = "1.5.0")]
2273    pub fn precision(&self) -> Option<usize> {
2274        if self.options.flags & flags::PRECISION_FLAG == 0 {
2275            None
2276        } else {
2277            Some(self.options.precision as usize)
2278        }
2279    }
2280
2281    /// Determines if the `+` flag was specified.
2282    ///
2283    /// # Examples
2284    ///
2285    /// ```
2286    /// use std::fmt;
2287    ///
2288    /// struct Foo(i32);
2289    ///
2290    /// impl fmt::Display for Foo {
2291    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2292    ///         if formatter.sign_plus() {
2293    ///             write!(formatter,
2294    ///                    "Foo({}{})",
2295    ///                    if self.0 < 0 { '-' } else { '+' },
2296    ///                    self.0.abs())
2297    ///         } else {
2298    ///             write!(formatter, "Foo({})", self.0)
2299    ///         }
2300    ///     }
2301    /// }
2302    ///
2303    /// assert_eq!(format!("{:+}", Foo(23)), "Foo(+23)");
2304    /// assert_eq!(format!("{:+}", Foo(-23)), "Foo(-23)");
2305    /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2306    /// ```
2307    #[must_use]
2308    #[stable(feature = "fmt_flags", since = "1.5.0")]
2309    pub fn sign_plus(&self) -> bool {
2310        self.options.flags & flags::SIGN_PLUS_FLAG != 0
2311    }
2312
2313    /// Determines if the `-` flag was specified.
2314    ///
2315    /// # Examples
2316    ///
2317    /// ```
2318    /// use std::fmt;
2319    ///
2320    /// struct Foo(i32);
2321    ///
2322    /// impl fmt::Display for Foo {
2323    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2324    ///         if formatter.sign_minus() {
2325    ///             // You want a minus sign? Have one!
2326    ///             write!(formatter, "-Foo({})", self.0)
2327    ///         } else {
2328    ///             write!(formatter, "Foo({})", self.0)
2329    ///         }
2330    ///     }
2331    /// }
2332    ///
2333    /// assert_eq!(format!("{:-}", Foo(23)), "-Foo(23)");
2334    /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2335    /// ```
2336    #[must_use]
2337    #[stable(feature = "fmt_flags", since = "1.5.0")]
2338    pub fn sign_minus(&self) -> bool {
2339        self.options.flags & flags::SIGN_MINUS_FLAG != 0
2340    }
2341
2342    /// Determines if the `#` flag was specified.
2343    ///
2344    /// # Examples
2345    ///
2346    /// ```
2347    /// use std::fmt;
2348    ///
2349    /// struct Foo(i32);
2350    ///
2351    /// impl fmt::Display for Foo {
2352    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2353    ///         if formatter.alternate() {
2354    ///             write!(formatter, "Foo({})", self.0)
2355    ///         } else {
2356    ///             write!(formatter, "{}", self.0)
2357    ///         }
2358    ///     }
2359    /// }
2360    ///
2361    /// assert_eq!(format!("{:#}", Foo(23)), "Foo(23)");
2362    /// assert_eq!(format!("{}", Foo(23)), "23");
2363    /// ```
2364    #[must_use]
2365    #[stable(feature = "fmt_flags", since = "1.5.0")]
2366    pub fn alternate(&self) -> bool {
2367        self.options.flags & flags::ALTERNATE_FLAG != 0
2368    }
2369
2370    /// Determines if the `0` flag was specified.
2371    ///
2372    /// # Examples
2373    ///
2374    /// ```
2375    /// use std::fmt;
2376    ///
2377    /// struct Foo(i32);
2378    ///
2379    /// impl fmt::Display for Foo {
2380    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2381    ///         assert!(formatter.sign_aware_zero_pad());
2382    ///         assert_eq!(formatter.width(), Some(4));
2383    ///         // We ignore the formatter's options.
2384    ///         write!(formatter, "{}", self.0)
2385    ///     }
2386    /// }
2387    ///
2388    /// assert_eq!(format!("{:04}", Foo(23)), "23");
2389    /// ```
2390    #[must_use]
2391    #[stable(feature = "fmt_flags", since = "1.5.0")]
2392    pub fn sign_aware_zero_pad(&self) -> bool {
2393        self.options.flags & flags::SIGN_AWARE_ZERO_PAD_FLAG != 0
2394    }
2395
2396    // FIXME: Decide what public API we want for these two flags.
2397    // https://github.com/rust-lang/rust/issues/48584
2398    fn debug_lower_hex(&self) -> bool {
2399        self.options.flags & flags::DEBUG_LOWER_HEX_FLAG != 0
2400    }
2401    fn debug_upper_hex(&self) -> bool {
2402        self.options.flags & flags::DEBUG_UPPER_HEX_FLAG != 0
2403    }
2404
2405    /// Creates a [`DebugStruct`] builder designed to assist with creation of
2406    /// [`fmt::Debug`] implementations for structs.
2407    ///
2408    /// [`fmt::Debug`]: self::Debug
2409    ///
2410    /// # Examples
2411    ///
2412    /// ```rust
2413    /// use std::fmt;
2414    /// use std::net::Ipv4Addr;
2415    ///
2416    /// struct Foo {
2417    ///     bar: i32,
2418    ///     baz: String,
2419    ///     addr: Ipv4Addr,
2420    /// }
2421    ///
2422    /// impl fmt::Debug for Foo {
2423    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2424    ///         fmt.debug_struct("Foo")
2425    ///             .field("bar", &self.bar)
2426    ///             .field("baz", &self.baz)
2427    ///             .field("addr", &format_args!("{}", self.addr))
2428    ///             .finish()
2429    ///     }
2430    /// }
2431    ///
2432    /// assert_eq!(
2433    ///     "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
2434    ///     format!("{:?}", Foo {
2435    ///         bar: 10,
2436    ///         baz: "Hello World".to_string(),
2437    ///         addr: Ipv4Addr::new(127, 0, 0, 1),
2438    ///     })
2439    /// );
2440    /// ```
2441    #[stable(feature = "debug_builders", since = "1.2.0")]
2442    pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
2443        builders::debug_struct_new(self, name)
2444    }
2445
2446    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2447    /// binaries. `debug_struct_fields_finish` is more general, but this is
2448    /// faster for 1 field.
2449    #[doc(hidden)]
2450    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2451    pub fn debug_struct_field1_finish<'b>(
2452        &'b mut self,
2453        name: &str,
2454        name1: &str,
2455        value1: &dyn Debug,
2456    ) -> Result {
2457        let mut builder = builders::debug_struct_new(self, name);
2458        builder.field(name1, value1);
2459        builder.finish()
2460    }
2461
2462    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2463    /// binaries. `debug_struct_fields_finish` is more general, but this is
2464    /// faster for 2 fields.
2465    #[doc(hidden)]
2466    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2467    pub fn debug_struct_field2_finish<'b>(
2468        &'b mut self,
2469        name: &str,
2470        name1: &str,
2471        value1: &dyn Debug,
2472        name2: &str,
2473        value2: &dyn Debug,
2474    ) -> Result {
2475        let mut builder = builders::debug_struct_new(self, name);
2476        builder.field(name1, value1);
2477        builder.field(name2, value2);
2478        builder.finish()
2479    }
2480
2481    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2482    /// binaries. `debug_struct_fields_finish` is more general, but this is
2483    /// faster for 3 fields.
2484    #[doc(hidden)]
2485    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2486    pub fn debug_struct_field3_finish<'b>(
2487        &'b mut self,
2488        name: &str,
2489        name1: &str,
2490        value1: &dyn Debug,
2491        name2: &str,
2492        value2: &dyn Debug,
2493        name3: &str,
2494        value3: &dyn Debug,
2495    ) -> Result {
2496        let mut builder = builders::debug_struct_new(self, name);
2497        builder.field(name1, value1);
2498        builder.field(name2, value2);
2499        builder.field(name3, value3);
2500        builder.finish()
2501    }
2502
2503    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2504    /// binaries. `debug_struct_fields_finish` is more general, but this is
2505    /// faster for 4 fields.
2506    #[doc(hidden)]
2507    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2508    pub fn debug_struct_field4_finish<'b>(
2509        &'b mut self,
2510        name: &str,
2511        name1: &str,
2512        value1: &dyn Debug,
2513        name2: &str,
2514        value2: &dyn Debug,
2515        name3: &str,
2516        value3: &dyn Debug,
2517        name4: &str,
2518        value4: &dyn Debug,
2519    ) -> Result {
2520        let mut builder = builders::debug_struct_new(self, name);
2521        builder.field(name1, value1);
2522        builder.field(name2, value2);
2523        builder.field(name3, value3);
2524        builder.field(name4, value4);
2525        builder.finish()
2526    }
2527
2528    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2529    /// binaries. `debug_struct_fields_finish` is more general, but this is
2530    /// faster for 5 fields.
2531    #[doc(hidden)]
2532    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2533    pub fn debug_struct_field5_finish<'b>(
2534        &'b mut self,
2535        name: &str,
2536        name1: &str,
2537        value1: &dyn Debug,
2538        name2: &str,
2539        value2: &dyn Debug,
2540        name3: &str,
2541        value3: &dyn Debug,
2542        name4: &str,
2543        value4: &dyn Debug,
2544        name5: &str,
2545        value5: &dyn Debug,
2546    ) -> Result {
2547        let mut builder = builders::debug_struct_new(self, name);
2548        builder.field(name1, value1);
2549        builder.field(name2, value2);
2550        builder.field(name3, value3);
2551        builder.field(name4, value4);
2552        builder.field(name5, value5);
2553        builder.finish()
2554    }
2555
2556    /// Shrinks `derive(Debug)` code, for faster compilation and smaller binaries.
2557    /// For the cases not covered by `debug_struct_field[12345]_finish`.
2558    #[doc(hidden)]
2559    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2560    pub fn debug_struct_fields_finish<'b>(
2561        &'b mut self,
2562        name: &str,
2563        names: &[&str],
2564        values: &[&dyn Debug],
2565    ) -> Result {
2566        assert_eq!(names.len(), values.len());
2567        let mut builder = builders::debug_struct_new(self, name);
2568        for (name, value) in iter::zip(names, values) {
2569            builder.field(name, value);
2570        }
2571        builder.finish()
2572    }
2573
2574    /// Creates a `DebugTuple` builder designed to assist with creation of
2575    /// `fmt::Debug` implementations for tuple structs.
2576    ///
2577    /// # Examples
2578    ///
2579    /// ```rust
2580    /// use std::fmt;
2581    /// use std::marker::PhantomData;
2582    ///
2583    /// struct Foo<T>(i32, String, PhantomData<T>);
2584    ///
2585    /// impl<T> fmt::Debug for Foo<T> {
2586    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2587    ///         fmt.debug_tuple("Foo")
2588    ///             .field(&self.0)
2589    ///             .field(&self.1)
2590    ///             .field(&format_args!("_"))
2591    ///             .finish()
2592    ///     }
2593    /// }
2594    ///
2595    /// assert_eq!(
2596    ///     "Foo(10, \"Hello\", _)",
2597    ///     format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
2598    /// );
2599    /// ```
2600    #[stable(feature = "debug_builders", since = "1.2.0")]
2601    pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
2602        builders::debug_tuple_new(self, name)
2603    }
2604
2605    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2606    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2607    /// for 1 field.
2608    #[doc(hidden)]
2609    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2610    pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result {
2611        let mut builder = builders::debug_tuple_new(self, name);
2612        builder.field(value1);
2613        builder.finish()
2614    }
2615
2616    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2617    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2618    /// for 2 fields.
2619    #[doc(hidden)]
2620    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2621    pub fn debug_tuple_field2_finish<'b>(
2622        &'b mut self,
2623        name: &str,
2624        value1: &dyn Debug,
2625        value2: &dyn Debug,
2626    ) -> Result {
2627        let mut builder = builders::debug_tuple_new(self, name);
2628        builder.field(value1);
2629        builder.field(value2);
2630        builder.finish()
2631    }
2632
2633    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2634    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2635    /// for 3 fields.
2636    #[doc(hidden)]
2637    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2638    pub fn debug_tuple_field3_finish<'b>(
2639        &'b mut self,
2640        name: &str,
2641        value1: &dyn Debug,
2642        value2: &dyn Debug,
2643        value3: &dyn Debug,
2644    ) -> Result {
2645        let mut builder = builders::debug_tuple_new(self, name);
2646        builder.field(value1);
2647        builder.field(value2);
2648        builder.field(value3);
2649        builder.finish()
2650    }
2651
2652    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2653    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2654    /// for 4 fields.
2655    #[doc(hidden)]
2656    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2657    pub fn debug_tuple_field4_finish<'b>(
2658        &'b mut self,
2659        name: &str,
2660        value1: &dyn Debug,
2661        value2: &dyn Debug,
2662        value3: &dyn Debug,
2663        value4: &dyn Debug,
2664    ) -> Result {
2665        let mut builder = builders::debug_tuple_new(self, name);
2666        builder.field(value1);
2667        builder.field(value2);
2668        builder.field(value3);
2669        builder.field(value4);
2670        builder.finish()
2671    }
2672
2673    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2674    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2675    /// for 5 fields.
2676    #[doc(hidden)]
2677    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2678    pub fn debug_tuple_field5_finish<'b>(
2679        &'b mut self,
2680        name: &str,
2681        value1: &dyn Debug,
2682        value2: &dyn Debug,
2683        value3: &dyn Debug,
2684        value4: &dyn Debug,
2685        value5: &dyn Debug,
2686    ) -> Result {
2687        let mut builder = builders::debug_tuple_new(self, name);
2688        builder.field(value1);
2689        builder.field(value2);
2690        builder.field(value3);
2691        builder.field(value4);
2692        builder.field(value5);
2693        builder.finish()
2694    }
2695
2696    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2697    /// binaries. For the cases not covered by `debug_tuple_field[12345]_finish`.
2698    #[doc(hidden)]
2699    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2700    pub fn debug_tuple_fields_finish<'b>(
2701        &'b mut self,
2702        name: &str,
2703        values: &[&dyn Debug],
2704    ) -> Result {
2705        let mut builder = builders::debug_tuple_new(self, name);
2706        for value in values {
2707            builder.field(value);
2708        }
2709        builder.finish()
2710    }
2711
2712    /// Creates a `DebugList` builder designed to assist with creation of
2713    /// `fmt::Debug` implementations for list-like structures.
2714    ///
2715    /// # Examples
2716    ///
2717    /// ```rust
2718    /// use std::fmt;
2719    ///
2720    /// struct Foo(Vec<i32>);
2721    ///
2722    /// impl fmt::Debug for Foo {
2723    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2724    ///         fmt.debug_list().entries(self.0.iter()).finish()
2725    ///     }
2726    /// }
2727    ///
2728    /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2729    /// ```
2730    #[stable(feature = "debug_builders", since = "1.2.0")]
2731    pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2732        builders::debug_list_new(self)
2733    }
2734
2735    /// Creates a `DebugSet` builder designed to assist with creation of
2736    /// `fmt::Debug` implementations for set-like structures.
2737    ///
2738    /// # Examples
2739    ///
2740    /// ```rust
2741    /// use std::fmt;
2742    ///
2743    /// struct Foo(Vec<i32>);
2744    ///
2745    /// impl fmt::Debug for Foo {
2746    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2747    ///         fmt.debug_set().entries(self.0.iter()).finish()
2748    ///     }
2749    /// }
2750    ///
2751    /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2752    /// ```
2753    ///
2754    /// [`format_args!`]: crate::format_args
2755    ///
2756    /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2757    /// to build a list of match arms:
2758    ///
2759    /// ```rust
2760    /// use std::fmt;
2761    ///
2762    /// struct Arm<'a, L, R>(&'a (L, R));
2763    /// struct Table<'a, K, V>(&'a [(K, V)], V);
2764    ///
2765    /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2766    /// where
2767    ///     L: 'a + fmt::Debug, R: 'a + fmt::Debug
2768    /// {
2769    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2770    ///         L::fmt(&(self.0).0, fmt)?;
2771    ///         fmt.write_str(" => ")?;
2772    ///         R::fmt(&(self.0).1, fmt)
2773    ///     }
2774    /// }
2775    ///
2776    /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2777    /// where
2778    ///     K: 'a + fmt::Debug, V: 'a + fmt::Debug
2779    /// {
2780    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2781    ///         fmt.debug_set()
2782    ///         .entries(self.0.iter().map(Arm))
2783    ///         .entry(&Arm(&(format_args!("_"), &self.1)))
2784    ///         .finish()
2785    ///     }
2786    /// }
2787    /// ```
2788    #[stable(feature = "debug_builders", since = "1.2.0")]
2789    pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2790        builders::debug_set_new(self)
2791    }
2792
2793    /// Creates a `DebugMap` builder designed to assist with creation of
2794    /// `fmt::Debug` implementations for map-like structures.
2795    ///
2796    /// # Examples
2797    ///
2798    /// ```rust
2799    /// use std::fmt;
2800    ///
2801    /// struct Foo(Vec<(String, i32)>);
2802    ///
2803    /// impl fmt::Debug for Foo {
2804    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2805    ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2806    ///     }
2807    /// }
2808    ///
2809    /// assert_eq!(
2810    ///     format!("{:?}",  Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2811    ///     r#"{"A": 10, "B": 11}"#
2812    ///  );
2813    /// ```
2814    #[stable(feature = "debug_builders", since = "1.2.0")]
2815    pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2816        builders::debug_map_new(self)
2817    }
2818
2819    /// Returns the sign of this formatter (`+` or `-`).
2820    #[unstable(feature = "formatting_options", issue = "118117")]
2821    pub const fn sign(&self) -> Option<Sign> {
2822        self.options.get_sign()
2823    }
2824
2825    /// Returns the formatting options this formatter corresponds to.
2826    #[unstable(feature = "formatting_options", issue = "118117")]
2827    pub const fn options(&self) -> FormattingOptions {
2828        self.options
2829    }
2830}
2831
2832#[stable(since = "1.2.0", feature = "formatter_write")]
2833impl Write for Formatter<'_> {
2834    fn write_str(&mut self, s: &str) -> Result {
2835        self.buf.write_str(s)
2836    }
2837
2838    fn write_char(&mut self, c: char) -> Result {
2839        self.buf.write_char(c)
2840    }
2841
2842    #[inline]
2843    fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2844        if let Some(s) = args.as_statically_known_str() {
2845            self.buf.write_str(s)
2846        } else {
2847            write(self.buf, args)
2848        }
2849    }
2850}
2851
2852#[stable(feature = "rust1", since = "1.0.0")]
2853impl Display for Error {
2854    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2855        Display::fmt("an error occurred when formatting an argument", f)
2856    }
2857}
2858
2859// Implementations of the core formatting traits
2860
2861macro_rules! fmt_refs {
2862    ($($tr:ident),*) => {
2863        $(
2864        #[stable(feature = "rust1", since = "1.0.0")]
2865        impl<T: PointeeSized + $tr> $tr for &T {
2866            fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2867        }
2868        #[stable(feature = "rust1", since = "1.0.0")]
2869        impl<T: PointeeSized + $tr> $tr for &mut T {
2870            fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2871        }
2872        )*
2873    }
2874}
2875
2876fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2877
2878#[unstable(feature = "never_type", issue = "35121")]
2879impl Debug for ! {
2880    #[inline]
2881    fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2882        *self
2883    }
2884}
2885
2886#[unstable(feature = "never_type", issue = "35121")]
2887impl Display for ! {
2888    #[inline]
2889    fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2890        *self
2891    }
2892}
2893
2894#[stable(feature = "rust1", since = "1.0.0")]
2895impl Debug for bool {
2896    #[inline]
2897    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2898        Display::fmt(self, f)
2899    }
2900}
2901
2902#[stable(feature = "rust1", since = "1.0.0")]
2903impl Display for bool {
2904    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2905        Display::fmt(if *self { "true" } else { "false" }, f)
2906    }
2907}
2908
2909#[stable(feature = "rust1", since = "1.0.0")]
2910impl Debug for str {
2911    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2912        f.write_char('"')?;
2913
2914        // substring we know is printable
2915        let mut printable_range = 0..0;
2916
2917        fn needs_escape(b: u8) -> bool {
2918            b > 0x7E || b < 0x20 || b == b'\\' || b == b'"'
2919        }
2920
2921        // the loop here first skips over runs of printable ASCII as a fast path.
2922        // other chars (unicode, or ASCII that needs escaping) are then handled per-`char`.
2923        let mut rest = self;
2924        while rest.len() > 0 {
2925            let Some(non_printable_start) = rest.as_bytes().iter().position(|&b| needs_escape(b))
2926            else {
2927                printable_range.end += rest.len();
2928                break;
2929            };
2930
2931            printable_range.end += non_printable_start;
2932            // SAFETY: the position was derived from an iterator, so is known to be within bounds, and at a char boundary
2933            rest = unsafe { rest.get_unchecked(non_printable_start..) };
2934
2935            let mut chars = rest.chars();
2936            if let Some(c) = chars.next() {
2937                let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2938                    escape_grapheme_extended: true,
2939                    escape_single_quote: false,
2940                    escape_double_quote: true,
2941                });
2942                if esc.len() != 1 {
2943                    f.write_str(&self[printable_range.clone()])?;
2944                    Display::fmt(&esc, f)?;
2945                    printable_range.start = printable_range.end + c.len_utf8();
2946                }
2947                printable_range.end += c.len_utf8();
2948            }
2949            rest = chars.as_str();
2950        }
2951
2952        f.write_str(&self[printable_range])?;
2953
2954        f.write_char('"')
2955    }
2956}
2957
2958#[stable(feature = "rust1", since = "1.0.0")]
2959impl Display for str {
2960    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2961        f.pad(self)
2962    }
2963}
2964
2965#[stable(feature = "rust1", since = "1.0.0")]
2966impl Debug for char {
2967    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2968        f.write_char('\'')?;
2969        let esc = self.escape_debug_ext(EscapeDebugExtArgs {
2970            escape_grapheme_extended: true,
2971            escape_single_quote: true,
2972            escape_double_quote: false,
2973        });
2974        Display::fmt(&esc, f)?;
2975        f.write_char('\'')
2976    }
2977}
2978
2979#[stable(feature = "rust1", since = "1.0.0")]
2980impl Display for char {
2981    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2982        if f.options.flags & (flags::WIDTH_FLAG | flags::PRECISION_FLAG) == 0 {
2983            f.write_char(*self)
2984        } else {
2985            f.pad(self.encode_utf8(&mut [0; char::MAX_LEN_UTF8]))
2986        }
2987    }
2988}
2989
2990#[stable(feature = "rust1", since = "1.0.0")]
2991impl<T: PointeeSized> Pointer for *const T {
2992    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2993        if <<T as core::ptr::Pointee>::Metadata as core::unit::IsUnit>::is_unit() {
2994            pointer_fmt_inner(self.expose_provenance(), f)
2995        } else {
2996            f.debug_struct("Pointer")
2997                .field_with("addr", |f| pointer_fmt_inner(self.expose_provenance(), f))
2998                .field("metadata", &core::ptr::metadata(*self))
2999                .finish()
3000        }
3001    }
3002}
3003
3004/// Since the formatting will be identical for all pointer types, uses a
3005/// non-monomorphized implementation for the actual formatting to reduce the
3006/// amount of codegen work needed.
3007///
3008/// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
3009/// `fn(...) -> ...` without using [problematic] "Oxford Casts".
3010///
3011/// [problematic]: https://github.com/rust-lang/rust/issues/95489
3012pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
3013    let old_options = f.options;
3014
3015    // The alternate flag is already treated by LowerHex as being special-
3016    // it denotes whether to prefix with 0x. We use it to work out whether
3017    // or not to zero extend, and then unconditionally set it to get the
3018    // prefix.
3019    if f.options.get_alternate() {
3020        f.options.sign_aware_zero_pad(true);
3021
3022        if f.options.get_width().is_none() {
3023            f.options.width(Some((usize::BITS / 4) as u16 + 2));
3024        }
3025    }
3026    f.options.alternate(true);
3027
3028    let ret = LowerHex::fmt(&ptr_addr, f);
3029
3030    f.options = old_options;
3031
3032    ret
3033}
3034
3035#[stable(feature = "rust1", since = "1.0.0")]
3036impl<T: PointeeSized> Pointer for *mut T {
3037    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3038        Pointer::fmt(&(*self as *const T), f)
3039    }
3040}
3041
3042#[stable(feature = "rust1", since = "1.0.0")]
3043impl<T: PointeeSized> Pointer for &T {
3044    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3045        Pointer::fmt(&(*self as *const T), f)
3046    }
3047}
3048
3049#[stable(feature = "rust1", since = "1.0.0")]
3050impl<T: PointeeSized> Pointer for &mut T {
3051    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3052        Pointer::fmt(&(&**self as *const T), f)
3053    }
3054}
3055
3056// Implementation of Display/Debug for various core types
3057
3058#[stable(feature = "rust1", since = "1.0.0")]
3059impl<T: PointeeSized> Debug for *const T {
3060    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3061        Pointer::fmt(self, f)
3062    }
3063}
3064#[stable(feature = "rust1", since = "1.0.0")]
3065impl<T: PointeeSized> Debug for *mut T {
3066    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3067        Pointer::fmt(self, f)
3068    }
3069}
3070
3071macro_rules! peel {
3072    ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
3073}
3074
3075macro_rules! tuple {
3076    () => ();
3077    ( $($name:ident,)+ ) => (
3078        maybe_tuple_doc! {
3079            $($name)+ @
3080            #[stable(feature = "rust1", since = "1.0.0")]
3081            impl<$($name:Debug),+> Debug for ($($name,)+) {
3082                #[allow(non_snake_case, unused_assignments)]
3083                fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3084                    let mut builder = f.debug_tuple("");
3085                    let ($(ref $name,)+) = *self;
3086                    $(
3087                        builder.field(&$name);
3088                    )+
3089
3090                    builder.finish()
3091                }
3092            }
3093        }
3094        peel! { $($name,)+ }
3095    )
3096}
3097
3098macro_rules! maybe_tuple_doc {
3099    ($a:ident @ #[$meta:meta] $item:item) => {
3100        #[doc(fake_variadic)]
3101        #[doc = "This trait is implemented for tuples up to twelve items long."]
3102        #[$meta]
3103        $item
3104    };
3105    ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
3106        #[doc(hidden)]
3107        #[$meta]
3108        $item
3109    };
3110}
3111
3112tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
3113
3114#[stable(feature = "rust1", since = "1.0.0")]
3115impl<T: Debug> Debug for [T] {
3116    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3117        f.debug_list().entries(self.iter()).finish()
3118    }
3119}
3120
3121#[stable(feature = "rust1", since = "1.0.0")]
3122impl Debug for () {
3123    #[inline]
3124    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3125        f.pad("()")
3126    }
3127}
3128#[stable(feature = "rust1", since = "1.0.0")]
3129impl<T: ?Sized> Debug for PhantomData<T> {
3130    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3131        write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
3132    }
3133}
3134
3135#[stable(feature = "rust1", since = "1.0.0")]
3136impl<T: Copy + Debug> Debug for Cell<T> {
3137    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3138        f.debug_struct("Cell").field("value", &self.get()).finish()
3139    }
3140}
3141
3142#[stable(feature = "rust1", since = "1.0.0")]
3143impl<T: ?Sized + Debug> Debug for RefCell<T> {
3144    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3145        let mut d = f.debug_struct("RefCell");
3146        match self.try_borrow() {
3147            Ok(borrow) => d.field("value", &borrow),
3148            Err(_) => d.field("value", &format_args!("<borrowed>")),
3149        };
3150        d.finish()
3151    }
3152}
3153
3154#[stable(feature = "rust1", since = "1.0.0")]
3155impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
3156    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3157        Debug::fmt(&**self, f)
3158    }
3159}
3160
3161#[stable(feature = "rust1", since = "1.0.0")]
3162impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
3163    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3164        Debug::fmt(&*(self.deref()), f)
3165    }
3166}
3167
3168#[stable(feature = "core_impl_debug", since = "1.9.0")]
3169impl<T: ?Sized> Debug for UnsafeCell<T> {
3170    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3171        f.debug_struct("UnsafeCell").finish_non_exhaustive()
3172    }
3173}
3174
3175#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
3176impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
3177    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3178        f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
3179    }
3180}
3181
3182// If you expected tests to be here, look instead at coretests/tests/fmt/;
3183// it's a lot easier than creating all of the rt::Piece structures here.
3184// There are also tests in alloctests/tests/fmt.rs, for those that need allocations.