1
//! Utilities for formatting and printing strings.
2

            
3
#![stable(feature = "rust1", since = "1.0.0")]
4

            
5
#[cfg(not(feature = "ferrocene_certified"))]
6
use crate::cell::{Cell, Ref, RefCell, RefMut, SyncUnsafeCell, UnsafeCell};
7
#[cfg(not(feature = "ferrocene_certified"))]
8
use crate::char::{EscapeDebugExtArgs, MAX_LEN_UTF8};
9
#[cfg(not(feature = "ferrocene_certified"))]
10
use crate::marker::{PhantomData, PointeeSized};
11
#[cfg(not(feature = "ferrocene_certified"))]
12
use crate::num::fmt as numfmt;
13
#[cfg(not(feature = "ferrocene_certified"))]
14
use crate::ops::Deref;
15
#[cfg(not(feature = "ferrocene_certified"))]
16
use crate::{iter, result, str};
17

            
18
#[cfg(not(feature = "ferrocene_certified"))]
19
mod builders;
20
#[cfg(not(no_fp_fmt_parse))]
21
#[cfg(not(feature = "ferrocene_certified"))]
22
mod float;
23
#[cfg(no_fp_fmt_parse)]
24
#[cfg(not(feature = "ferrocene_certified"))]
25
mod nofloat;
26
#[cfg(not(feature = "ferrocene_certified"))]
27
mod num;
28
#[cfg(not(feature = "ferrocene_certified"))]
29
mod num_buffer;
30
#[cfg(not(feature = "ferrocene_certified"))]
31
mod rt;
32

            
33
#[stable(feature = "fmt_flags_align", since = "1.28.0")]
34
#[rustc_diagnostic_item = "Alignment"]
35
/// Possible alignments returned by `Formatter::align`
36
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
37
#[cfg(not(feature = "ferrocene_certified"))]
38
pub enum Alignment {
39
    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
40
    /// Indication that contents should be left-aligned.
41
    Left,
42
    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
43
    /// Indication that contents should be right-aligned.
44
    Right,
45
    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
46
    /// Indication that contents should be center-aligned.
47
    Center,
48
}
49

            
50
#[unstable(feature = "int_format_into", issue = "138215")]
51
#[cfg(not(feature = "ferrocene_certified"))]
52
pub use num_buffer::{NumBuffer, NumBufferTrait};
53

            
54
#[stable(feature = "debug_builders", since = "1.2.0")]
55
#[cfg(not(feature = "ferrocene_certified"))]
56
pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
57
#[unstable(feature = "debug_closure_helpers", issue = "117729")]
58
#[cfg(not(feature = "ferrocene_certified"))]
59
pub use self::builders::{FromFn, from_fn};
60

            
61
/// The type returned by formatter methods.
62
///
63
/// # Examples
64
///
65
/// ```
66
/// use std::fmt;
67
///
68
/// #[derive(Debug)]
69
/// struct Triangle {
70
///     a: f32,
71
///     b: f32,
72
///     c: f32
73
/// }
74
///
75
/// impl fmt::Display for Triangle {
76
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77
///         write!(f, "({}, {}, {})", self.a, self.b, self.c)
78
///     }
79
/// }
80
///
81
/// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
82
///
83
/// assert_eq!(format!("{pythagorean_triple}"), "(3, 4, 5)");
84
/// ```
85
#[stable(feature = "rust1", since = "1.0.0")]
86
#[cfg(not(feature = "ferrocene_certified"))]
87
pub type Result = result::Result<(), Error>;
88

            
89
/// The error type which is returned from formatting a message into a stream.
90
///
91
/// This type does not support transmission of an error other than that an error
92
/// occurred. This is because, despite the existence of this error,
93
/// string formatting is considered an infallible operation.
94
/// `fmt()` implementors should not return this `Error` unless they received it from their
95
/// [`Formatter`]. The only time your code should create a new instance of this
96
/// error is when implementing `fmt::Write`, in order to cancel the formatting operation when
97
/// writing to the underlying stream fails.
98
///
99
/// Any extra information must be arranged to be transmitted through some other means,
100
/// such as storing it in a field to be consulted after the formatting operation has been
101
/// cancelled. (For example, this is how [`std::io::Write::write_fmt()`] propagates IO errors
102
/// during writing.)
103
///
104
/// This type, `fmt::Error`, should not be
105
/// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
106
/// have in scope.
107
///
108
/// [`std::io::Error`]: ../../std/io/struct.Error.html
109
/// [`std::io::Write::write_fmt()`]: ../../std/io/trait.Write.html#method.write_fmt
110
/// [`std::error::Error`]: ../../std/error/trait.Error.html
111
///
112
/// # Examples
113
///
114
/// ```rust
115
/// use std::fmt::{self, write};
116
///
117
/// let mut output = String::new();
118
/// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
119
///     panic!("An error occurred");
120
/// }
121
/// ```
122
#[stable(feature = "rust1", since = "1.0.0")]
123
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
124
#[cfg(not(feature = "ferrocene_certified"))]
125
pub struct Error;
126

            
127
/// A trait for writing or formatting into Unicode-accepting buffers or streams.
128
///
129
/// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
130
/// want to accept Unicode and you don't need flushing, you should implement this trait;
131
/// otherwise you should implement [`std::io::Write`].
132
///
133
/// [`std::io::Write`]: ../../std/io/trait.Write.html
134
/// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
135
#[stable(feature = "rust1", since = "1.0.0")]
136
#[cfg(not(feature = "ferrocene_certified"))]
137
pub trait Write {
138
    /// Writes a string slice into this writer, returning whether the write
139
    /// succeeded.
140
    ///
141
    /// This method can only succeed if the entire string slice was successfully
142
    /// written, and this method will not return until all data has been
143
    /// written or an error occurs.
144
    ///
145
    /// # Errors
146
    ///
147
    /// This function will return an instance of [`std::fmt::Error`][Error] on error.
148
    ///
149
    /// The purpose of that error is to abort the formatting operation when the underlying
150
    /// destination encounters some error preventing it from accepting more text;
151
    /// in particular, it does not communicate any information about *what* error occurred.
152
    /// It should generally be propagated rather than handled, at least when implementing
153
    /// formatting traits.
154
    ///
155
    /// # Examples
156
    ///
157
    /// ```
158
    /// use std::fmt::{Error, Write};
159
    ///
160
    /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
161
    ///     f.write_str(s)
162
    /// }
163
    ///
164
    /// let mut buf = String::new();
165
    /// writer(&mut buf, "hola")?;
166
    /// assert_eq!(&buf, "hola");
167
    /// # std::fmt::Result::Ok(())
168
    /// ```
169
    #[stable(feature = "rust1", since = "1.0.0")]
170
    fn write_str(&mut self, s: &str) -> Result;
171

            
172
    /// Writes a [`char`] into this writer, returning whether the write succeeded.
173
    ///
174
    /// A single [`char`] may be encoded as more than one byte.
175
    /// This method can only succeed if the entire byte sequence was successfully
176
    /// written, and this method will not return until all data has been
177
    /// written or an error occurs.
178
    ///
179
    /// # Errors
180
    ///
181
    /// This function will return an instance of [`Error`] on error.
182
    ///
183
    /// # Examples
184
    ///
185
    /// ```
186
    /// use std::fmt::{Error, Write};
187
    ///
188
    /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
189
    ///     f.write_char(c)
190
    /// }
191
    ///
192
    /// let mut buf = String::new();
193
    /// writer(&mut buf, 'a')?;
194
    /// writer(&mut buf, 'b')?;
195
    /// assert_eq!(&buf, "ab");
196
    /// # std::fmt::Result::Ok(())
197
    /// ```
198
    #[stable(feature = "fmt_write_char", since = "1.1.0")]
199
2010
    fn write_char(&mut self, c: char) -> Result {
200
2010
        self.write_str(c.encode_utf8(&mut [0; MAX_LEN_UTF8]))
201
2010
    }
202

            
203
    /// Glue for usage of the [`write!`] macro with implementors of this trait.
204
    ///
205
    /// This method should generally not be invoked manually, but rather through
206
    /// the [`write!`] macro itself.
207
    ///
208
    /// # Errors
209
    ///
210
    /// This function will return an instance of [`Error`] on error. Please see
211
    /// [write_str](Write::write_str) for details.
212
    ///
213
    /// # Examples
214
    ///
215
    /// ```
216
    /// use std::fmt::{Error, Write};
217
    ///
218
    /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
219
    ///     f.write_fmt(format_args!("{s}"))
220
    /// }
221
    ///
222
    /// let mut buf = String::new();
223
    /// writer(&mut buf, "world")?;
224
    /// assert_eq!(&buf, "world");
225
    /// # std::fmt::Result::Ok(())
226
    /// ```
227
    #[stable(feature = "rust1", since = "1.0.0")]
228
4067
    fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
229
        // We use a specialization for `Sized` types to avoid an indirection
230
        // through `&mut self`
231
        trait SpecWriteFmt {
232
            fn spec_write_fmt(self, args: Arguments<'_>) -> Result;
233
        }
234

            
235
        impl<W: Write + ?Sized> SpecWriteFmt for &mut W {
236
            #[inline]
237
            default fn spec_write_fmt(mut self, args: Arguments<'_>) -> Result {
238
                if let Some(s) = args.as_statically_known_str() {
239
                    self.write_str(s)
240
                } else {
241
                    write(&mut self, args)
242
                }
243
            }
244
        }
245

            
246
        impl<W: Write> SpecWriteFmt for &mut W {
247
            #[inline]
248
4067
            fn spec_write_fmt(self, args: Arguments<'_>) -> Result {
249
4067
                if let Some(s) = args.as_statically_known_str() {
250
                    self.write_str(s)
251
                } else {
252
4067
                    write(self, args)
253
                }
254
4067
            }
255
        }
256

            
257
4067
        self.spec_write_fmt(args)
258
4067
    }
259
}
260

            
261
#[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
262
#[cfg(not(feature = "ferrocene_certified"))]
263
impl<W: Write + ?Sized> Write for &mut W {
264
    fn write_str(&mut self, s: &str) -> Result {
265
        (**self).write_str(s)
266
    }
267

            
268
    fn write_char(&mut self, c: char) -> Result {
269
        (**self).write_char(c)
270
    }
271

            
272
    fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
273
        (**self).write_fmt(args)
274
    }
275
}
276

            
277
/// The signedness of a [`Formatter`] (or of a [`FormattingOptions`]).
278
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
279
#[unstable(feature = "formatting_options", issue = "118117")]
280
#[cfg(not(feature = "ferrocene_certified"))]
281
pub enum Sign {
282
    /// Represents the `+` flag.
283
    Plus,
284
    /// Represents the `-` flag.
285
    Minus,
286
}
287

            
288
/// Specifies whether the [`Debug`] trait should use lower-/upper-case
289
/// hexadecimal or normal integers.
290
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
291
#[unstable(feature = "formatting_options", issue = "118117")]
292
#[cfg(not(feature = "ferrocene_certified"))]
293
pub enum DebugAsHex {
294
    /// Use lower-case hexadecimal integers for the `Debug` trait (like [the `x?` type](../../std/fmt/index.html#formatting-traits)).
295
    Lower,
296
    /// Use upper-case hexadecimal integers for the `Debug` trait (like [the `X?` type](../../std/fmt/index.html#formatting-traits)).
297
    Upper,
298
}
299

            
300
/// Options for formatting.
301
///
302
/// `FormattingOptions` is a [`Formatter`] without an attached [`Write`] trait.
303
/// It is mainly used to construct `Formatter` instances.
304
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
305
#[unstable(feature = "formatting_options", issue = "118117")]
306
#[cfg(not(feature = "ferrocene_certified"))]
307
pub struct FormattingOptions {
308
    /// Flags, with the following bit fields:
309
    ///
310
    /// ```text
311
    ///   31  30  29  28  27  26  25  24  23  22  21  20                              0
312
    /// ┌───┬───────┬───┬───┬───┬───┬───┬───┬───┬───┬──────────────────────────────────┐
313
    /// │ 1 │ align │ p │ w │ X?│ x?│'0'│ # │ - │ + │               fill               │
314
    /// └───┴───────┴───┴───┴───┴───┴───┴───┴───┴───┴──────────────────────────────────┘
315
    ///   │     │     │   │  └─┬───────────────────┘ └─┬──────────────────────────────┘
316
    ///   │     │     │   │    │                       └─ The fill character (21 bits char).
317
    ///   │     │     │   │    └─ The debug upper/lower hex, zero pad, alternate, and plus/minus flags.
318
    ///   │     │     │   └─ Whether a width is set. (The value is stored separately.)
319
    ///   │     │     └─ Whether a precision is set. (The value is stored separately.)
320
    ///   │     ├─ 0: Align left. (<)
321
    ///   │     ├─ 1: Align right. (>)
322
    ///   │     ├─ 2: Align center. (^)
323
    ///   │     └─ 3: Alignment not set. (default)
324
    ///   └─ Always set.
325
    ///      This makes it possible to distinguish formatting flags from
326
    ///      a &str size when stored in (the upper bits of) the same field.
327
    ///      (fmt::Arguments will make use of this property in the future.)
328
    /// ```
329
    // Note: This could use a special niche type with range 0x8000_0000..=0xfdd0ffff.
330
    // It's unclear if that's useful, though.
331
    flags: u32,
332
    /// Width if width flag (bit 27) above is set. Otherwise, always 0.
333
    width: u16,
334
    /// Precision if precision flag (bit 28) above is set. Otherwise, always 0.
335
    precision: u16,
336
}
337

            
338
// This needs to match with compiler/rustc_ast_lowering/src/format.rs.
339
#[cfg(not(feature = "ferrocene_certified"))]
340
mod flags {
341
    pub(super) const SIGN_PLUS_FLAG: u32 = 1 << 21;
342
    pub(super) const SIGN_MINUS_FLAG: u32 = 1 << 22;
343
    pub(super) const ALTERNATE_FLAG: u32 = 1 << 23;
344
    pub(super) const SIGN_AWARE_ZERO_PAD_FLAG: u32 = 1 << 24;
345
    pub(super) const DEBUG_LOWER_HEX_FLAG: u32 = 1 << 25;
346
    pub(super) const DEBUG_UPPER_HEX_FLAG: u32 = 1 << 26;
347
    pub(super) const WIDTH_FLAG: u32 = 1 << 27;
348
    pub(super) const PRECISION_FLAG: u32 = 1 << 28;
349
    pub(super) const ALIGN_BITS: u32 = 0b11 << 29;
350
    pub(super) const ALIGN_LEFT: u32 = 0 << 29;
351
    pub(super) const ALIGN_RIGHT: u32 = 1 << 29;
352
    pub(super) const ALIGN_CENTER: u32 = 2 << 29;
353
    pub(super) const ALIGN_UNKNOWN: u32 = 3 << 29;
354
    pub(super) const ALWAYS_SET: u32 = 1 << 31;
355
}
356

            
357
#[cfg(not(feature = "ferrocene_certified"))]
358
impl FormattingOptions {
359
    /// Construct a new `FormatterBuilder` with the supplied `Write` trait
360
    /// object for output that is equivalent to the `{}` formatting
361
    /// specifier:
362
    ///
363
    /// - no flags,
364
    /// - filled with spaces,
365
    /// - no alignment,
366
    /// - no width,
367
    /// - no precision, and
368
    /// - no [`DebugAsHex`] output mode.
369
    #[unstable(feature = "formatting_options", issue = "118117")]
370
    pub const fn new() -> Self {
371
        Self {
372
            flags: ' ' as u32 | flags::ALIGN_UNKNOWN | flags::ALWAYS_SET,
373
            width: 0,
374
            precision: 0,
375
        }
376
    }
377

            
378
    /// Sets or removes the sign (the `+` or the `-` flag).
379
    ///
380
    /// - `+`: This is intended for numeric types and indicates that the sign
381
    ///   should always be printed. By default only the negative sign of signed
382
    ///   values is printed, and the sign of positive or unsigned values is
383
    ///   omitted. This flag indicates that the correct sign (+ or -) should
384
    ///   always be printed.
385
    /// - `-`: Currently not used
386
    #[unstable(feature = "formatting_options", issue = "118117")]
387
    pub const fn sign(&mut self, sign: Option<Sign>) -> &mut Self {
388
        let sign = match sign {
389
            None => 0,
390
            Some(Sign::Plus) => flags::SIGN_PLUS_FLAG,
391
            Some(Sign::Minus) => flags::SIGN_MINUS_FLAG,
392
        };
393
        self.flags = self.flags & !(flags::SIGN_PLUS_FLAG | flags::SIGN_MINUS_FLAG) | sign;
394
        self
395
    }
396
    /// Sets or unsets the `0` flag.
397
    ///
398
    /// 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
399
    #[unstable(feature = "formatting_options", issue = "118117")]
400
    pub const fn sign_aware_zero_pad(&mut self, sign_aware_zero_pad: bool) -> &mut Self {
401
        if sign_aware_zero_pad {
402
            self.flags |= flags::SIGN_AWARE_ZERO_PAD_FLAG;
403
        } else {
404
            self.flags &= !flags::SIGN_AWARE_ZERO_PAD_FLAG;
405
        }
406
        self
407
    }
408
    /// Sets or unsets the `#` flag.
409
    ///
410
    /// This flag indicates that the "alternate" form of printing should be
411
    /// used. The alternate forms are:
412
    /// - [`Debug`] : pretty-print the [`Debug`] formatting (adds linebreaks and indentation)
413
    /// - [`LowerHex`] as well as [`UpperHex`] - precedes the argument with a `0x`
414
    /// - [`Octal`] - precedes the argument with a `0b`
415
    /// - [`Binary`] - precedes the argument with a `0o`
416
    #[unstable(feature = "formatting_options", issue = "118117")]
417
    pub const fn alternate(&mut self, alternate: bool) -> &mut Self {
418
        if alternate {
419
            self.flags |= flags::ALTERNATE_FLAG;
420
        } else {
421
            self.flags &= !flags::ALTERNATE_FLAG;
422
        }
423
        self
424
    }
425
    /// Sets the fill character.
426
    ///
427
    /// The optional fill character and alignment is provided normally in
428
    /// conjunction with the width parameter. This indicates that if the value
429
    /// being formatted is smaller than width some extra characters will be
430
    /// printed around it.
431
    #[unstable(feature = "formatting_options", issue = "118117")]
432
    pub const fn fill(&mut self, fill: char) -> &mut Self {
433
        self.flags = self.flags & (u32::MAX << 21) | fill as u32;
434
        self
435
    }
436
    /// Sets or removes the alignment.
437
    ///
438
    /// The alignment specifies how the value being formatted should be
439
    /// positioned if it is smaller than the width of the formatter.
440
    #[unstable(feature = "formatting_options", issue = "118117")]
441
    pub const fn align(&mut self, align: Option<Alignment>) -> &mut Self {
442
        let align: u32 = match align {
443
            Some(Alignment::Left) => flags::ALIGN_LEFT,
444
            Some(Alignment::Right) => flags::ALIGN_RIGHT,
445
            Some(Alignment::Center) => flags::ALIGN_CENTER,
446
            None => flags::ALIGN_UNKNOWN,
447
        };
448
        self.flags = self.flags & !flags::ALIGN_BITS | align;
449
        self
450
    }
451
    /// Sets or removes the width.
452
    ///
453
    /// This is a parameter for the “minimum width” that the format should take
454
    /// up. If the value’s string does not fill up this many characters, then
455
    /// the padding specified by [`FormattingOptions::fill`]/[`FormattingOptions::align`]
456
    /// will be used to take up the required space.
457
    #[unstable(feature = "formatting_options", issue = "118117")]
458
    pub const fn width(&mut self, width: Option<u16>) -> &mut Self {
459
        if let Some(width) = width {
460
            self.flags |= flags::WIDTH_FLAG;
461
            self.width = width;
462
        } else {
463
            self.flags &= !flags::WIDTH_FLAG;
464
            self.width = 0;
465
        }
466
        self
467
    }
468
    /// Sets or removes the precision.
469
    ///
470
    /// - For non-numeric types, this can be considered a “maximum width”. If
471
    ///   the resulting string is longer than this width, then it is truncated
472
    ///   down to this many characters and that truncated value is emitted with
473
    ///   proper fill, alignment and width if those parameters are set.
474
    /// - For integral types, this is ignored.
475
    /// - For floating-point types, this indicates how many digits after the
476
    /// decimal point should be printed.
477
    #[unstable(feature = "formatting_options", issue = "118117")]
478
    pub const fn precision(&mut self, precision: Option<u16>) -> &mut Self {
479
        if let Some(precision) = precision {
480
            self.flags |= flags::PRECISION_FLAG;
481
            self.precision = precision;
482
        } else {
483
            self.flags &= !flags::PRECISION_FLAG;
484
            self.precision = 0;
485
        }
486
        self
487
    }
488
    /// Specifies whether the [`Debug`] trait should use lower-/upper-case
489
    /// hexadecimal or normal integers
490
    #[unstable(feature = "formatting_options", issue = "118117")]
491
    pub const fn debug_as_hex(&mut self, debug_as_hex: Option<DebugAsHex>) -> &mut Self {
492
        let debug_as_hex = match debug_as_hex {
493
            None => 0,
494
            Some(DebugAsHex::Lower) => flags::DEBUG_LOWER_HEX_FLAG,
495
            Some(DebugAsHex::Upper) => flags::DEBUG_UPPER_HEX_FLAG,
496
        };
497
        self.flags = self.flags & !(flags::DEBUG_LOWER_HEX_FLAG | flags::DEBUG_UPPER_HEX_FLAG)
498
            | debug_as_hex;
499
        self
500
    }
501

            
502
    /// Returns the current sign (the `+` or the `-` flag).
503
    #[unstable(feature = "formatting_options", issue = "118117")]
504
    pub const fn get_sign(&self) -> Option<Sign> {
505
        if self.flags & flags::SIGN_PLUS_FLAG != 0 {
506
            Some(Sign::Plus)
507
        } else if self.flags & flags::SIGN_MINUS_FLAG != 0 {
508
            Some(Sign::Minus)
509
        } else {
510
            None
511
        }
512
    }
513
    /// Returns the current `0` flag.
514
    #[unstable(feature = "formatting_options", issue = "118117")]
515
    pub const fn get_sign_aware_zero_pad(&self) -> bool {
516
        self.flags & flags::SIGN_AWARE_ZERO_PAD_FLAG != 0
517
    }
518
    /// Returns the current `#` flag.
519
    #[unstable(feature = "formatting_options", issue = "118117")]
520
    pub const fn get_alternate(&self) -> bool {
521
        self.flags & flags::ALTERNATE_FLAG != 0
522
    }
523
    /// Returns the current fill character.
524
    #[unstable(feature = "formatting_options", issue = "118117")]
525
    pub const fn get_fill(&self) -> char {
526
        // SAFETY: We only ever put a valid `char` in the lower 21 bits of the flags field.
527
        unsafe { char::from_u32_unchecked(self.flags & 0x1FFFFF) }
528
    }
529
    /// Returns the current alignment.
530
    #[unstable(feature = "formatting_options", issue = "118117")]
531
    pub const fn get_align(&self) -> Option<Alignment> {
532
        match self.flags & flags::ALIGN_BITS {
533
            flags::ALIGN_LEFT => Some(Alignment::Left),
534
            flags::ALIGN_RIGHT => Some(Alignment::Right),
535
            flags::ALIGN_CENTER => Some(Alignment::Center),
536
            _ => None,
537
        }
538
    }
539
    /// Returns the current width.
540
    #[unstable(feature = "formatting_options", issue = "118117")]
541
    pub const fn get_width(&self) -> Option<u16> {
542
        if self.flags & flags::WIDTH_FLAG != 0 { Some(self.width) } else { None }
543
    }
544
    /// Returns the current precision.
545
    #[unstable(feature = "formatting_options", issue = "118117")]
546
    pub const fn get_precision(&self) -> Option<u16> {
547
        if self.flags & flags::PRECISION_FLAG != 0 { Some(self.precision) } else { None }
548
    }
549
    /// Returns the current precision.
550
    #[unstable(feature = "formatting_options", issue = "118117")]
551
    pub const fn get_debug_as_hex(&self) -> Option<DebugAsHex> {
552
        if self.flags & flags::DEBUG_LOWER_HEX_FLAG != 0 {
553
            Some(DebugAsHex::Lower)
554
        } else if self.flags & flags::DEBUG_UPPER_HEX_FLAG != 0 {
555
            Some(DebugAsHex::Upper)
556
        } else {
557
            None
558
        }
559
    }
560

            
561
    /// Creates a [`Formatter`] that writes its output to the given [`Write`] trait.
562
    ///
563
    /// You may alternatively use [`Formatter::new()`].
564
    #[unstable(feature = "formatting_options", issue = "118117")]
565
    pub const fn create_formatter<'a>(self, write: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
566
        Formatter { options: self, buf: write }
567
    }
568
}
569

            
570
#[unstable(feature = "formatting_options", issue = "118117")]
571
#[cfg(not(feature = "ferrocene_certified"))]
572
impl Default for FormattingOptions {
573
    /// Same as [`FormattingOptions::new()`].
574
    fn default() -> Self {
575
        // The `#[derive(Default)]` implementation would set `fill` to `\0` instead of space.
576
        Self::new()
577
    }
578
}
579

            
580
/// Configuration for formatting.
581
///
582
/// A `Formatter` represents various options related to formatting. Users do not
583
/// construct `Formatter`s directly; a mutable reference to one is passed to
584
/// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
585
///
586
/// To interact with a `Formatter`, you'll call various methods to change the
587
/// various options related to formatting. For examples, please see the
588
/// documentation of the methods defined on `Formatter` below.
589
#[allow(missing_debug_implementations)]
590
#[stable(feature = "rust1", since = "1.0.0")]
591
#[rustc_diagnostic_item = "Formatter"]
592
#[cfg(not(feature = "ferrocene_certified"))]
593
pub struct Formatter<'a> {
594
    options: FormattingOptions,
595

            
596
    buf: &'a mut (dyn Write + 'a),
597
}
598

            
599
#[cfg(not(feature = "ferrocene_certified"))]
600
impl<'a> Formatter<'a> {
601
    /// Creates a new formatter with given [`FormattingOptions`].
602
    ///
603
    /// If `write` is a reference to a formatter, it is recommended to use
604
    /// [`Formatter::with_options`] instead as this can borrow the underlying
605
    /// `write`, thereby bypassing one layer of indirection.
606
    ///
607
    /// You may alternatively use [`FormattingOptions::create_formatter()`].
608
    #[unstable(feature = "formatting_options", issue = "118117")]
609
80549
    pub const fn new(write: &'a mut (dyn Write + 'a), options: FormattingOptions) -> Self {
610
80549
        Formatter { options, buf: write }
611
80549
    }
612

            
613
    /// Creates a new formatter based on this one with given [`FormattingOptions`].
614
    #[unstable(feature = "formatting_options", issue = "118117")]
615
    pub const fn with_options<'b>(&'b mut self, options: FormattingOptions) -> Formatter<'b> {
616
        Formatter { options, buf: self.buf }
617
    }
618
}
619

            
620
/// This structure represents a safely precompiled version of a format string
621
/// and its arguments. This cannot be generated at runtime because it cannot
622
/// safely be done, so no constructors are given and the fields are private
623
/// to prevent modification.
624
///
625
/// The [`format_args!`] macro will safely create an instance of this structure.
626
/// The macro validates the format string at compile-time so usage of the
627
/// [`write()`] and [`format()`] functions can be safely performed.
628
///
629
/// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
630
/// and `Display` contexts as seen below. The example also shows that `Debug`
631
/// and `Display` format to the same thing: the interpolated format string
632
/// in `format_args!`.
633
///
634
/// ```rust
635
/// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
636
/// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
637
/// assert_eq!("1 foo 2", display);
638
/// assert_eq!(display, debug);
639
/// ```
640
///
641
/// [`format()`]: ../../std/fmt/fn.format.html
642
#[lang = "format_arguments"]
643
#[stable(feature = "rust1", since = "1.0.0")]
644
#[derive(Copy, Clone)]
645
#[cfg(not(feature = "ferrocene_certified"))]
646
pub struct Arguments<'a> {
647
    // Format string pieces to print.
648
    pieces: &'a [&'static str],
649

            
650
    // Placeholder specs, or `None` if all specs are default (as in "{}{}").
651
    fmt: Option<&'a [rt::Placeholder]>,
652

            
653
    // Dynamic arguments for interpolation, to be interleaved with string
654
    // pieces. (Every argument is preceded by a string piece.)
655
    args: &'a [rt::Argument<'a>],
656
}
657

            
658
#[doc(hidden)]
659
#[unstable(feature = "fmt_internals", issue = "none")]
660
#[cfg(not(feature = "ferrocene_certified"))]
661
impl<'a> Arguments<'a> {
662
    /// Estimates the length of the formatted text.
663
    ///
664
    /// This is intended to be used for setting initial `String` capacity
665
    /// when using `format!`. Note: this is neither the lower nor upper bound.
666
    #[inline]
667
    pub fn estimated_capacity(&self) -> usize {
668
        let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
669

            
670
        if self.args.is_empty() {
671
            pieces_length
672
        } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
673
            // If the format string starts with an argument,
674
            // don't preallocate anything, unless length
675
            // of pieces is significant.
676
            0
677
        } else {
678
            // There are some arguments, so any additional push
679
            // will reallocate the string. To avoid that,
680
            // we're "pre-doubling" the capacity here.
681
            pieces_length.checked_mul(2).unwrap_or(0)
682
        }
683
    }
684
}
685

            
686
#[cfg(not(feature = "ferrocene_certified"))]
687
impl<'a> Arguments<'a> {
688
    /// Gets the formatted string, if it has no arguments to be formatted at runtime.
689
    ///
690
    /// This can be used to avoid allocations in some cases.
691
    ///
692
    /// # Guarantees
693
    ///
694
    /// For `format_args!("just a literal")`, this function is guaranteed to
695
    /// return `Some("just a literal")`.
696
    ///
697
    /// For most cases with placeholders, this function will return `None`.
698
    ///
699
    /// However, the compiler may perform optimizations that can cause this
700
    /// function to return `Some(_)` even if the format string contains
701
    /// placeholders. For example, `format_args!("Hello, {}!", "world")` may be
702
    /// optimized to `format_args!("Hello, world!")`, such that `as_str()`
703
    /// returns `Some("Hello, world!")`.
704
    ///
705
    /// The behavior for anything but the trivial case (without placeholders)
706
    /// is not guaranteed, and should not be relied upon for anything other
707
    /// than optimization.
708
    ///
709
    /// # Examples
710
    ///
711
    /// ```rust
712
    /// use std::fmt::Arguments;
713
    ///
714
    /// fn write_str(_: &str) { /* ... */ }
715
    ///
716
    /// fn write_fmt(args: &Arguments<'_>) {
717
    ///     if let Some(s) = args.as_str() {
718
    ///         write_str(s)
719
    ///     } else {
720
    ///         write_str(&args.to_string());
721
    ///     }
722
    /// }
723
    /// ```
724
    ///
725
    /// ```rust
726
    /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
727
    /// assert_eq!(format_args!("").as_str(), Some(""));
728
    /// assert_eq!(format_args!("{:?}", std::env::current_dir()).as_str(), None);
729
    /// ```
730
    #[stable(feature = "fmt_as_str", since = "1.52.0")]
731
    #[rustc_const_stable(feature = "const_arguments_as_str", since = "1.84.0")]
732
    #[must_use]
733
    #[inline]
734
129218
    pub const fn as_str(&self) -> Option<&'static str> {
735
129218
        match (self.pieces, self.args) {
736
129218
            ([], []) => Some(""),
737
31135
            ([s], []) => Some(s),
738
108107
            _ => None,
739
        }
740
129218
    }
741

            
742
    /// Same as [`Arguments::as_str`], but will only return `Some(s)` if it can be determined at compile time.
743
    #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
744
    #[must_use]
745
    #[inline]
746
    #[doc(hidden)]
747
80232
    pub fn as_statically_known_str(&self) -> Option<&'static str> {
748
80232
        let s = self.as_str();
749
80232
        if core::intrinsics::is_val_statically_known(s.is_some()) { s } else { None }
750
80232
    }
751
}
752

            
753
// Manually implementing these results in better error messages.
754
#[stable(feature = "rust1", since = "1.0.0")]
755
#[cfg(not(feature = "ferrocene_certified"))]
756
impl !Send for Arguments<'_> {}
757
#[stable(feature = "rust1", since = "1.0.0")]
758
#[cfg(not(feature = "ferrocene_certified"))]
759
impl !Sync for Arguments<'_> {}
760

            
761
#[stable(feature = "rust1", since = "1.0.0")]
762
#[cfg(not(feature = "ferrocene_certified"))]
763
impl Debug for Arguments<'_> {
764
    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
765
        Display::fmt(self, fmt)
766
    }
767
}
768

            
769
#[stable(feature = "rust1", since = "1.0.0")]
770
#[cfg(not(feature = "ferrocene_certified"))]
771
impl Display for Arguments<'_> {
772
    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
773
        write(fmt.buf, *self)
774
    }
775
}
776

            
777
/// `?` formatting.
778
///
779
/// `Debug` should format the output in a programmer-facing, debugging context.
780
///
781
/// Generally speaking, you should just `derive` a `Debug` implementation.
782
///
783
/// When used with the alternate format specifier `#?`, the output is pretty-printed.
784
///
785
/// For more information on formatters, see [the module-level documentation][module].
786
///
787
/// [module]: ../../std/fmt/index.html
788
///
789
/// This trait can be used with `#[derive]` if all fields implement `Debug`. When
790
/// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
791
/// comma-separated list of each field's name and `Debug` value, then `}`. For
792
/// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
793
/// `Debug` values of the fields, then `)`.
794
///
795
/// # Stability
796
///
797
/// Derived `Debug` formats are not stable, and so may change with future Rust
798
/// versions. Additionally, `Debug` implementations of types provided by the
799
/// standard library (`std`, `core`, `alloc`, etc.) are not stable, and
800
/// may also change with future Rust versions.
801
///
802
/// # Examples
803
///
804
/// Deriving an implementation:
805
///
806
/// ```
807
/// #[derive(Debug)]
808
/// struct Point {
809
///     x: i32,
810
///     y: i32,
811
/// }
812
///
813
/// let origin = Point { x: 0, y: 0 };
814
///
815
/// assert_eq!(
816
///     format!("The origin is: {origin:?}"),
817
///     "The origin is: Point { x: 0, y: 0 }",
818
/// );
819
/// ```
820
///
821
/// Manually implementing:
822
///
823
/// ```
824
/// use std::fmt;
825
///
826
/// struct Point {
827
///     x: i32,
828
///     y: i32,
829
/// }
830
///
831
/// impl fmt::Debug for Point {
832
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
833
///         f.debug_struct("Point")
834
///          .field("x", &self.x)
835
///          .field("y", &self.y)
836
///          .finish()
837
///     }
838
/// }
839
///
840
/// let origin = Point { x: 0, y: 0 };
841
///
842
/// assert_eq!(
843
///     format!("The origin is: {origin:?}"),
844
///     "The origin is: Point { x: 0, y: 0 }",
845
/// );
846
/// ```
847
///
848
/// There are a number of helper methods on the [`Formatter`] struct to help you with manual
849
/// implementations, such as [`debug_struct`].
850
///
851
/// [`debug_struct`]: Formatter::debug_struct
852
///
853
/// Types that do not wish to use the standard suite of debug representations
854
/// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
855
/// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
856
/// manually writing an arbitrary representation to the `Formatter`.
857
///
858
/// ```
859
/// # use std::fmt;
860
/// # struct Point {
861
/// #     x: i32,
862
/// #     y: i32,
863
/// # }
864
/// #
865
/// impl fmt::Debug for Point {
866
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
867
///         write!(f, "Point [{} {}]", self.x, self.y)
868
///     }
869
/// }
870
/// ```
871
///
872
/// `Debug` implementations using either `derive` or the debug builder API
873
/// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
874
///
875
/// Pretty-printing with `#?`:
876
///
877
/// ```
878
/// #[derive(Debug)]
879
/// struct Point {
880
///     x: i32,
881
///     y: i32,
882
/// }
883
///
884
/// let origin = Point { x: 0, y: 0 };
885
///
886
/// let expected = "The origin is: Point {
887
///     x: 0,
888
///     y: 0,
889
/// }";
890
/// assert_eq!(format!("The origin is: {origin:#?}"), expected);
891
/// ```
892
#[stable(feature = "rust1", since = "1.0.0")]
893
#[rustc_on_unimplemented(
894
    on(
895
        crate_local,
896
        note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {This} for {Self}`"
897
    ),
898
    on(
899
        from_desugaring = "FormatLiteral",
900
        label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{This}`"
901
    ),
902
    message = "`{Self}` doesn't implement `{This}`"
903
)]
904
#[doc(alias = "{:?}")]
905
#[rustc_diagnostic_item = "Debug"]
906
#[rustc_trivial_field_reads]
907
#[cfg(not(feature = "ferrocene_certified"))]
908
pub trait Debug: PointeeSized {
909
    #[doc = include_str!("fmt_trait_method_doc.md")]
910
    ///
911
    /// # Examples
912
    ///
913
    /// ```
914
    /// use std::fmt;
915
    ///
916
    /// struct Position {
917
    ///     longitude: f32,
918
    ///     latitude: f32,
919
    /// }
920
    ///
921
    /// impl fmt::Debug for Position {
922
    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
923
    ///         f.debug_tuple("")
924
    ///          .field(&self.longitude)
925
    ///          .field(&self.latitude)
926
    ///          .finish()
927
    ///     }
928
    /// }
929
    ///
930
    /// let position = Position { longitude: 1.987, latitude: 2.983 };
931
    /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
932
    ///
933
    /// assert_eq!(format!("{position:#?}"), "(
934
    ///     1.987,
935
    ///     2.983,
936
    /// )");
937
    /// ```
938
    #[stable(feature = "rust1", since = "1.0.0")]
939
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
940
}
941

            
942
// Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
943
#[cfg(not(feature = "ferrocene_certified"))]
944
pub(crate) mod macros {
945
    /// Derive macro generating an impl of the trait `Debug`.
946
    #[rustc_builtin_macro]
947
    #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
948
    #[allow_internal_unstable(core_intrinsics, fmt_helpers_for_derive)]
949
    pub macro Debug($item:item) {
950
        /* compiler built-in */
951
    }
952
}
953
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
954
#[doc(inline)]
955
#[cfg(not(feature = "ferrocene_certified"))]
956
pub use macros::Debug;
957

            
958
/// Format trait for an empty format, `{}`.
959
///
960
/// Implementing this trait for a type will automatically implement the
961
/// [`ToString`][tostring] trait for the type, allowing the usage
962
/// of the [`.to_string()`][tostring_function] method. Prefer implementing
963
/// the `Display` trait for a type, rather than [`ToString`][tostring].
964
///
965
/// `Display` is similar to [`Debug`], but `Display` is for user-facing
966
/// output, and so cannot be derived.
967
///
968
/// For more information on formatters, see [the module-level documentation][module].
969
///
970
/// [module]: ../../std/fmt/index.html
971
/// [tostring]: ../../std/string/trait.ToString.html
972
/// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
973
///
974
/// # Completeness and parseability
975
///
976
/// `Display` for a type might not necessarily be a lossless or complete representation of the type.
977
/// It may omit internal state, precision, or other information the type does not consider important
978
/// for user-facing output, as determined by the type. As such, the output of `Display` might not be
979
/// possible to parse, and even if it is, the result of parsing might not exactly match the original
980
/// value.
981
///
982
/// However, if a type has a lossless `Display` implementation whose output is meant to be
983
/// conveniently machine-parseable and not just meant for human consumption, then the type may wish
984
/// to accept the same format in `FromStr`, and document that usage. Having both `Display` and
985
/// `FromStr` implementations where the result of `Display` cannot be parsed with `FromStr` may
986
/// surprise users.
987
///
988
/// # Internationalization
989
///
990
/// Because a type can only have one `Display` implementation, it is often preferable
991
/// to only implement `Display` when there is a single most "obvious" way that
992
/// values can be formatted as text. This could mean formatting according to the
993
/// "invariant" culture and "undefined" locale, or it could mean that the type
994
/// display is designed for a specific culture/locale, such as developer logs.
995
///
996
/// If not all values have a justifiably canonical textual format or if you want
997
/// to support alternative formats not covered by the standard set of possible
998
/// [formatting traits], the most flexible approach is display adapters: methods
999
/// like [`str::escape_default`] or [`Path::display`] which create a wrapper
/// implementing `Display` to output the specific display format.
///
/// [formatting traits]: ../../std/fmt/index.html#formatting-traits
/// [`Path::display`]: ../../std/path/struct.Path.html#method.display
///
/// # Examples
///
/// Implementing `Display` on a type:
///
/// ```
/// use std::fmt;
///
/// struct Point {
///     x: i32,
///     y: i32,
/// }
///
/// impl fmt::Display for Point {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "({}, {})", self.x, self.y)
///     }
/// }
///
/// let origin = Point { x: 0, y: 0 };
///
/// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
/// ```
#[rustc_on_unimplemented(
    on(
        any(Self = "std::path::Path", Self = "std::path::PathBuf"),
        label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
        note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
                as they may contain non-Unicode data",
    ),
    on(
        from_desugaring = "FormatLiteral",
        note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead",
        label = "`{Self}` cannot be formatted with the default formatter",
    ),
    message = "`{Self}` doesn't implement `{This}`"
)]
#[doc(alias = "{}")]
#[rustc_diagnostic_item = "Display"]
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub trait Display: PointeeSized {
    #[doc = include_str!("fmt_trait_method_doc.md")]
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Position {
    ///     longitude: f32,
    ///     latitude: f32,
    /// }
    ///
    /// impl fmt::Display for Position {
    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         write!(f, "({}, {})", self.longitude, self.latitude)
    ///     }
    /// }
    ///
    /// assert_eq!(
    ///     "(1.987, 2.983)",
    ///     format!("{}", Position { longitude: 1.987, latitude: 2.983, }),
    /// );
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}
/// `o` formatting.
///
/// The `Octal` trait should format its output as a number in base-8.
///
/// For primitive signed integers (`i8` to `i128`, and `isize`),
/// negative values are formatted as the two’s complement representation.
///
/// The alternate flag, `#`, adds a `0o` in front of the output.
///
/// For more information on formatters, see [the module-level documentation][module].
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// Basic usage with `i32`:
///
/// ```
/// let x = 42; // 42 is '52' in octal
///
/// assert_eq!(format!("{x:o}"), "52");
/// assert_eq!(format!("{x:#o}"), "0o52");
///
/// assert_eq!(format!("{:o}", -16), "37777777760");
/// ```
///
/// Implementing `Octal` on a type:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::Octal for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = self.0;
///
///         fmt::Octal::fmt(&val, f) // delegate to i32's implementation
///     }
/// }
///
/// let l = Length(9);
///
/// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
///
/// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub trait Octal: PointeeSized {
    #[doc = include_str!("fmt_trait_method_doc.md")]
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}
/// `b` formatting.
///
/// The `Binary` trait should format its output as a number in binary.
///
/// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
/// negative values are formatted as the two’s complement representation.
///
/// The alternate flag, `#`, adds a `0b` in front of the output.
///
/// For more information on formatters, see [the module-level documentation][module].
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// Basic usage with [`i32`]:
///
/// ```
/// let x = 42; // 42 is '101010' in binary
///
/// assert_eq!(format!("{x:b}"), "101010");
/// assert_eq!(format!("{x:#b}"), "0b101010");
///
/// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
/// ```
///
/// Implementing `Binary` on a type:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::Binary for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = self.0;
///
///         fmt::Binary::fmt(&val, f) // delegate to i32's implementation
///     }
/// }
///
/// let l = Length(107);
///
/// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
///
/// assert_eq!(
///     // Note that the `0b` prefix added by `#` is included in the total width, so we
///     // need to add two to correctly display all 32 bits.
///     format!("l as binary is: {l:#034b}"),
///     "l as binary is: 0b00000000000000000000000001101011"
/// );
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub trait Binary: PointeeSized {
    #[doc = include_str!("fmt_trait_method_doc.md")]
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}
/// `x` formatting.
///
/// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
/// in lower case.
///
/// For primitive signed integers (`i8` to `i128`, and `isize`),
/// negative values are formatted as the two’s complement representation.
///
/// The alternate flag, `#`, adds a `0x` in front of the output.
///
/// For more information on formatters, see [the module-level documentation][module].
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// Basic usage with `i32`:
///
/// ```
/// let y = 42; // 42 is '2a' in hex
///
/// assert_eq!(format!("{y:x}"), "2a");
/// assert_eq!(format!("{y:#x}"), "0x2a");
///
/// assert_eq!(format!("{:x}", -16), "fffffff0");
/// ```
///
/// Implementing `LowerHex` on a type:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::LowerHex for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = self.0;
///
///         fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
///     }
/// }
///
/// let l = Length(9);
///
/// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
///
/// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub trait LowerHex: PointeeSized {
    #[doc = include_str!("fmt_trait_method_doc.md")]
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}
/// `X` formatting.
///
/// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
/// in upper case.
///
/// For primitive signed integers (`i8` to `i128`, and `isize`),
/// negative values are formatted as the two’s complement representation.
///
/// The alternate flag, `#`, adds a `0x` in front of the output.
///
/// For more information on formatters, see [the module-level documentation][module].
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// Basic usage with `i32`:
///
/// ```
/// let y = 42; // 42 is '2A' in hex
///
/// assert_eq!(format!("{y:X}"), "2A");
/// assert_eq!(format!("{y:#X}"), "0x2A");
///
/// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
/// ```
///
/// Implementing `UpperHex` on a type:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::UpperHex for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = self.0;
///
///         fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
///     }
/// }
///
/// let l = Length(i32::MAX);
///
/// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
///
/// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub trait UpperHex: PointeeSized {
    #[doc = include_str!("fmt_trait_method_doc.md")]
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}
/// `p` formatting.
///
/// The `Pointer` trait should format its output as a memory location. This is commonly presented
/// as hexadecimal. For more information on formatters, see [the module-level documentation][module].
///
/// Printing of pointers is not a reliable way to discover how Rust programs are implemented.
/// The act of reading an address changes the program itself, and may change how the data is represented
/// in memory, and may affect which optimizations are applied to the code.
///
/// The printed pointer values are not guaranteed to be stable nor unique identifiers of objects.
/// Rust allows moving values to different memory locations, and may reuse the same memory locations
/// for different purposes.
///
/// There is no guarantee that the printed value can be converted back to a pointer.
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// Basic usage with `&i32`:
///
/// ```
/// let x = &42;
///
/// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
/// ```
///
/// Implementing `Pointer` on a type:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::Pointer for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         // use `as` to convert to a `*const T`, which implements Pointer, which we can use
///
///         let ptr = self as *const Self;
///         fmt::Pointer::fmt(&ptr, f)
///     }
/// }
///
/// let l = Length(42);
///
/// println!("l is in memory here: {l:p}");
///
/// let l_ptr = format!("{l:018p}");
/// assert_eq!(l_ptr.len(), 18);
/// assert_eq!(&l_ptr[..2], "0x");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_diagnostic_item = "Pointer"]
#[cfg(not(feature = "ferrocene_certified"))]
pub trait Pointer: PointeeSized {
    #[doc = include_str!("fmt_trait_method_doc.md")]
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}
/// `e` formatting.
///
/// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
///
/// For more information on formatters, see [the module-level documentation][module].
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// Basic usage with `f64`:
///
/// ```
/// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
///
/// assert_eq!(format!("{x:e}"), "4.2e1");
/// ```
///
/// Implementing `LowerExp` on a type:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::LowerExp for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = f64::from(self.0);
///         fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
///     }
/// }
///
/// let l = Length(100);
///
/// assert_eq!(
///     format!("l in scientific notation is: {l:e}"),
///     "l in scientific notation is: 1e2"
/// );
///
/// assert_eq!(
///     format!("l in scientific notation is: {l:05e}"),
///     "l in scientific notation is: 001e2"
/// );
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub trait LowerExp: PointeeSized {
    #[doc = include_str!("fmt_trait_method_doc.md")]
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}
/// `E` formatting.
///
/// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
///
/// For more information on formatters, see [the module-level documentation][module].
///
/// [module]: ../../std/fmt/index.html
///
/// # Examples
///
/// Basic usage with `f64`:
///
/// ```
/// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
///
/// assert_eq!(format!("{x:E}"), "4.2E1");
/// ```
///
/// Implementing `UpperExp` on a type:
///
/// ```
/// use std::fmt;
///
/// struct Length(i32);
///
/// impl fmt::UpperExp for Length {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         let val = f64::from(self.0);
///         fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
///     }
/// }
///
/// let l = Length(100);
///
/// assert_eq!(
///     format!("l in scientific notation is: {l:E}"),
///     "l in scientific notation is: 1E2"
/// );
///
/// assert_eq!(
///     format!("l in scientific notation is: {l:05E}"),
///     "l in scientific notation is: 001E2"
/// );
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub trait UpperExp: PointeeSized {
    #[doc = include_str!("fmt_trait_method_doc.md")]
    #[stable(feature = "rust1", since = "1.0.0")]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}
/// Takes an output stream and an `Arguments` struct that can be precompiled with
/// the `format_args!` macro.
///
/// The arguments will be formatted according to the specified format string
/// into the output stream provided.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::fmt;
///
/// let mut output = String::new();
/// fmt::write(&mut output, format_args!("Hello {}!", "world"))
///     .expect("Error occurred while trying to write in String");
/// assert_eq!(output, "Hello world!");
/// ```
///
/// Please note that using [`write!`] might be preferable. Example:
///
/// ```
/// use std::fmt::Write;
///
/// let mut output = String::new();
/// write!(&mut output, "Hello {}!", "world")
///     .expect("Error occurred while trying to write in String");
/// assert_eq!(output, "Hello world!");
/// ```
///
/// [`write!`]: crate::write!
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
    let mut formatter = Formatter::new(output, FormattingOptions::new());
    let mut idx = 0;
    match args.fmt {
        None => {
            // We can use default formatting parameters for all arguments.
            for (i, arg) in args.args.iter().enumerate() {
                // SAFETY: args.args and args.pieces come from the same Arguments,
                // which guarantees the indexes are always within bounds.
                let piece = unsafe { args.pieces.get_unchecked(i) };
                if !piece.is_empty() {
                    formatter.buf.write_str(*piece)?;
                }
                // SAFETY: There are no formatting parameters and hence no
                // count arguments.
                unsafe {
                    arg.fmt(&mut formatter)?;
                }
                idx += 1;
            }
        }
        Some(fmt) => {
            // Every spec has a corresponding argument that is preceded by
            // a string piece.
            for (i, arg) in fmt.iter().enumerate() {
                // SAFETY: fmt and args.pieces come from the same Arguments,
                // which guarantees the indexes are always within bounds.
                let piece = unsafe { args.pieces.get_unchecked(i) };
                if !piece.is_empty() {
                    formatter.buf.write_str(*piece)?;
                }
                // SAFETY: arg and args.args come from the same Arguments,
                // which guarantees the indexes are always within bounds.
                unsafe { run(&mut formatter, arg, args.args) }?;
                idx += 1;
            }
        }
    }
    // There can be only one trailing string piece left.
    if let Some(piece) = args.pieces.get(idx) {
        formatter.buf.write_str(*piece)?;
    }
    Ok(())
}
#[cfg(not(feature = "ferrocene_certified"))]
unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::Placeholder, args: &[rt::Argument<'_>]) -> Result {
    let (width, precision) =
        // SAFETY: arg and args come from the same Arguments,
        // which guarantees the indexes are always within bounds.
        unsafe { (getcount(args, &arg.width), getcount(args, &arg.precision)) };
    let options = FormattingOptions { flags: arg.flags, width, precision };
    // Extract the correct argument
    debug_assert!(arg.position < args.len());
    // SAFETY: arg and args come from the same Arguments,
    // which guarantees its index is always within bounds.
    let value = unsafe { args.get_unchecked(arg.position) };
    // Set all the formatting options.
    fmt.options = options;
    // Then actually do some printing
    // SAFETY: this is a placeholder argument.
    unsafe { value.fmt(fmt) }
}
#[cfg(not(feature = "ferrocene_certified"))]
unsafe fn getcount(args: &[rt::Argument<'_>], cnt: &rt::Count) -> u16 {
    match *cnt {
        rt::Count::Is(n) => n,
        rt::Count::Implied => 0,
        rt::Count::Param(i) => {
            debug_assert!(i < args.len());
            // SAFETY: cnt and args come from the same Arguments,
            // which guarantees this index is always within bounds.
            unsafe { args.get_unchecked(i).as_u16().unwrap_unchecked() }
        }
    }
}
/// Padding after the end of something. Returned by `Formatter::padding`.
#[must_use = "don't forget to write the post padding"]
#[cfg(not(feature = "ferrocene_certified"))]
pub(crate) struct PostPadding {
    fill: char,
    padding: u16,
}
#[cfg(not(feature = "ferrocene_certified"))]
impl PostPadding {
    fn new(fill: char, padding: u16) -> PostPadding {
        PostPadding { fill, padding }
    }
    /// Writes this post padding.
    pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
        for _ in 0..self.padding {
            f.buf.write_char(self.fill)?;
        }
        Ok(())
    }
}
#[cfg(not(feature = "ferrocene_certified"))]
impl<'a> Formatter<'a> {
    fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
    where
        'b: 'c,
        F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
    {
        Formatter {
            // We want to change this
            buf: wrap(self.buf),
            // And preserve these
            options: self.options,
        }
    }
    // Helper methods used for padding and processing formatting arguments that
    // all formatting traits can use.
    /// Performs the correct padding for an integer which has already been
    /// emitted into a str. The str should *not* contain the sign for the
    /// integer, that will be added by this method.
    ///
    /// # Arguments
    ///
    /// * is_nonnegative - whether the original integer was either positive or zero.
    /// * prefix - if the '#' character (Alternate) is provided, this
    ///   is the prefix to put in front of the number.
    /// * buf - the byte array that the number has been formatted into
    ///
    /// This function will correctly account for the flags provided as well as
    /// the minimum width. It will not take precision into account.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo { nb: i32 }
    ///
    /// impl Foo {
    ///     fn new(nb: i32) -> Foo {
    ///         Foo {
    ///             nb,
    ///         }
    ///     }
    /// }
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         // We need to remove "-" from the number output.
    ///         let tmp = self.nb.abs().to_string();
    ///
    ///         formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{}", Foo::new(2)), "2");
    /// assert_eq!(format!("{}", Foo::new(-1)), "-1");
    /// assert_eq!(format!("{}", Foo::new(0)), "0");
    /// assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
    /// assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
        let mut width = buf.len();
        let mut sign = None;
        if !is_nonnegative {
            sign = Some('-');
            width += 1;
        } else if self.sign_plus() {
            sign = Some('+');
            width += 1;
        }
        let prefix = if self.alternate() {
            width += prefix.chars().count();
            Some(prefix)
        } else {
            None
        };
        // Writes the sign if it exists, and then the prefix if it was requested
        #[inline(never)]
        fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
            if let Some(c) = sign {
                f.buf.write_char(c)?;
            }
            if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
        }
        // The `width` field is more of a `min-width` parameter at this point.
        let min = self.options.width;
        if width >= usize::from(min) {
            // We're over the minimum width, so then we can just write the bytes.
            write_prefix(self, sign, prefix)?;
            self.buf.write_str(buf)
        } else if self.sign_aware_zero_pad() {
            // The sign and prefix goes before the padding if the fill character
            // is zero
            let old_options = self.options;
            self.options.fill('0').align(Some(Alignment::Right));
            write_prefix(self, sign, prefix)?;
            let post_padding = self.padding(min - width as u16, Alignment::Right)?;
            self.buf.write_str(buf)?;
            post_padding.write(self)?;
            self.options = old_options;
            Ok(())
        } else {
            // Otherwise, the sign and prefix goes after the padding
            let post_padding = self.padding(min - width as u16, Alignment::Right)?;
            write_prefix(self, sign, prefix)?;
            self.buf.write_str(buf)?;
            post_padding.write(self)
        }
    }
    /// Takes a string slice and emits it to the internal buffer after applying
    /// the relevant formatting flags specified.
    ///
    /// The flags recognized for generic strings are:
    ///
    /// * width - the minimum width of what to emit
    /// * fill/align - what to emit and where to emit it if the string
    ///                provided needs to be padded
    /// * precision - the maximum length to emit, the string is truncated if it
    ///               is longer than this length
    ///
    /// Notably this function ignores the `flag` parameters.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo;
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         formatter.pad("Foo")
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{Foo:<4}"), "Foo ");
    /// assert_eq!(format!("{Foo:0>4}"), "0Foo");
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn pad(&mut self, s: &str) -> Result {
        // Make sure there's a fast path up front.
        if self.options.flags & (flags::WIDTH_FLAG | flags::PRECISION_FLAG) == 0 {
            return self.buf.write_str(s);
        }
        // The `precision` field can be interpreted as a maximum width for the
        // string being formatted.
        let (s, char_count) = if let Some(max_char_count) = self.options.get_precision() {
            let mut iter = s.char_indices();
            let remaining = match iter.advance_by(usize::from(max_char_count)) {
                Ok(()) => 0,
                Err(remaining) => remaining.get(),
            };
            // SAFETY: The offset of `.char_indices()` is guaranteed to be
            // in-bounds and between character boundaries.
            let truncated = unsafe { s.get_unchecked(..iter.offset()) };
            (truncated, usize::from(max_char_count) - remaining)
        } else {
            // Use the optimized char counting algorithm for the full string.
            (s, s.chars().count())
        };
        // The `width` field is more of a minimum width parameter at this point.
        if char_count < usize::from(self.options.width) {
            // If we're under the minimum width, then fill up the minimum width
            // with the specified string + some alignment.
            let post_padding =
                self.padding(self.options.width - char_count as u16, Alignment::Left)?;
            self.buf.write_str(s)?;
            post_padding.write(self)
        } else {
            // If we're over the minimum width or there is no minimum width, we
            // can just emit the string.
            self.buf.write_str(s)
        }
    }
    /// Writes the pre-padding and returns the unwritten post-padding.
    ///
    /// Callers are responsible for ensuring post-padding is written after the
    /// thing that is being padded.
    pub(crate) fn padding(
        &mut self,
        padding: u16,
        default: Alignment,
    ) -> result::Result<PostPadding, Error> {
        let align = self.options.get_align().unwrap_or(default);
        let fill = self.options.get_fill();
        let padding_left = match align {
            Alignment::Left => 0,
            Alignment::Right => padding,
            Alignment::Center => padding / 2,
        };
        for _ in 0..padding_left {
            self.buf.write_char(fill)?;
        }
        Ok(PostPadding::new(fill, padding - padding_left))
    }
    /// Takes the formatted parts and applies the padding.
    ///
    /// Assumes that the caller already has rendered the parts with required precision,
    /// so that `self.precision` can be ignored.
    ///
    /// # Safety
    ///
    /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
    unsafe fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
        if self.options.width == 0 {
            // this is the common case and we take a shortcut
            // SAFETY: Per the precondition.
            unsafe { self.write_formatted_parts(formatted) }
        } else {
            // for the sign-aware zero padding, we render the sign first and
            // behave as if we had no sign from the beginning.
            let mut formatted = formatted.clone();
            let mut width = self.options.width;
            let old_options = self.options;
            if self.sign_aware_zero_pad() {
                // a sign always goes first
                let sign = formatted.sign;
                self.buf.write_str(sign)?;
                // remove the sign from the formatted parts
                formatted.sign = "";
                width = width.saturating_sub(sign.len() as u16);
                self.options.fill('0').align(Some(Alignment::Right));
            }
            // remaining parts go through the ordinary padding process.
            let len = formatted.len();
            let ret = if usize::from(width) <= len {
                // no padding
                // SAFETY: Per the precondition.
                unsafe { self.write_formatted_parts(&formatted) }
            } else {
                let post_padding = self.padding(width - len as u16, Alignment::Right)?;
                // SAFETY: Per the precondition.
                unsafe {
                    self.write_formatted_parts(&formatted)?;
                }
                post_padding.write(self)
            };
            self.options = old_options;
            ret
        }
    }
    /// # Safety
    ///
    /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
    unsafe fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
        unsafe fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
            // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
            // It's safe to use for `numfmt::Part::Num` since every char `c` is between
            // `b'0'` and `b'9'`, which means `s` is valid UTF-8. It's safe to use for
            // `numfmt::Part::Copy` due to this function's precondition.
            buf.write_str(unsafe { str::from_utf8_unchecked(s) })
        }
        if !formatted.sign.is_empty() {
            self.buf.write_str(formatted.sign)?;
        }
        for part in formatted.parts {
            match *part {
                numfmt::Part::Zero(mut nzeroes) => {
                    const ZEROES: &str = // 64 zeroes
                        "0000000000000000000000000000000000000000000000000000000000000000";
                    while nzeroes > ZEROES.len() {
                        self.buf.write_str(ZEROES)?;
                        nzeroes -= ZEROES.len();
                    }
                    if nzeroes > 0 {
                        self.buf.write_str(&ZEROES[..nzeroes])?;
                    }
                }
                numfmt::Part::Num(mut v) => {
                    let mut s = [0; 5];
                    let len = part.len();
                    for c in s[..len].iter_mut().rev() {
                        *c = b'0' + (v % 10) as u8;
                        v /= 10;
                    }
                    // SAFETY: Per the precondition.
                    unsafe {
                        write_bytes(self.buf, &s[..len])?;
                    }
                }
                // SAFETY: Per the precondition.
                numfmt::Part::Copy(buf) => unsafe {
                    write_bytes(self.buf, buf)?;
                },
            }
        }
        Ok(())
    }
    /// Writes some data to the underlying buffer contained within this
    /// formatter.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo;
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         formatter.write_str("Foo")
    ///         // This is equivalent to:
    ///         // write!(formatter, "Foo")
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{Foo}"), "Foo");
    /// assert_eq!(format!("{Foo:0>8}"), "Foo");
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn write_str(&mut self, data: &str) -> Result {
        self.buf.write_str(data)
    }
    /// Glue for usage of the [`write!`] macro with implementors of this trait.
    ///
    /// This method should generally not be invoked manually, but rather through
    /// the [`write!`] macro itself.
    ///
    /// Writes some formatted information into this instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         formatter.write_fmt(format_args!("Foo {}", self.0))
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{}", Foo(-1)), "Foo -1");
    /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    #[inline]
21928
    pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
21928
        if let Some(s) = fmt.as_statically_known_str() {
13
            self.buf.write_str(s)
        } else {
21915
            write(self.buf, fmt)
        }
21928
    }
    /// Returns flags for formatting.
    #[must_use]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[deprecated(
        since = "1.24.0",
        note = "use the `sign_plus`, `sign_minus`, `alternate`, \
                or `sign_aware_zero_pad` methods instead"
    )]
    pub fn flags(&self) -> u32 {
        // Extract the debug upper/lower hex, zero pad, alternate, and plus/minus flags
        // to stay compatible with older versions of Rust.
        self.options.flags >> 21 & 0x3F
    }
    /// Returns the character used as 'fill' whenever there is alignment.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo;
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         let c = formatter.fill();
    ///         if let Some(width) = formatter.width() {
    ///             for _ in 0..width {
    ///                 write!(formatter, "{c}")?;
    ///             }
    ///             Ok(())
    ///         } else {
    ///             write!(formatter, "{c}")
    ///         }
    ///     }
    /// }
    ///
    /// // We set alignment to the right with ">".
    /// assert_eq!(format!("{Foo:G>3}"), "GGG");
    /// assert_eq!(format!("{Foo:t>6}"), "tttttt");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn fill(&self) -> char {
        self.options.get_fill()
    }
    /// Returns a flag indicating what form of alignment was requested.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt::{self, Alignment};
    ///
    /// struct Foo;
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         let s = if let Some(s) = formatter.align() {
    ///             match s {
    ///                 Alignment::Left    => "left",
    ///                 Alignment::Right   => "right",
    ///                 Alignment::Center  => "center",
    ///             }
    ///         } else {
    ///             "into the void"
    ///         };
    ///         write!(formatter, "{s}")
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{Foo:<}"), "left");
    /// assert_eq!(format!("{Foo:>}"), "right");
    /// assert_eq!(format!("{Foo:^}"), "center");
    /// assert_eq!(format!("{Foo}"), "into the void");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags_align", since = "1.28.0")]
    pub fn align(&self) -> Option<Alignment> {
        self.options.get_align()
    }
    /// Returns the optionally specified integer width that the output should be.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         if let Some(width) = formatter.width() {
    ///             // If we received a width, we use it
    ///             write!(formatter, "{:width$}", format!("Foo({})", self.0), width = width)
    ///         } else {
    ///             // Otherwise we do nothing special
    ///             write!(formatter, "Foo({})", self.0)
    ///         }
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{:10}", Foo(23)), "Foo(23)   ");
    /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn width(&self) -> Option<usize> {
        if self.options.flags & flags::WIDTH_FLAG == 0 {
            None
        } else {
            Some(self.options.width as usize)
        }
    }
    /// Returns the optionally specified precision for numeric types.
    /// Alternatively, the maximum width for string types.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(f32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         if let Some(precision) = formatter.precision() {
    ///             // If we received a precision, we use it.
    ///             write!(formatter, "Foo({1:.*})", precision, self.0)
    ///         } else {
    ///             // Otherwise we default to 2.
    ///             write!(formatter, "Foo({:.2})", self.0)
    ///         }
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
    /// assert_eq!(format!("{}", Foo(23.2)), "Foo(23.20)");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn precision(&self) -> Option<usize> {
        if self.options.flags & flags::PRECISION_FLAG == 0 {
            None
        } else {
            Some(self.options.precision as usize)
        }
    }
    /// Determines if the `+` flag was specified.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         if formatter.sign_plus() {
    ///             write!(formatter,
    ///                    "Foo({}{})",
    ///                    if self.0 < 0 { '-' } else { '+' },
    ///                    self.0.abs())
    ///         } else {
    ///             write!(formatter, "Foo({})", self.0)
    ///         }
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{:+}", Foo(23)), "Foo(+23)");
    /// assert_eq!(format!("{:+}", Foo(-23)), "Foo(-23)");
    /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn sign_plus(&self) -> bool {
        self.options.flags & flags::SIGN_PLUS_FLAG != 0
    }
    /// Determines if the `-` flag was specified.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         if formatter.sign_minus() {
    ///             // You want a minus sign? Have one!
    ///             write!(formatter, "-Foo({})", self.0)
    ///         } else {
    ///             write!(formatter, "Foo({})", self.0)
    ///         }
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{:-}", Foo(23)), "-Foo(23)");
    /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn sign_minus(&self) -> bool {
        self.options.flags & flags::SIGN_MINUS_FLAG != 0
    }
    /// Determines if the `#` flag was specified.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         if formatter.alternate() {
    ///             write!(formatter, "Foo({})", self.0)
    ///         } else {
    ///             write!(formatter, "{}", self.0)
    ///         }
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{:#}", Foo(23)), "Foo(23)");
    /// assert_eq!(format!("{}", Foo(23)), "23");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
113179
    pub fn alternate(&self) -> bool {
113179
        self.options.flags & flags::ALTERNATE_FLAG != 0
113179
    }
    /// Determines if the `0` flag was specified.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// struct Foo(i32);
    ///
    /// impl fmt::Display for Foo {
    ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         assert!(formatter.sign_aware_zero_pad());
    ///         assert_eq!(formatter.width(), Some(4));
    ///         // We ignore the formatter's options.
    ///         write!(formatter, "{}", self.0)
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{:04}", Foo(23)), "23");
    /// ```
    #[must_use]
    #[stable(feature = "fmt_flags", since = "1.5.0")]
    pub fn sign_aware_zero_pad(&self) -> bool {
        self.options.flags & flags::SIGN_AWARE_ZERO_PAD_FLAG != 0
    }
    // FIXME: Decide what public API we want for these two flags.
    // https://github.com/rust-lang/rust/issues/48584
114
    fn debug_lower_hex(&self) -> bool {
114
        self.options.flags & flags::DEBUG_LOWER_HEX_FLAG != 0
114
    }
110
    fn debug_upper_hex(&self) -> bool {
110
        self.options.flags & flags::DEBUG_UPPER_HEX_FLAG != 0
110
    }
    /// Creates a [`DebugStruct`] builder designed to assist with creation of
    /// [`fmt::Debug`] implementations for structs.
    ///
    /// [`fmt::Debug`]: self::Debug
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt;
    /// use std::net::Ipv4Addr;
    ///
    /// struct Foo {
    ///     bar: i32,
    ///     baz: String,
    ///     addr: Ipv4Addr,
    /// }
    ///
    /// impl fmt::Debug for Foo {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         fmt.debug_struct("Foo")
    ///             .field("bar", &self.bar)
    ///             .field("baz", &self.baz)
    ///             .field("addr", &format_args!("{}", self.addr))
    ///             .finish()
    ///     }
    /// }
    ///
    /// assert_eq!(
    ///     "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
    ///     format!("{:?}", Foo {
    ///         bar: 10,
    ///         baz: "Hello World".to_string(),
    ///         addr: Ipv4Addr::new(127, 0, 0, 1),
    ///     })
    /// );
    /// ```
    #[stable(feature = "debug_builders", since = "1.2.0")]
    pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
        builders::debug_struct_new(self, name)
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. `debug_struct_fields_finish` is more general, but this is
    /// faster for 1 field.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_struct_field1_finish<'b>(
        &'b mut self,
        name: &str,
        name1: &str,
        value1: &dyn Debug,
    ) -> Result {
        let mut builder = builders::debug_struct_new(self, name);
        builder.field(name1, value1);
        builder.finish()
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. `debug_struct_fields_finish` is more general, but this is
    /// faster for 2 fields.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_struct_field2_finish<'b>(
        &'b mut self,
        name: &str,
        name1: &str,
        value1: &dyn Debug,
        name2: &str,
        value2: &dyn Debug,
    ) -> Result {
        let mut builder = builders::debug_struct_new(self, name);
        builder.field(name1, value1);
        builder.field(name2, value2);
        builder.finish()
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. `debug_struct_fields_finish` is more general, but this is
    /// faster for 3 fields.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_struct_field3_finish<'b>(
        &'b mut self,
        name: &str,
        name1: &str,
        value1: &dyn Debug,
        name2: &str,
        value2: &dyn Debug,
        name3: &str,
        value3: &dyn Debug,
    ) -> Result {
        let mut builder = builders::debug_struct_new(self, name);
        builder.field(name1, value1);
        builder.field(name2, value2);
        builder.field(name3, value3);
        builder.finish()
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. `debug_struct_fields_finish` is more general, but this is
    /// faster for 4 fields.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_struct_field4_finish<'b>(
        &'b mut self,
        name: &str,
        name1: &str,
        value1: &dyn Debug,
        name2: &str,
        value2: &dyn Debug,
        name3: &str,
        value3: &dyn Debug,
        name4: &str,
        value4: &dyn Debug,
    ) -> Result {
        let mut builder = builders::debug_struct_new(self, name);
        builder.field(name1, value1);
        builder.field(name2, value2);
        builder.field(name3, value3);
        builder.field(name4, value4);
        builder.finish()
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. `debug_struct_fields_finish` is more general, but this is
    /// faster for 5 fields.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_struct_field5_finish<'b>(
        &'b mut self,
        name: &str,
        name1: &str,
        value1: &dyn Debug,
        name2: &str,
        value2: &dyn Debug,
        name3: &str,
        value3: &dyn Debug,
        name4: &str,
        value4: &dyn Debug,
        name5: &str,
        value5: &dyn Debug,
    ) -> Result {
        let mut builder = builders::debug_struct_new(self, name);
        builder.field(name1, value1);
        builder.field(name2, value2);
        builder.field(name3, value3);
        builder.field(name4, value4);
        builder.field(name5, value5);
        builder.finish()
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller binaries.
    /// For the cases not covered by `debug_struct_field[12345]_finish`.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_struct_fields_finish<'b>(
        &'b mut self,
        name: &str,
        names: &[&str],
        values: &[&dyn Debug],
    ) -> Result {
        assert_eq!(names.len(), values.len());
        let mut builder = builders::debug_struct_new(self, name);
        for (name, value) in iter::zip(names, values) {
            builder.field(name, value);
        }
        builder.finish()
    }
    /// Creates a `DebugTuple` builder designed to assist with creation of
    /// `fmt::Debug` implementations for tuple structs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt;
    /// use std::marker::PhantomData;
    ///
    /// struct Foo<T>(i32, String, PhantomData<T>);
    ///
    /// impl<T> fmt::Debug for Foo<T> {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         fmt.debug_tuple("Foo")
    ///             .field(&self.0)
    ///             .field(&self.1)
    ///             .field(&format_args!("_"))
    ///             .finish()
    ///     }
    /// }
    ///
    /// assert_eq!(
    ///     "Foo(10, \"Hello\", _)",
    ///     format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
    /// );
    /// ```
    #[stable(feature = "debug_builders", since = "1.2.0")]
    pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
        builders::debug_tuple_new(self, name)
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
    /// for 1 field.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result {
        let mut builder = builders::debug_tuple_new(self, name);
        builder.field(value1);
        builder.finish()
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
    /// for 2 fields.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_tuple_field2_finish<'b>(
        &'b mut self,
        name: &str,
        value1: &dyn Debug,
        value2: &dyn Debug,
    ) -> Result {
        let mut builder = builders::debug_tuple_new(self, name);
        builder.field(value1);
        builder.field(value2);
        builder.finish()
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
    /// for 3 fields.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_tuple_field3_finish<'b>(
        &'b mut self,
        name: &str,
        value1: &dyn Debug,
        value2: &dyn Debug,
        value3: &dyn Debug,
    ) -> Result {
        let mut builder = builders::debug_tuple_new(self, name);
        builder.field(value1);
        builder.field(value2);
        builder.field(value3);
        builder.finish()
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
    /// for 4 fields.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_tuple_field4_finish<'b>(
        &'b mut self,
        name: &str,
        value1: &dyn Debug,
        value2: &dyn Debug,
        value3: &dyn Debug,
        value4: &dyn Debug,
    ) -> Result {
        let mut builder = builders::debug_tuple_new(self, name);
        builder.field(value1);
        builder.field(value2);
        builder.field(value3);
        builder.field(value4);
        builder.finish()
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
    /// for 5 fields.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_tuple_field5_finish<'b>(
        &'b mut self,
        name: &str,
        value1: &dyn Debug,
        value2: &dyn Debug,
        value3: &dyn Debug,
        value4: &dyn Debug,
        value5: &dyn Debug,
    ) -> Result {
        let mut builder = builders::debug_tuple_new(self, name);
        builder.field(value1);
        builder.field(value2);
        builder.field(value3);
        builder.field(value4);
        builder.field(value5);
        builder.finish()
    }
    /// Shrinks `derive(Debug)` code, for faster compilation and smaller
    /// binaries. For the cases not covered by `debug_tuple_field[12345]_finish`.
    #[doc(hidden)]
    #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
    pub fn debug_tuple_fields_finish<'b>(
        &'b mut self,
        name: &str,
        values: &[&dyn Debug],
    ) -> Result {
        let mut builder = builders::debug_tuple_new(self, name);
        for value in values {
            builder.field(value);
        }
        builder.finish()
    }
    /// Creates a `DebugList` builder designed to assist with creation of
    /// `fmt::Debug` implementations for list-like structures.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt;
    ///
    /// struct Foo(Vec<i32>);
    ///
    /// impl fmt::Debug for Foo {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         fmt.debug_list().entries(self.0.iter()).finish()
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
    /// ```
    #[stable(feature = "debug_builders", since = "1.2.0")]
    pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
        builders::debug_list_new(self)
    }
    /// Creates a `DebugSet` builder designed to assist with creation of
    /// `fmt::Debug` implementations for set-like structures.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt;
    ///
    /// struct Foo(Vec<i32>);
    ///
    /// impl fmt::Debug for Foo {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         fmt.debug_set().entries(self.0.iter()).finish()
    ///     }
    /// }
    ///
    /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
    /// ```
    ///
    /// [`format_args!`]: crate::format_args
    ///
    /// In this more complex example, we use [`format_args!`] and `.debug_set()`
    /// to build a list of match arms:
    ///
    /// ```rust
    /// use std::fmt;
    ///
    /// struct Arm<'a, L, R>(&'a (L, R));
    /// struct Table<'a, K, V>(&'a [(K, V)], V);
    ///
    /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
    /// where
    ///     L: 'a + fmt::Debug, R: 'a + fmt::Debug
    /// {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         L::fmt(&(self.0).0, fmt)?;
    ///         fmt.write_str(" => ")?;
    ///         R::fmt(&(self.0).1, fmt)
    ///     }
    /// }
    ///
    /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
    /// where
    ///     K: 'a + fmt::Debug, V: 'a + fmt::Debug
    /// {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         fmt.debug_set()
    ///         .entries(self.0.iter().map(Arm))
    ///         .entry(&Arm(&(format_args!("_"), &self.1)))
    ///         .finish()
    ///     }
    /// }
    /// ```
    #[stable(feature = "debug_builders", since = "1.2.0")]
    pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
        builders::debug_set_new(self)
    }
    /// Creates a `DebugMap` builder designed to assist with creation of
    /// `fmt::Debug` implementations for map-like structures.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::fmt;
    ///
    /// struct Foo(Vec<(String, i32)>);
    ///
    /// impl fmt::Debug for Foo {
    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
    ///     }
    /// }
    ///
    /// assert_eq!(
    ///     format!("{:?}",  Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
    ///     r#"{"A": 10, "B": 11}"#
    ///  );
    /// ```
    #[stable(feature = "debug_builders", since = "1.2.0")]
    pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
        builders::debug_map_new(self)
    }
    /// Returns the sign of this formatter (`+` or `-`).
    #[unstable(feature = "formatting_options", issue = "118117")]
    pub const fn sign(&self) -> Option<Sign> {
        self.options.get_sign()
    }
    /// Returns the formatting options this formatter corresponds to.
    #[unstable(feature = "formatting_options", issue = "118117")]
    pub const fn options(&self) -> FormattingOptions {
        self.options
    }
}
#[stable(since = "1.2.0", feature = "formatter_write")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Write for Formatter<'_> {
    fn write_str(&mut self, s: &str) -> Result {
        self.buf.write_str(s)
    }
    fn write_char(&mut self, c: char) -> Result {
        self.buf.write_char(c)
    }
    #[inline]
    fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
        if let Some(s) = args.as_statically_known_str() {
            self.buf.write_str(s)
        } else {
            write(self.buf, args)
        }
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Display::fmt("an error occurred when formatting an argument", f)
    }
}
// Implementations of the core formatting traits
#[cfg(not(feature = "ferrocene_certified"))]
macro_rules! fmt_refs {
    ($($tr:ident),*) => {
        $(
        #[stable(feature = "rust1", since = "1.0.0")]
        impl<T: PointeeSized + $tr> $tr for &T {
18145
            fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
        }
        #[stable(feature = "rust1", since = "1.0.0")]
        impl<T: PointeeSized + $tr> $tr for &mut T {
            fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
        }
        )*
    }
}
#[cfg(not(feature = "ferrocene_certified"))]
fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
#[unstable(feature = "never_type", issue = "35121")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Debug for ! {
    #[inline]
    fn fmt(&self, _: &mut Formatter<'_>) -> Result {
        *self
    }
}
#[unstable(feature = "never_type", issue = "35121")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Display for ! {
    #[inline]
    fn fmt(&self, _: &mut Formatter<'_>) -> Result {
        *self
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Debug for bool {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Display::fmt(self, f)
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Display for bool {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Display::fmt(if *self { "true" } else { "false" }, f)
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Debug for str {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.write_char('"')?;
        // substring we know is printable
        let mut printable_range = 0..0;
        fn needs_escape(b: u8) -> bool {
            b > 0x7E || b < 0x20 || b == b'\\' || b == b'"'
        }
        // the loop here first skips over runs of printable ASCII as a fast path.
        // other chars (unicode, or ASCII that needs escaping) are then handled per-`char`.
        let mut rest = self;
        while rest.len() > 0 {
            let Some(non_printable_start) = rest.as_bytes().iter().position(|&b| needs_escape(b))
            else {
                printable_range.end += rest.len();
                break;
            };
            printable_range.end += non_printable_start;
            // SAFETY: the position was derived from an iterator, so is known to be within bounds, and at a char boundary
            rest = unsafe { rest.get_unchecked(non_printable_start..) };
            let mut chars = rest.chars();
            if let Some(c) = chars.next() {
                let esc = c.escape_debug_ext(EscapeDebugExtArgs {
                    escape_grapheme_extended: true,
                    escape_single_quote: false,
                    escape_double_quote: true,
                });
                if esc.len() != 1 {
                    f.write_str(&self[printable_range.clone()])?;
                    Display::fmt(&esc, f)?;
                    printable_range.start = printable_range.end + c.len_utf8();
                }
                printable_range.end += c.len_utf8();
            }
            rest = chars.as_str();
        }
        f.write_str(&self[printable_range])?;
        f.write_char('"')
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Display for str {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.pad(self)
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Debug for char {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.write_char('\'')?;
        let esc = self.escape_debug_ext(EscapeDebugExtArgs {
            escape_grapheme_extended: true,
            escape_single_quote: true,
            escape_double_quote: false,
        });
        Display::fmt(&esc, f)?;
        f.write_char('\'')
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Display for char {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        if f.options.flags & (flags::WIDTH_FLAG | flags::PRECISION_FLAG) == 0 {
            f.write_char(*self)
        } else {
            f.pad(self.encode_utf8(&mut [0; MAX_LEN_UTF8]))
        }
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> Pointer for *const T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        if <<T as core::ptr::Pointee>::Metadata as core::unit::IsUnit>::is_unit() {
            pointer_fmt_inner(self.expose_provenance(), f)
        } else {
            f.debug_struct("Pointer")
                .field_with("addr", |f| pointer_fmt_inner(self.expose_provenance(), f))
                .field("metadata", &core::ptr::metadata(*self))
                .finish()
        }
    }
}
/// Since the formatting will be identical for all pointer types, uses a
/// non-monomorphized implementation for the actual formatting to reduce the
/// amount of codegen work needed.
///
/// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
/// `fn(...) -> ...` without using [problematic] "Oxford Casts".
///
/// [problematic]: https://github.com/rust-lang/rust/issues/95489
#[cfg(not(feature = "ferrocene_certified"))]
pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
    let old_options = f.options;
    // The alternate flag is already treated by LowerHex as being special-
    // it denotes whether to prefix with 0x. We use it to work out whether
    // or not to zero extend, and then unconditionally set it to get the
    // prefix.
    if f.options.get_alternate() {
        f.options.sign_aware_zero_pad(true);
        if f.options.get_width().is_none() {
            f.options.width(Some((usize::BITS / 4) as u16 + 2));
        }
    }
    f.options.alternate(true);
    let ret = LowerHex::fmt(&ptr_addr, f);
    f.options = old_options;
    ret
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> Pointer for *mut T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Pointer::fmt(&(*self as *const T), f)
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> Pointer for &T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Pointer::fmt(&(*self as *const T), f)
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> Pointer for &mut T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Pointer::fmt(&(&**self as *const T), f)
    }
}
// Implementation of Display/Debug for various core types
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> Debug for *const T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Pointer::fmt(self, f)
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> Debug for *mut T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Pointer::fmt(self, f)
    }
}
#[cfg(not(feature = "ferrocene_certified"))]
macro_rules! peel {
    ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
}
#[cfg(not(feature = "ferrocene_certified"))]
macro_rules! tuple {
    () => ();
    ( $($name:ident,)+ ) => (
        maybe_tuple_doc! {
            $($name)+ @
            #[stable(feature = "rust1", since = "1.0.0")]
            impl<$($name:Debug),+> Debug for ($($name,)+) {
                #[allow(non_snake_case, unused_assignments)]
                fn fmt(&self, f: &mut Formatter<'_>) -> Result {
                    let mut builder = f.debug_tuple("");
                    let ($(ref $name,)+) = *self;
                    $(
                        builder.field(&$name);
                    )+
                    builder.finish()
                }
            }
        }
        peel! { $($name,)+ }
    )
}
#[cfg(not(feature = "ferrocene_certified"))]
macro_rules! maybe_tuple_doc {
    ($a:ident @ #[$meta:meta] $item:item) => {
        #[doc(fake_variadic)]
        #[doc = "This trait is implemented for tuples up to twelve items long."]
        #[$meta]
        $item
    };
    ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
        #[doc(hidden)]
        #[$meta]
        $item
    };
}
#[cfg(not(feature = "ferrocene_certified"))]
tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: Debug> Debug for [T] {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_list().entries(self.iter()).finish()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl Debug for () {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.pad("()")
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: ?Sized> Debug for PhantomData<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: Copy + Debug> Debug for Cell<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("Cell").field("value", &self.get()).finish()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: ?Sized + Debug> Debug for RefCell<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        let mut d = f.debug_struct("RefCell");
        match self.try_borrow() {
            Ok(borrow) => d.field("value", &borrow),
            Err(_) => d.field("value", &format_args!("<borrowed>")),
        };
        d.finish()
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Debug::fmt(&**self, f)
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Debug::fmt(&*(self.deref()), f)
    }
}
#[stable(feature = "core_impl_debug", since = "1.9.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: ?Sized> Debug for UnsafeCell<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("UnsafeCell").finish_non_exhaustive()
    }
}
#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
    }
}
// If you expected tests to be here, look instead at coretests/tests/fmt/;
// it's a lot easier than creating all of the rt::Piece structures here.
// There are also tests in alloctests/tests/fmt.rs, for those that need allocations.