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