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