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, MAX_LEN_UTF8};
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; MAX_LEN_UTF8]))
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<u16>,
298    precision: Option<u16>,
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<u16>) -> &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<u16>) -> &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<u16> {
459        self.width
460    }
461    /// Returns the current precision.
462    #[unstable(feature = "formatting_options", issue = "118117")]
463    pub const fn get_precision(&self) -> Option<u16> {
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<u16> {
1503    match *cnt {
1504        #[cfg(bootstrap)]
1505        rt::Count::Is(n) => Some(n as u16),
1506        #[cfg(not(bootstrap))]
1507        rt::Count::Is(n) => Some(n),
1508        rt::Count::Implied => None,
1509        rt::Count::Param(i) => {
1510            debug_assert!(i < args.len());
1511            // SAFETY: cnt and args come from the same Arguments,
1512            // which guarantees this index is always within bounds.
1513            unsafe { args.get_unchecked(i).as_u16() }
1514        }
1515    }
1516}
1517
1518/// Padding after the end of something. Returned by `Formatter::padding`.
1519#[must_use = "don't forget to write the post padding"]
1520pub(crate) struct PostPadding {
1521    fill: char,
1522    padding: u16,
1523}
1524
1525impl PostPadding {
1526    fn new(fill: char, padding: u16) -> PostPadding {
1527        PostPadding { fill, padding }
1528    }
1529
1530    /// Writes this post padding.
1531    pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1532        for _ in 0..self.padding {
1533            f.buf.write_char(self.fill)?;
1534        }
1535        Ok(())
1536    }
1537}
1538
1539impl<'a> Formatter<'a> {
1540    fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1541    where
1542        'b: 'c,
1543        F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1544    {
1545        Formatter {
1546            // We want to change this
1547            buf: wrap(self.buf),
1548
1549            // And preserve these
1550            options: self.options,
1551        }
1552    }
1553
1554    // Helper methods used for padding and processing formatting arguments that
1555    // all formatting traits can use.
1556
1557    /// Performs the correct padding for an integer which has already been
1558    /// emitted into a str. The str should *not* contain the sign for the
1559    /// integer, that will be added by this method.
1560    ///
1561    /// # Arguments
1562    ///
1563    /// * is_nonnegative - whether the original integer was either positive or zero.
1564    /// * prefix - if the '#' character (Alternate) is provided, this
1565    ///   is the prefix to put in front of the number.
1566    /// * buf - the byte array that the number has been formatted into
1567    ///
1568    /// This function will correctly account for the flags provided as well as
1569    /// the minimum width. It will not take precision into account.
1570    ///
1571    /// # Examples
1572    ///
1573    /// ```
1574    /// use std::fmt;
1575    ///
1576    /// struct Foo { nb: i32 }
1577    ///
1578    /// impl Foo {
1579    ///     fn new(nb: i32) -> Foo {
1580    ///         Foo {
1581    ///             nb,
1582    ///         }
1583    ///     }
1584    /// }
1585    ///
1586    /// impl fmt::Display for Foo {
1587    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1588    ///         // We need to remove "-" from the number output.
1589    ///         let tmp = self.nb.abs().to_string();
1590    ///
1591    ///         formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1592    ///     }
1593    /// }
1594    ///
1595    /// assert_eq!(format!("{}", Foo::new(2)), "2");
1596    /// assert_eq!(format!("{}", Foo::new(-1)), "-1");
1597    /// assert_eq!(format!("{}", Foo::new(0)), "0");
1598    /// assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
1599    /// assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1600    /// ```
1601    #[stable(feature = "rust1", since = "1.0.0")]
1602    pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1603        let mut width = buf.len();
1604
1605        let mut sign = None;
1606        if !is_nonnegative {
1607            sign = Some('-');
1608            width += 1;
1609        } else if self.sign_plus() {
1610            sign = Some('+');
1611            width += 1;
1612        }
1613
1614        let prefix = if self.alternate() {
1615            width += prefix.chars().count();
1616            Some(prefix)
1617        } else {
1618            None
1619        };
1620
1621        // Writes the sign if it exists, and then the prefix if it was requested
1622        #[inline(never)]
1623        fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1624            if let Some(c) = sign {
1625                f.buf.write_char(c)?;
1626            }
1627            if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1628        }
1629
1630        // The `width` field is more of a `min-width` parameter at this point.
1631        match self.options.width {
1632            // If there's no minimum length requirements then we can just
1633            // write the bytes.
1634            None => {
1635                write_prefix(self, sign, prefix)?;
1636                self.buf.write_str(buf)
1637            }
1638            // Check if we're over the minimum width, if so then we can also
1639            // just write the bytes.
1640            Some(min) if width >= usize::from(min) => {
1641                write_prefix(self, sign, prefix)?;
1642                self.buf.write_str(buf)
1643            }
1644            // The sign and prefix goes before the padding if the fill character
1645            // is zero
1646            Some(min) if self.sign_aware_zero_pad() => {
1647                let old_fill = crate::mem::replace(&mut self.options.fill, '0');
1648                let old_align =
1649                    crate::mem::replace(&mut self.options.align, Some(Alignment::Right));
1650                write_prefix(self, sign, prefix)?;
1651                let post_padding = self.padding(min - width as u16, Alignment::Right)?;
1652                self.buf.write_str(buf)?;
1653                post_padding.write(self)?;
1654                self.options.fill = old_fill;
1655                self.options.align = old_align;
1656                Ok(())
1657            }
1658            // Otherwise, the sign and prefix goes after the padding
1659            Some(min) => {
1660                let post_padding = self.padding(min - width as u16, Alignment::Right)?;
1661                write_prefix(self, sign, prefix)?;
1662                self.buf.write_str(buf)?;
1663                post_padding.write(self)
1664            }
1665        }
1666    }
1667
1668    /// Takes a string slice and emits it to the internal buffer after applying
1669    /// the relevant formatting flags specified.
1670    ///
1671    /// The flags recognized for generic strings are:
1672    ///
1673    /// * width - the minimum width of what to emit
1674    /// * fill/align - what to emit and where to emit it if the string
1675    ///                provided needs to be padded
1676    /// * precision - the maximum length to emit, the string is truncated if it
1677    ///               is longer than this length
1678    ///
1679    /// Notably this function ignores the `flag` parameters.
1680    ///
1681    /// # Examples
1682    ///
1683    /// ```
1684    /// use std::fmt;
1685    ///
1686    /// struct Foo;
1687    ///
1688    /// impl fmt::Display for Foo {
1689    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1690    ///         formatter.pad("Foo")
1691    ///     }
1692    /// }
1693    ///
1694    /// assert_eq!(format!("{Foo:<4}"), "Foo ");
1695    /// assert_eq!(format!("{Foo:0>4}"), "0Foo");
1696    /// ```
1697    #[stable(feature = "rust1", since = "1.0.0")]
1698    pub fn pad(&mut self, s: &str) -> Result {
1699        // Make sure there's a fast path up front.
1700        if self.options.width.is_none() && self.options.precision.is_none() {
1701            return self.buf.write_str(s);
1702        }
1703
1704        // The `precision` field can be interpreted as a maximum width for the
1705        // string being formatted.
1706        let (s, char_count) = if let Some(max_char_count) = self.options.precision {
1707            let mut iter = s.char_indices();
1708            let remaining = match iter.advance_by(usize::from(max_char_count)) {
1709                Ok(()) => 0,
1710                Err(remaining) => remaining.get(),
1711            };
1712            // SAFETY: The offset of `.char_indices()` is guaranteed to be
1713            // in-bounds and between character boundaries.
1714            let truncated = unsafe { s.get_unchecked(..iter.offset()) };
1715            (truncated, usize::from(max_char_count) - remaining)
1716        } else {
1717            // Use the optimized char counting algorithm for the full string.
1718            (s, s.chars().count())
1719        };
1720
1721        // The `width` field is more of a minimum width parameter at this point.
1722        if let Some(width) = self.options.width
1723            && char_count < usize::from(width)
1724        {
1725            // If we're under the minimum width, then fill up the minimum width
1726            // with the specified string + some alignment.
1727            let post_padding = self.padding(width - char_count as u16, Alignment::Left)?;
1728            self.buf.write_str(s)?;
1729            post_padding.write(self)
1730        } else {
1731            // If we're over the minimum width or there is no minimum width, we
1732            // can just emit the string.
1733            self.buf.write_str(s)
1734        }
1735    }
1736
1737    /// Writes the pre-padding and returns the unwritten post-padding.
1738    ///
1739    /// Callers are responsible for ensuring post-padding is written after the
1740    /// thing that is being padded.
1741    pub(crate) fn padding(
1742        &mut self,
1743        padding: u16,
1744        default: Alignment,
1745    ) -> result::Result<PostPadding, Error> {
1746        let align = self.align().unwrap_or(default);
1747
1748        let (pre_pad, post_pad) = match align {
1749            Alignment::Left => (0, padding),
1750            Alignment::Right => (padding, 0),
1751            Alignment::Center => (padding / 2, (padding + 1) / 2),
1752        };
1753
1754        for _ in 0..pre_pad {
1755            self.buf.write_char(self.options.fill)?;
1756        }
1757
1758        Ok(PostPadding::new(self.options.fill, post_pad))
1759    }
1760
1761    /// Takes the formatted parts and applies the padding.
1762    ///
1763    /// Assumes that the caller already has rendered the parts with required precision,
1764    /// so that `self.precision` can be ignored.
1765    ///
1766    /// # Safety
1767    ///
1768    /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
1769    unsafe fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1770        if let Some(mut width) = self.options.width {
1771            // for the sign-aware zero padding, we render the sign first and
1772            // behave as if we had no sign from the beginning.
1773            let mut formatted = formatted.clone();
1774            let old_fill = self.options.fill;
1775            let old_align = self.options.align;
1776            if self.sign_aware_zero_pad() {
1777                // a sign always goes first
1778                let sign = formatted.sign;
1779                self.buf.write_str(sign)?;
1780
1781                // remove the sign from the formatted parts
1782                formatted.sign = "";
1783                width = width.saturating_sub(sign.len() as u16);
1784                self.options.fill = '0';
1785                self.options.align = Some(Alignment::Right);
1786            }
1787
1788            // remaining parts go through the ordinary padding process.
1789            let len = formatted.len();
1790            let ret = if usize::from(width) <= len {
1791                // no padding
1792                // SAFETY: Per the precondition.
1793                unsafe { self.write_formatted_parts(&formatted) }
1794            } else {
1795                let post_padding = self.padding(width - len as u16, Alignment::Right)?;
1796                // SAFETY: Per the precondition.
1797                unsafe {
1798                    self.write_formatted_parts(&formatted)?;
1799                }
1800                post_padding.write(self)
1801            };
1802            self.options.fill = old_fill;
1803            self.options.align = old_align;
1804            ret
1805        } else {
1806            // this is the common case and we take a shortcut
1807            // SAFETY: Per the precondition.
1808            unsafe { self.write_formatted_parts(formatted) }
1809        }
1810    }
1811
1812    /// # Safety
1813    ///
1814    /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
1815    unsafe fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1816        unsafe fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1817            // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1818            // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1819            // `b'0'` and `b'9'`, which means `s` is valid UTF-8. It's safe to use for
1820            // `numfmt::Part::Copy` due to this function's precondition.
1821            buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1822        }
1823
1824        if !formatted.sign.is_empty() {
1825            self.buf.write_str(formatted.sign)?;
1826        }
1827        for part in formatted.parts {
1828            match *part {
1829                numfmt::Part::Zero(mut nzeroes) => {
1830                    const ZEROES: &str = // 64 zeroes
1831                        "0000000000000000000000000000000000000000000000000000000000000000";
1832                    while nzeroes > ZEROES.len() {
1833                        self.buf.write_str(ZEROES)?;
1834                        nzeroes -= ZEROES.len();
1835                    }
1836                    if nzeroes > 0 {
1837                        self.buf.write_str(&ZEROES[..nzeroes])?;
1838                    }
1839                }
1840                numfmt::Part::Num(mut v) => {
1841                    let mut s = [0; 5];
1842                    let len = part.len();
1843                    for c in s[..len].iter_mut().rev() {
1844                        *c = b'0' + (v % 10) as u8;
1845                        v /= 10;
1846                    }
1847                    // SAFETY: Per the precondition.
1848                    unsafe {
1849                        write_bytes(self.buf, &s[..len])?;
1850                    }
1851                }
1852                // SAFETY: Per the precondition.
1853                numfmt::Part::Copy(buf) => unsafe {
1854                    write_bytes(self.buf, buf)?;
1855                },
1856            }
1857        }
1858        Ok(())
1859    }
1860
1861    /// Writes some data to the underlying buffer contained within this
1862    /// formatter.
1863    ///
1864    /// # Examples
1865    ///
1866    /// ```
1867    /// use std::fmt;
1868    ///
1869    /// struct Foo;
1870    ///
1871    /// impl fmt::Display for Foo {
1872    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1873    ///         formatter.write_str("Foo")
1874    ///         // This is equivalent to:
1875    ///         // write!(formatter, "Foo")
1876    ///     }
1877    /// }
1878    ///
1879    /// assert_eq!(format!("{Foo}"), "Foo");
1880    /// assert_eq!(format!("{Foo:0>8}"), "Foo");
1881    /// ```
1882    #[stable(feature = "rust1", since = "1.0.0")]
1883    pub fn write_str(&mut self, data: &str) -> Result {
1884        self.buf.write_str(data)
1885    }
1886
1887    /// Glue for usage of the [`write!`] macro with implementors of this trait.
1888    ///
1889    /// This method should generally not be invoked manually, but rather through
1890    /// the [`write!`] macro itself.
1891    ///
1892    /// Writes some formatted information into this instance.
1893    ///
1894    /// # Examples
1895    ///
1896    /// ```
1897    /// use std::fmt;
1898    ///
1899    /// struct Foo(i32);
1900    ///
1901    /// impl fmt::Display for Foo {
1902    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1903    ///         formatter.write_fmt(format_args!("Foo {}", self.0))
1904    ///     }
1905    /// }
1906    ///
1907    /// assert_eq!(format!("{}", Foo(-1)), "Foo -1");
1908    /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
1909    /// ```
1910    #[stable(feature = "rust1", since = "1.0.0")]
1911    #[inline]
1912    pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1913        if let Some(s) = fmt.as_statically_known_str() {
1914            self.buf.write_str(s)
1915        } else {
1916            write(self.buf, fmt)
1917        }
1918    }
1919
1920    /// Returns flags for formatting.
1921    #[must_use]
1922    #[stable(feature = "rust1", since = "1.0.0")]
1923    #[deprecated(
1924        since = "1.24.0",
1925        note = "use the `sign_plus`, `sign_minus`, `alternate`, \
1926                or `sign_aware_zero_pad` methods instead"
1927    )]
1928    pub fn flags(&self) -> u32 {
1929        self.options.flags
1930    }
1931
1932    /// Returns the character used as 'fill' whenever there is alignment.
1933    ///
1934    /// # Examples
1935    ///
1936    /// ```
1937    /// use std::fmt;
1938    ///
1939    /// struct Foo;
1940    ///
1941    /// impl fmt::Display for Foo {
1942    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1943    ///         let c = formatter.fill();
1944    ///         if let Some(width) = formatter.width() {
1945    ///             for _ in 0..width {
1946    ///                 write!(formatter, "{c}")?;
1947    ///             }
1948    ///             Ok(())
1949    ///         } else {
1950    ///             write!(formatter, "{c}")
1951    ///         }
1952    ///     }
1953    /// }
1954    ///
1955    /// // We set alignment to the right with ">".
1956    /// assert_eq!(format!("{Foo:G>3}"), "GGG");
1957    /// assert_eq!(format!("{Foo:t>6}"), "tttttt");
1958    /// ```
1959    #[must_use]
1960    #[stable(feature = "fmt_flags", since = "1.5.0")]
1961    pub fn fill(&self) -> char {
1962        self.options.fill
1963    }
1964
1965    /// Returns a flag indicating what form of alignment was requested.
1966    ///
1967    /// # Examples
1968    ///
1969    /// ```
1970    /// use std::fmt::{self, Alignment};
1971    ///
1972    /// struct Foo;
1973    ///
1974    /// impl fmt::Display for Foo {
1975    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1976    ///         let s = if let Some(s) = formatter.align() {
1977    ///             match s {
1978    ///                 Alignment::Left    => "left",
1979    ///                 Alignment::Right   => "right",
1980    ///                 Alignment::Center  => "center",
1981    ///             }
1982    ///         } else {
1983    ///             "into the void"
1984    ///         };
1985    ///         write!(formatter, "{s}")
1986    ///     }
1987    /// }
1988    ///
1989    /// assert_eq!(format!("{Foo:<}"), "left");
1990    /// assert_eq!(format!("{Foo:>}"), "right");
1991    /// assert_eq!(format!("{Foo:^}"), "center");
1992    /// assert_eq!(format!("{Foo}"), "into the void");
1993    /// ```
1994    #[must_use]
1995    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1996    pub fn align(&self) -> Option<Alignment> {
1997        self.options.align
1998    }
1999
2000    /// Returns the optionally specified integer width that the output should be.
2001    ///
2002    /// # Examples
2003    ///
2004    /// ```
2005    /// use std::fmt;
2006    ///
2007    /// struct Foo(i32);
2008    ///
2009    /// impl fmt::Display for Foo {
2010    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2011    ///         if let Some(width) = formatter.width() {
2012    ///             // If we received a width, we use it
2013    ///             write!(formatter, "{:width$}", format!("Foo({})", self.0), width = width)
2014    ///         } else {
2015    ///             // Otherwise we do nothing special
2016    ///             write!(formatter, "Foo({})", self.0)
2017    ///         }
2018    ///     }
2019    /// }
2020    ///
2021    /// assert_eq!(format!("{:10}", Foo(23)), "Foo(23)   ");
2022    /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2023    /// ```
2024    #[must_use]
2025    #[stable(feature = "fmt_flags", since = "1.5.0")]
2026    pub fn width(&self) -> Option<usize> {
2027        self.options.width.map(|x| x as usize)
2028    }
2029
2030    /// Returns the optionally specified precision for numeric types.
2031    /// Alternatively, the maximum width for string types.
2032    ///
2033    /// # Examples
2034    ///
2035    /// ```
2036    /// use std::fmt;
2037    ///
2038    /// struct Foo(f32);
2039    ///
2040    /// impl fmt::Display for Foo {
2041    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2042    ///         if let Some(precision) = formatter.precision() {
2043    ///             // If we received a precision, we use it.
2044    ///             write!(formatter, "Foo({1:.*})", precision, self.0)
2045    ///         } else {
2046    ///             // Otherwise we default to 2.
2047    ///             write!(formatter, "Foo({:.2})", self.0)
2048    ///         }
2049    ///     }
2050    /// }
2051    ///
2052    /// assert_eq!(format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
2053    /// assert_eq!(format!("{}", Foo(23.2)), "Foo(23.20)");
2054    /// ```
2055    #[must_use]
2056    #[stable(feature = "fmt_flags", since = "1.5.0")]
2057    pub fn precision(&self) -> Option<usize> {
2058        self.options.precision.map(|x| x as usize)
2059    }
2060
2061    /// Determines if the `+` flag was specified.
2062    ///
2063    /// # Examples
2064    ///
2065    /// ```
2066    /// use std::fmt;
2067    ///
2068    /// struct Foo(i32);
2069    ///
2070    /// impl fmt::Display for Foo {
2071    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2072    ///         if formatter.sign_plus() {
2073    ///             write!(formatter,
2074    ///                    "Foo({}{})",
2075    ///                    if self.0 < 0 { '-' } else { '+' },
2076    ///                    self.0.abs())
2077    ///         } else {
2078    ///             write!(formatter, "Foo({})", self.0)
2079    ///         }
2080    ///     }
2081    /// }
2082    ///
2083    /// assert_eq!(format!("{:+}", Foo(23)), "Foo(+23)");
2084    /// assert_eq!(format!("{:+}", Foo(-23)), "Foo(-23)");
2085    /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2086    /// ```
2087    #[must_use]
2088    #[stable(feature = "fmt_flags", since = "1.5.0")]
2089    pub fn sign_plus(&self) -> bool {
2090        self.options.flags & (1 << rt::Flag::SignPlus as u32) != 0
2091    }
2092
2093    /// Determines if the `-` flag was specified.
2094    ///
2095    /// # Examples
2096    ///
2097    /// ```
2098    /// use std::fmt;
2099    ///
2100    /// struct Foo(i32);
2101    ///
2102    /// impl fmt::Display for Foo {
2103    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2104    ///         if formatter.sign_minus() {
2105    ///             // You want a minus sign? Have one!
2106    ///             write!(formatter, "-Foo({})", self.0)
2107    ///         } else {
2108    ///             write!(formatter, "Foo({})", self.0)
2109    ///         }
2110    ///     }
2111    /// }
2112    ///
2113    /// assert_eq!(format!("{:-}", Foo(23)), "-Foo(23)");
2114    /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2115    /// ```
2116    #[must_use]
2117    #[stable(feature = "fmt_flags", since = "1.5.0")]
2118    pub fn sign_minus(&self) -> bool {
2119        self.options.flags & (1 << rt::Flag::SignMinus as u32) != 0
2120    }
2121
2122    /// Determines if the `#` flag was specified.
2123    ///
2124    /// # Examples
2125    ///
2126    /// ```
2127    /// use std::fmt;
2128    ///
2129    /// struct Foo(i32);
2130    ///
2131    /// impl fmt::Display for Foo {
2132    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2133    ///         if formatter.alternate() {
2134    ///             write!(formatter, "Foo({})", self.0)
2135    ///         } else {
2136    ///             write!(formatter, "{}", self.0)
2137    ///         }
2138    ///     }
2139    /// }
2140    ///
2141    /// assert_eq!(format!("{:#}", Foo(23)), "Foo(23)");
2142    /// assert_eq!(format!("{}", Foo(23)), "23");
2143    /// ```
2144    #[must_use]
2145    #[stable(feature = "fmt_flags", since = "1.5.0")]
2146    pub fn alternate(&self) -> bool {
2147        self.options.flags & (1 << rt::Flag::Alternate as u32) != 0
2148    }
2149
2150    /// Determines if the `0` flag was specified.
2151    ///
2152    /// # Examples
2153    ///
2154    /// ```
2155    /// use std::fmt;
2156    ///
2157    /// struct Foo(i32);
2158    ///
2159    /// impl fmt::Display for Foo {
2160    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2161    ///         assert!(formatter.sign_aware_zero_pad());
2162    ///         assert_eq!(formatter.width(), Some(4));
2163    ///         // We ignore the formatter's options.
2164    ///         write!(formatter, "{}", self.0)
2165    ///     }
2166    /// }
2167    ///
2168    /// assert_eq!(format!("{:04}", Foo(23)), "23");
2169    /// ```
2170    #[must_use]
2171    #[stable(feature = "fmt_flags", since = "1.5.0")]
2172    pub fn sign_aware_zero_pad(&self) -> bool {
2173        self.options.flags & (1 << rt::Flag::SignAwareZeroPad as u32) != 0
2174    }
2175
2176    // FIXME: Decide what public API we want for these two flags.
2177    // https://github.com/rust-lang/rust/issues/48584
2178    fn debug_lower_hex(&self) -> bool {
2179        self.options.flags & (1 << rt::Flag::DebugLowerHex as u32) != 0
2180    }
2181
2182    fn debug_upper_hex(&self) -> bool {
2183        self.options.flags & (1 << rt::Flag::DebugUpperHex as u32) != 0
2184    }
2185
2186    /// Creates a [`DebugStruct`] builder designed to assist with creation of
2187    /// [`fmt::Debug`] implementations for structs.
2188    ///
2189    /// [`fmt::Debug`]: self::Debug
2190    ///
2191    /// # Examples
2192    ///
2193    /// ```rust
2194    /// use std::fmt;
2195    /// use std::net::Ipv4Addr;
2196    ///
2197    /// struct Foo {
2198    ///     bar: i32,
2199    ///     baz: String,
2200    ///     addr: Ipv4Addr,
2201    /// }
2202    ///
2203    /// impl fmt::Debug for Foo {
2204    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2205    ///         fmt.debug_struct("Foo")
2206    ///             .field("bar", &self.bar)
2207    ///             .field("baz", &self.baz)
2208    ///             .field("addr", &format_args!("{}", self.addr))
2209    ///             .finish()
2210    ///     }
2211    /// }
2212    ///
2213    /// assert_eq!(
2214    ///     "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
2215    ///     format!("{:?}", Foo {
2216    ///         bar: 10,
2217    ///         baz: "Hello World".to_string(),
2218    ///         addr: Ipv4Addr::new(127, 0, 0, 1),
2219    ///     })
2220    /// );
2221    /// ```
2222    #[stable(feature = "debug_builders", since = "1.2.0")]
2223    pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
2224        builders::debug_struct_new(self, name)
2225    }
2226
2227    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2228    /// binaries. `debug_struct_fields_finish` is more general, but this is
2229    /// faster for 1 field.
2230    #[doc(hidden)]
2231    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2232    pub fn debug_struct_field1_finish<'b>(
2233        &'b mut self,
2234        name: &str,
2235        name1: &str,
2236        value1: &dyn Debug,
2237    ) -> Result {
2238        let mut builder = builders::debug_struct_new(self, name);
2239        builder.field(name1, value1);
2240        builder.finish()
2241    }
2242
2243    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2244    /// binaries. `debug_struct_fields_finish` is more general, but this is
2245    /// faster for 2 fields.
2246    #[doc(hidden)]
2247    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2248    pub fn debug_struct_field2_finish<'b>(
2249        &'b mut self,
2250        name: &str,
2251        name1: &str,
2252        value1: &dyn Debug,
2253        name2: &str,
2254        value2: &dyn Debug,
2255    ) -> Result {
2256        let mut builder = builders::debug_struct_new(self, name);
2257        builder.field(name1, value1);
2258        builder.field(name2, value2);
2259        builder.finish()
2260    }
2261
2262    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2263    /// binaries. `debug_struct_fields_finish` is more general, but this is
2264    /// faster for 3 fields.
2265    #[doc(hidden)]
2266    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2267    pub fn debug_struct_field3_finish<'b>(
2268        &'b mut self,
2269        name: &str,
2270        name1: &str,
2271        value1: &dyn Debug,
2272        name2: &str,
2273        value2: &dyn Debug,
2274        name3: &str,
2275        value3: &dyn Debug,
2276    ) -> Result {
2277        let mut builder = builders::debug_struct_new(self, name);
2278        builder.field(name1, value1);
2279        builder.field(name2, value2);
2280        builder.field(name3, value3);
2281        builder.finish()
2282    }
2283
2284    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2285    /// binaries. `debug_struct_fields_finish` is more general, but this is
2286    /// faster for 4 fields.
2287    #[doc(hidden)]
2288    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2289    pub fn debug_struct_field4_finish<'b>(
2290        &'b mut self,
2291        name: &str,
2292        name1: &str,
2293        value1: &dyn Debug,
2294        name2: &str,
2295        value2: &dyn Debug,
2296        name3: &str,
2297        value3: &dyn Debug,
2298        name4: &str,
2299        value4: &dyn Debug,
2300    ) -> Result {
2301        let mut builder = builders::debug_struct_new(self, name);
2302        builder.field(name1, value1);
2303        builder.field(name2, value2);
2304        builder.field(name3, value3);
2305        builder.field(name4, value4);
2306        builder.finish()
2307    }
2308
2309    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2310    /// binaries. `debug_struct_fields_finish` is more general, but this is
2311    /// faster for 5 fields.
2312    #[doc(hidden)]
2313    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2314    pub fn debug_struct_field5_finish<'b>(
2315        &'b mut self,
2316        name: &str,
2317        name1: &str,
2318        value1: &dyn Debug,
2319        name2: &str,
2320        value2: &dyn Debug,
2321        name3: &str,
2322        value3: &dyn Debug,
2323        name4: &str,
2324        value4: &dyn Debug,
2325        name5: &str,
2326        value5: &dyn Debug,
2327    ) -> Result {
2328        let mut builder = builders::debug_struct_new(self, name);
2329        builder.field(name1, value1);
2330        builder.field(name2, value2);
2331        builder.field(name3, value3);
2332        builder.field(name4, value4);
2333        builder.field(name5, value5);
2334        builder.finish()
2335    }
2336
2337    /// Shrinks `derive(Debug)` code, for faster compilation and smaller binaries.
2338    /// For the cases not covered by `debug_struct_field[12345]_finish`.
2339    #[doc(hidden)]
2340    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2341    pub fn debug_struct_fields_finish<'b>(
2342        &'b mut self,
2343        name: &str,
2344        names: &[&str],
2345        values: &[&dyn Debug],
2346    ) -> Result {
2347        assert_eq!(names.len(), values.len());
2348        let mut builder = builders::debug_struct_new(self, name);
2349        for (name, value) in iter::zip(names, values) {
2350            builder.field(name, value);
2351        }
2352        builder.finish()
2353    }
2354
2355    /// Creates a `DebugTuple` builder designed to assist with creation of
2356    /// `fmt::Debug` implementations for tuple structs.
2357    ///
2358    /// # Examples
2359    ///
2360    /// ```rust
2361    /// use std::fmt;
2362    /// use std::marker::PhantomData;
2363    ///
2364    /// struct Foo<T>(i32, String, PhantomData<T>);
2365    ///
2366    /// impl<T> fmt::Debug for Foo<T> {
2367    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2368    ///         fmt.debug_tuple("Foo")
2369    ///             .field(&self.0)
2370    ///             .field(&self.1)
2371    ///             .field(&format_args!("_"))
2372    ///             .finish()
2373    ///     }
2374    /// }
2375    ///
2376    /// assert_eq!(
2377    ///     "Foo(10, \"Hello\", _)",
2378    ///     format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
2379    /// );
2380    /// ```
2381    #[stable(feature = "debug_builders", since = "1.2.0")]
2382    pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
2383        builders::debug_tuple_new(self, name)
2384    }
2385
2386    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2387    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2388    /// for 1 field.
2389    #[doc(hidden)]
2390    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2391    pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result {
2392        let mut builder = builders::debug_tuple_new(self, name);
2393        builder.field(value1);
2394        builder.finish()
2395    }
2396
2397    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2398    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2399    /// for 2 fields.
2400    #[doc(hidden)]
2401    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2402    pub fn debug_tuple_field2_finish<'b>(
2403        &'b mut self,
2404        name: &str,
2405        value1: &dyn Debug,
2406        value2: &dyn Debug,
2407    ) -> Result {
2408        let mut builder = builders::debug_tuple_new(self, name);
2409        builder.field(value1);
2410        builder.field(value2);
2411        builder.finish()
2412    }
2413
2414    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2415    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2416    /// for 3 fields.
2417    #[doc(hidden)]
2418    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2419    pub fn debug_tuple_field3_finish<'b>(
2420        &'b mut self,
2421        name: &str,
2422        value1: &dyn Debug,
2423        value2: &dyn Debug,
2424        value3: &dyn Debug,
2425    ) -> Result {
2426        let mut builder = builders::debug_tuple_new(self, name);
2427        builder.field(value1);
2428        builder.field(value2);
2429        builder.field(value3);
2430        builder.finish()
2431    }
2432
2433    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2434    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2435    /// for 4 fields.
2436    #[doc(hidden)]
2437    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2438    pub fn debug_tuple_field4_finish<'b>(
2439        &'b mut self,
2440        name: &str,
2441        value1: &dyn Debug,
2442        value2: &dyn Debug,
2443        value3: &dyn Debug,
2444        value4: &dyn Debug,
2445    ) -> Result {
2446        let mut builder = builders::debug_tuple_new(self, name);
2447        builder.field(value1);
2448        builder.field(value2);
2449        builder.field(value3);
2450        builder.field(value4);
2451        builder.finish()
2452    }
2453
2454    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2455    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2456    /// for 5 fields.
2457    #[doc(hidden)]
2458    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2459    pub fn debug_tuple_field5_finish<'b>(
2460        &'b mut self,
2461        name: &str,
2462        value1: &dyn Debug,
2463        value2: &dyn Debug,
2464        value3: &dyn Debug,
2465        value4: &dyn Debug,
2466        value5: &dyn Debug,
2467    ) -> Result {
2468        let mut builder = builders::debug_tuple_new(self, name);
2469        builder.field(value1);
2470        builder.field(value2);
2471        builder.field(value3);
2472        builder.field(value4);
2473        builder.field(value5);
2474        builder.finish()
2475    }
2476
2477    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2478    /// binaries. For the cases not covered by `debug_tuple_field[12345]_finish`.
2479    #[doc(hidden)]
2480    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2481    pub fn debug_tuple_fields_finish<'b>(
2482        &'b mut self,
2483        name: &str,
2484        values: &[&dyn Debug],
2485    ) -> Result {
2486        let mut builder = builders::debug_tuple_new(self, name);
2487        for value in values {
2488            builder.field(value);
2489        }
2490        builder.finish()
2491    }
2492
2493    /// Creates a `DebugList` builder designed to assist with creation of
2494    /// `fmt::Debug` implementations for list-like structures.
2495    ///
2496    /// # Examples
2497    ///
2498    /// ```rust
2499    /// use std::fmt;
2500    ///
2501    /// struct Foo(Vec<i32>);
2502    ///
2503    /// impl fmt::Debug for Foo {
2504    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2505    ///         fmt.debug_list().entries(self.0.iter()).finish()
2506    ///     }
2507    /// }
2508    ///
2509    /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2510    /// ```
2511    #[stable(feature = "debug_builders", since = "1.2.0")]
2512    pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2513        builders::debug_list_new(self)
2514    }
2515
2516    /// Creates a `DebugSet` builder designed to assist with creation of
2517    /// `fmt::Debug` implementations for set-like structures.
2518    ///
2519    /// # Examples
2520    ///
2521    /// ```rust
2522    /// use std::fmt;
2523    ///
2524    /// struct Foo(Vec<i32>);
2525    ///
2526    /// impl fmt::Debug for Foo {
2527    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2528    ///         fmt.debug_set().entries(self.0.iter()).finish()
2529    ///     }
2530    /// }
2531    ///
2532    /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2533    /// ```
2534    ///
2535    /// [`format_args!`]: crate::format_args
2536    ///
2537    /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2538    /// to build a list of match arms:
2539    ///
2540    /// ```rust
2541    /// use std::fmt;
2542    ///
2543    /// struct Arm<'a, L, R>(&'a (L, R));
2544    /// struct Table<'a, K, V>(&'a [(K, V)], V);
2545    ///
2546    /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2547    /// where
2548    ///     L: 'a + fmt::Debug, R: 'a + fmt::Debug
2549    /// {
2550    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2551    ///         L::fmt(&(self.0).0, fmt)?;
2552    ///         fmt.write_str(" => ")?;
2553    ///         R::fmt(&(self.0).1, fmt)
2554    ///     }
2555    /// }
2556    ///
2557    /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2558    /// where
2559    ///     K: 'a + fmt::Debug, V: 'a + fmt::Debug
2560    /// {
2561    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2562    ///         fmt.debug_set()
2563    ///         .entries(self.0.iter().map(Arm))
2564    ///         .entry(&Arm(&(format_args!("_"), &self.1)))
2565    ///         .finish()
2566    ///     }
2567    /// }
2568    /// ```
2569    #[stable(feature = "debug_builders", since = "1.2.0")]
2570    pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2571        builders::debug_set_new(self)
2572    }
2573
2574    /// Creates a `DebugMap` builder designed to assist with creation of
2575    /// `fmt::Debug` implementations for map-like structures.
2576    ///
2577    /// # Examples
2578    ///
2579    /// ```rust
2580    /// use std::fmt;
2581    ///
2582    /// struct Foo(Vec<(String, i32)>);
2583    ///
2584    /// impl fmt::Debug for Foo {
2585    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2586    ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2587    ///     }
2588    /// }
2589    ///
2590    /// assert_eq!(
2591    ///     format!("{:?}",  Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2592    ///     r#"{"A": 10, "B": 11}"#
2593    ///  );
2594    /// ```
2595    #[stable(feature = "debug_builders", since = "1.2.0")]
2596    pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2597        builders::debug_map_new(self)
2598    }
2599
2600    /// Returns the sign of this formatter (`+` or `-`).
2601    #[unstable(feature = "formatting_options", issue = "118117")]
2602    pub const fn sign(&self) -> Option<Sign> {
2603        self.options.get_sign()
2604    }
2605
2606    /// Returns the formatting options this formatter corresponds to.
2607    #[unstable(feature = "formatting_options", issue = "118117")]
2608    pub const fn options(&self) -> FormattingOptions {
2609        self.options
2610    }
2611}
2612
2613#[stable(since = "1.2.0", feature = "formatter_write")]
2614impl Write for Formatter<'_> {
2615    fn write_str(&mut self, s: &str) -> Result {
2616        self.buf.write_str(s)
2617    }
2618
2619    fn write_char(&mut self, c: char) -> Result {
2620        self.buf.write_char(c)
2621    }
2622
2623    #[inline]
2624    fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2625        if let Some(s) = args.as_statically_known_str() {
2626            self.buf.write_str(s)
2627        } else {
2628            write(self.buf, args)
2629        }
2630    }
2631}
2632
2633#[stable(feature = "rust1", since = "1.0.0")]
2634impl Display for Error {
2635    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2636        Display::fmt("an error occurred when formatting an argument", f)
2637    }
2638}
2639
2640// Implementations of the core formatting traits
2641
2642macro_rules! fmt_refs {
2643    ($($tr:ident),*) => {
2644        $(
2645        #[stable(feature = "rust1", since = "1.0.0")]
2646        impl<T: ?Sized + $tr> $tr for &T {
2647            fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2648        }
2649        #[stable(feature = "rust1", since = "1.0.0")]
2650        impl<T: ?Sized + $tr> $tr for &mut T {
2651            fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2652        }
2653        )*
2654    }
2655}
2656
2657fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2658
2659#[unstable(feature = "never_type", issue = "35121")]
2660impl Debug for ! {
2661    #[inline]
2662    fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2663        *self
2664    }
2665}
2666
2667#[unstable(feature = "never_type", issue = "35121")]
2668impl Display for ! {
2669    #[inline]
2670    fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2671        *self
2672    }
2673}
2674
2675#[stable(feature = "rust1", since = "1.0.0")]
2676impl Debug for bool {
2677    #[inline]
2678    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2679        Display::fmt(self, f)
2680    }
2681}
2682
2683#[stable(feature = "rust1", since = "1.0.0")]
2684impl Display for bool {
2685    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2686        Display::fmt(if *self { "true" } else { "false" }, f)
2687    }
2688}
2689
2690#[stable(feature = "rust1", since = "1.0.0")]
2691impl Debug for str {
2692    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2693        f.write_char('"')?;
2694
2695        // substring we know is printable
2696        let mut printable_range = 0..0;
2697
2698        fn needs_escape(b: u8) -> bool {
2699            b > 0x7E || b < 0x20 || b == b'\\' || b == b'"'
2700        }
2701
2702        // the loop here first skips over runs of printable ASCII as a fast path.
2703        // other chars (unicode, or ASCII that needs escaping) are then handled per-`char`.
2704        let mut rest = self;
2705        while rest.len() > 0 {
2706            let Some(non_printable_start) = rest.as_bytes().iter().position(|&b| needs_escape(b))
2707            else {
2708                printable_range.end += rest.len();
2709                break;
2710            };
2711
2712            printable_range.end += non_printable_start;
2713            // SAFETY: the position was derived from an iterator, so is known to be within bounds, and at a char boundary
2714            rest = unsafe { rest.get_unchecked(non_printable_start..) };
2715
2716            let mut chars = rest.chars();
2717            if let Some(c) = chars.next() {
2718                let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2719                    escape_grapheme_extended: true,
2720                    escape_single_quote: false,
2721                    escape_double_quote: true,
2722                });
2723                if esc.len() != 1 {
2724                    f.write_str(&self[printable_range.clone()])?;
2725                    Display::fmt(&esc, f)?;
2726                    printable_range.start = printable_range.end + c.len_utf8();
2727                }
2728                printable_range.end += c.len_utf8();
2729            }
2730            rest = chars.as_str();
2731        }
2732
2733        f.write_str(&self[printable_range])?;
2734
2735        f.write_char('"')
2736    }
2737}
2738
2739#[stable(feature = "rust1", since = "1.0.0")]
2740impl Display for str {
2741    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2742        f.pad(self)
2743    }
2744}
2745
2746#[stable(feature = "rust1", since = "1.0.0")]
2747impl Debug for char {
2748    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2749        f.write_char('\'')?;
2750        let esc = self.escape_debug_ext(EscapeDebugExtArgs {
2751            escape_grapheme_extended: true,
2752            escape_single_quote: true,
2753            escape_double_quote: false,
2754        });
2755        Display::fmt(&esc, f)?;
2756        f.write_char('\'')
2757    }
2758}
2759
2760#[stable(feature = "rust1", since = "1.0.0")]
2761impl Display for char {
2762    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2763        if f.options.width.is_none() && f.options.precision.is_none() {
2764            f.write_char(*self)
2765        } else {
2766            f.pad(self.encode_utf8(&mut [0; MAX_LEN_UTF8]))
2767        }
2768    }
2769}
2770
2771#[stable(feature = "rust1", since = "1.0.0")]
2772impl<T: ?Sized> Pointer for *const T {
2773    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2774        pointer_fmt_inner(self.expose_provenance(), f)
2775    }
2776}
2777
2778/// Since the formatting will be identical for all pointer types, uses a
2779/// non-monomorphized implementation for the actual formatting to reduce the
2780/// amount of codegen work needed.
2781///
2782/// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
2783/// `fn(...) -> ...` without using [problematic] "Oxford Casts".
2784///
2785/// [problematic]: https://github.com/rust-lang/rust/issues/95489
2786pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
2787    let old_width = f.options.width;
2788    let old_flags = f.options.flags;
2789
2790    // The alternate flag is already treated by LowerHex as being special-
2791    // it denotes whether to prefix with 0x. We use it to work out whether
2792    // or not to zero extend, and then unconditionally set it to get the
2793    // prefix.
2794    if f.alternate() {
2795        f.options.flags |= 1 << (rt::Flag::SignAwareZeroPad as u32);
2796
2797        if f.options.width.is_none() {
2798            f.options.width = Some((usize::BITS / 4) as u16 + 2);
2799        }
2800    }
2801    f.options.flags |= 1 << (rt::Flag::Alternate as u32);
2802
2803    let ret = LowerHex::fmt(&ptr_addr, f);
2804
2805    f.options.width = old_width;
2806    f.options.flags = old_flags;
2807
2808    ret
2809}
2810
2811#[stable(feature = "rust1", since = "1.0.0")]
2812impl<T: ?Sized> Pointer for *mut T {
2813    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2814        Pointer::fmt(&(*self as *const T), f)
2815    }
2816}
2817
2818#[stable(feature = "rust1", since = "1.0.0")]
2819impl<T: ?Sized> Pointer for &T {
2820    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2821        Pointer::fmt(&(*self as *const T), f)
2822    }
2823}
2824
2825#[stable(feature = "rust1", since = "1.0.0")]
2826impl<T: ?Sized> Pointer for &mut T {
2827    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2828        Pointer::fmt(&(&**self as *const T), f)
2829    }
2830}
2831
2832// Implementation of Display/Debug for various core types
2833
2834#[stable(feature = "rust1", since = "1.0.0")]
2835impl<T: ?Sized> Debug for *const T {
2836    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2837        Pointer::fmt(self, f)
2838    }
2839}
2840#[stable(feature = "rust1", since = "1.0.0")]
2841impl<T: ?Sized> Debug for *mut T {
2842    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2843        Pointer::fmt(self, f)
2844    }
2845}
2846
2847macro_rules! peel {
2848    ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2849}
2850
2851macro_rules! tuple {
2852    () => ();
2853    ( $($name:ident,)+ ) => (
2854        maybe_tuple_doc! {
2855            $($name)+ @
2856            #[stable(feature = "rust1", since = "1.0.0")]
2857            impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2858                #[allow(non_snake_case, unused_assignments)]
2859                fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2860                    let mut builder = f.debug_tuple("");
2861                    let ($(ref $name,)+) = *self;
2862                    $(
2863                        builder.field(&$name);
2864                    )+
2865
2866                    builder.finish()
2867                }
2868            }
2869        }
2870        peel! { $($name,)+ }
2871    )
2872}
2873
2874macro_rules! maybe_tuple_doc {
2875    ($a:ident @ #[$meta:meta] $item:item) => {
2876        #[doc(fake_variadic)]
2877        #[doc = "This trait is implemented for tuples up to twelve items long."]
2878        #[$meta]
2879        $item
2880    };
2881    ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
2882        #[doc(hidden)]
2883        #[$meta]
2884        $item
2885    };
2886}
2887
2888macro_rules! last_type {
2889    ($a:ident,) => { $a };
2890    ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2891}
2892
2893tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
2894
2895#[stable(feature = "rust1", since = "1.0.0")]
2896impl<T: Debug> Debug for [T] {
2897    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2898        f.debug_list().entries(self.iter()).finish()
2899    }
2900}
2901
2902#[stable(feature = "rust1", since = "1.0.0")]
2903impl Debug for () {
2904    #[inline]
2905    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2906        f.pad("()")
2907    }
2908}
2909#[stable(feature = "rust1", since = "1.0.0")]
2910impl<T: ?Sized> Debug for PhantomData<T> {
2911    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2912        write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
2913    }
2914}
2915
2916#[stable(feature = "rust1", since = "1.0.0")]
2917impl<T: Copy + Debug> Debug for Cell<T> {
2918    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2919        f.debug_struct("Cell").field("value", &self.get()).finish()
2920    }
2921}
2922
2923#[stable(feature = "rust1", since = "1.0.0")]
2924impl<T: ?Sized + Debug> Debug for RefCell<T> {
2925    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2926        let mut d = f.debug_struct("RefCell");
2927        match self.try_borrow() {
2928            Ok(borrow) => d.field("value", &borrow),
2929            Err(_) => d.field("value", &format_args!("<borrowed>")),
2930        };
2931        d.finish()
2932    }
2933}
2934
2935#[stable(feature = "rust1", since = "1.0.0")]
2936impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2937    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2938        Debug::fmt(&**self, f)
2939    }
2940}
2941
2942#[stable(feature = "rust1", since = "1.0.0")]
2943impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2944    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2945        Debug::fmt(&*(self.deref()), f)
2946    }
2947}
2948
2949#[stable(feature = "core_impl_debug", since = "1.9.0")]
2950impl<T: ?Sized> Debug for UnsafeCell<T> {
2951    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2952        f.debug_struct("UnsafeCell").finish_non_exhaustive()
2953    }
2954}
2955
2956#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2957impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
2958    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2959        f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
2960    }
2961}
2962
2963// If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2964// it's a lot easier than creating all of the rt::Piece structures here.
2965// There are also tests in the alloc crate, for those that need allocations.