]> git.lizzy.rs Git - rust.git/blob - library/core/src/fmt/mod.rs
docs: clean up trait docs for tuples
[rust.git] / library / core / src / fmt / mod.rs
1 //! Utilities for formatting and printing strings.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 use crate::cell::{Cell, Ref, RefCell, RefMut, SyncUnsafeCell, UnsafeCell};
6 use crate::char::EscapeDebugExtArgs;
7 use crate::marker::PhantomData;
8 use crate::mem;
9 use crate::num::fmt as numfmt;
10 use crate::ops::Deref;
11 use crate::result;
12 use crate::str;
13
14 mod builders;
15 #[cfg(not(no_fp_fmt_parse))]
16 mod float;
17 #[cfg(no_fp_fmt_parse)]
18 mod nofloat;
19 mod num;
20
21 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
22 #[cfg_attr(not(test), rustc_diagnostic_item = "Alignment")]
23 /// Possible alignments returned by `Formatter::align`
24 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
25 pub enum Alignment {
26     #[stable(feature = "fmt_flags_align", since = "1.28.0")]
27     /// Indication that contents should be left-aligned.
28     Left,
29     #[stable(feature = "fmt_flags_align", since = "1.28.0")]
30     /// Indication that contents should be right-aligned.
31     Right,
32     #[stable(feature = "fmt_flags_align", since = "1.28.0")]
33     /// Indication that contents should be center-aligned.
34     Center,
35 }
36
37 #[stable(feature = "debug_builders", since = "1.2.0")]
38 pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
39
40 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
41 #[doc(hidden)]
42 pub mod rt {
43     pub mod v1;
44 }
45
46 /// The type returned by formatter methods.
47 ///
48 /// # Examples
49 ///
50 /// ```
51 /// use std::fmt;
52 ///
53 /// #[derive(Debug)]
54 /// struct Triangle {
55 ///     a: f32,
56 ///     b: f32,
57 ///     c: f32
58 /// }
59 ///
60 /// impl fmt::Display for Triangle {
61 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 ///         write!(f, "({}, {}, {})", self.a, self.b, self.c)
63 ///     }
64 /// }
65 ///
66 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
67 ///
68 /// assert_eq!(format!("{pythagorean_triple}"), "(3, 4, 5)");
69 /// ```
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub type Result = result::Result<(), Error>;
72
73 /// The error type which is returned from formatting a message into a stream.
74 ///
75 /// This type does not support transmission of an error other than that an error
76 /// occurred. Any extra information must be arranged to be transmitted through
77 /// some other means.
78 ///
79 /// An important thing to remember is that the type `fmt::Error` should not be
80 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
81 /// have in scope.
82 ///
83 /// [`std::io::Error`]: ../../std/io/struct.Error.html
84 /// [`std::error::Error`]: ../../std/error/trait.Error.html
85 ///
86 /// # Examples
87 ///
88 /// ```rust
89 /// use std::fmt::{self, write};
90 ///
91 /// let mut output = String::new();
92 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
93 ///     panic!("An error occurred");
94 /// }
95 /// ```
96 #[stable(feature = "rust1", since = "1.0.0")]
97 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
98 pub struct Error;
99
100 /// A trait for writing or formatting into Unicode-accepting buffers or streams.
101 ///
102 /// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
103 /// want to accept Unicode and you don't need flushing, you should implement this trait;
104 /// otherwise you should implement [`std::io::Write`].
105 ///
106 /// [`std::io::Write`]: ../../std/io/trait.Write.html
107 /// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
108 #[stable(feature = "rust1", since = "1.0.0")]
109 pub trait Write {
110     /// Writes a string slice into this writer, returning whether the write
111     /// succeeded.
112     ///
113     /// This method can only succeed if the entire string slice was successfully
114     /// written, and this method will not return until all data has been
115     /// written or an error occurs.
116     ///
117     /// # Errors
118     ///
119     /// This function will return an instance of [`Error`] on error.
120     ///
121     /// # Examples
122     ///
123     /// ```
124     /// use std::fmt::{Error, Write};
125     ///
126     /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
127     ///     f.write_str(s)
128     /// }
129     ///
130     /// let mut buf = String::new();
131     /// writer(&mut buf, "hola").unwrap();
132     /// assert_eq!(&buf, "hola");
133     /// ```
134     #[stable(feature = "rust1", since = "1.0.0")]
135     fn write_str(&mut self, s: &str) -> Result;
136
137     /// Writes a [`char`] into this writer, returning whether the write succeeded.
138     ///
139     /// A single [`char`] may be encoded as more than one byte.
140     /// This method can only succeed if the entire byte sequence was successfully
141     /// written, and this method will not return until all data has been
142     /// written or an error occurs.
143     ///
144     /// # Errors
145     ///
146     /// This function will return an instance of [`Error`] on error.
147     ///
148     /// # Examples
149     ///
150     /// ```
151     /// use std::fmt::{Error, Write};
152     ///
153     /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
154     ///     f.write_char(c)
155     /// }
156     ///
157     /// let mut buf = String::new();
158     /// writer(&mut buf, 'a').unwrap();
159     /// writer(&mut buf, 'b').unwrap();
160     /// assert_eq!(&buf, "ab");
161     /// ```
162     #[stable(feature = "fmt_write_char", since = "1.1.0")]
163     fn write_char(&mut self, c: char) -> Result {
164         self.write_str(c.encode_utf8(&mut [0; 4]))
165     }
166
167     /// Glue for usage of the [`write!`] macro with implementors of this trait.
168     ///
169     /// This method should generally not be invoked manually, but rather through
170     /// the [`write!`] macro itself.
171     ///
172     /// # Examples
173     ///
174     /// ```
175     /// use std::fmt::{Error, Write};
176     ///
177     /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
178     ///     f.write_fmt(format_args!("{s}"))
179     /// }
180     ///
181     /// let mut buf = String::new();
182     /// writer(&mut buf, "world").unwrap();
183     /// assert_eq!(&buf, "world");
184     /// ```
185     #[stable(feature = "rust1", since = "1.0.0")]
186     fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
187         write(&mut self, args)
188     }
189 }
190
191 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
192 impl<W: Write + ?Sized> Write for &mut W {
193     fn write_str(&mut self, s: &str) -> Result {
194         (**self).write_str(s)
195     }
196
197     fn write_char(&mut self, c: char) -> Result {
198         (**self).write_char(c)
199     }
200
201     fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
202         (**self).write_fmt(args)
203     }
204 }
205
206 /// Configuration for formatting.
207 ///
208 /// A `Formatter` represents various options related to formatting. Users do not
209 /// construct `Formatter`s directly; a mutable reference to one is passed to
210 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
211 ///
212 /// To interact with a `Formatter`, you'll call various methods to change the
213 /// various options related to formatting. For examples, please see the
214 /// documentation of the methods defined on `Formatter` below.
215 #[allow(missing_debug_implementations)]
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub struct Formatter<'a> {
218     flags: u32,
219     fill: char,
220     align: rt::v1::Alignment,
221     width: Option<usize>,
222     precision: Option<usize>,
223
224     buf: &'a mut (dyn Write + 'a),
225 }
226
227 impl<'a> Formatter<'a> {
228     /// Creates a new formatter with default settings.
229     ///
230     /// This can be used as a micro-optimization in cases where a full `Arguments`
231     /// structure (as created by `format_args!`) is not necessary; `Arguments`
232     /// is a little more expensive to use in simple formatting scenarios.
233     ///
234     /// Currently not intended for use outside of the standard library.
235     #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
236     #[doc(hidden)]
237     pub fn new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
238         Formatter {
239             flags: 0,
240             fill: ' ',
241             align: rt::v1::Alignment::Unknown,
242             width: None,
243             precision: None,
244             buf,
245         }
246     }
247 }
248
249 // NB. Argument is essentially an optimized partially applied formatting function,
250 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
251
252 extern "C" {
253     type Opaque;
254 }
255
256 /// This struct represents the generic "argument" which is taken by the Xprintf
257 /// family of functions. It contains a function to format the given value. At
258 /// compile time it is ensured that the function and the value have the correct
259 /// types, and then this struct is used to canonicalize arguments to one type.
260 #[derive(Copy, Clone)]
261 #[allow(missing_debug_implementations)]
262 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
263 #[doc(hidden)]
264 pub struct ArgumentV1<'a> {
265     value: &'a Opaque,
266     formatter: fn(&Opaque, &mut Formatter<'_>) -> Result,
267 }
268
269 /// This struct represents the unsafety of constructing an `Arguments`.
270 /// It exists, rather than an unsafe function, in order to simplify the expansion
271 /// of `format_args!(..)` and reduce the scope of the `unsafe` block.
272 #[allow(missing_debug_implementations)]
273 #[doc(hidden)]
274 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
275 pub struct UnsafeArg {
276     _private: (),
277 }
278
279 impl UnsafeArg {
280     /// See documentation where `UnsafeArg` is required to know when it is safe to
281     /// create and use `UnsafeArg`.
282     #[doc(hidden)]
283     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
284     #[inline(always)]
285     pub unsafe fn new() -> Self {
286         Self { _private: () }
287     }
288 }
289
290 // This guarantees a single stable value for the function pointer associated with
291 // indices/counts in the formatting infrastructure.
292 //
293 // Note that a function defined as such would not be correct as functions are
294 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
295 // address is not considered important to LLVM and as such the as_usize cast
296 // could have been miscompiled. In practice, we never call as_usize on non-usize
297 // containing data (as a matter of static generation of the formatting
298 // arguments), so this is merely an additional check.
299 //
300 // We primarily want to ensure that the function pointer at `USIZE_MARKER` has
301 // an address corresponding *only* to functions that also take `&usize` as their
302 // first argument. The read_volatile here ensures that we can safely ready out a
303 // usize from the passed reference and that this address does not point at a
304 // non-usize taking function.
305 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
306 static USIZE_MARKER: fn(&usize, &mut Formatter<'_>) -> Result = |ptr, _| {
307     // SAFETY: ptr is a reference
308     let _v: usize = unsafe { crate::ptr::read_volatile(ptr) };
309     loop {}
310 };
311
312 macro_rules! arg_new {
313     ($f: ident, $t: ident) => {
314         #[doc(hidden)]
315         #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
316         #[inline]
317         pub fn $f<'b, T: $t>(x: &'b T) -> ArgumentV1<'_> {
318             Self::new(x, $t::fmt)
319         }
320     };
321 }
322
323 impl<'a> ArgumentV1<'a> {
324     #[doc(hidden)]
325     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
326     #[inline]
327     pub fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
328         // SAFETY: `mem::transmute(x)` is safe because
329         //     1. `&'b T` keeps the lifetime it originated with `'b`
330         //              (so as to not have an unbounded lifetime)
331         //     2. `&'b T` and `&'b Opaque` have the same memory layout
332         //              (when `T` is `Sized`, as it is here)
333         // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
334         // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
335         // (as long as `T` is `Sized`)
336         unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) } }
337     }
338
339     arg_new!(new_display, Display);
340     arg_new!(new_debug, Debug);
341     arg_new!(new_octal, Octal);
342     arg_new!(new_lower_hex, LowerHex);
343     arg_new!(new_upper_hex, UpperHex);
344     arg_new!(new_pointer, Pointer);
345     arg_new!(new_binary, Binary);
346     arg_new!(new_lower_exp, LowerExp);
347     arg_new!(new_upper_exp, UpperExp);
348
349     #[doc(hidden)]
350     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
351     pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
352         ArgumentV1::new(x, USIZE_MARKER)
353     }
354
355     fn as_usize(&self) -> Option<usize> {
356         // We are type punning a bit here: USIZE_MARKER only takes an &usize but
357         // formatter takes an &Opaque. Rust understandably doesn't think we should compare
358         // the function pointers if they don't have the same signature, so we cast to
359         // usizes to tell it that we just want to compare addresses.
360         if self.formatter as usize == USIZE_MARKER as usize {
361             // SAFETY: The `formatter` field is only set to USIZE_MARKER if
362             // the value is a usize, so this is safe
363             Some(unsafe { *(self.value as *const _ as *const usize) })
364         } else {
365             None
366         }
367     }
368 }
369
370 // flags available in the v1 format of format_args
371 #[derive(Copy, Clone)]
372 enum FlagV1 {
373     SignPlus,
374     SignMinus,
375     Alternate,
376     SignAwareZeroPad,
377     DebugLowerHex,
378     DebugUpperHex,
379 }
380
381 impl<'a> Arguments<'a> {
382     /// When using the format_args!() macro, this function is used to generate the
383     /// Arguments structure.
384     #[doc(hidden)]
385     #[inline]
386     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
387     #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
388     pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
389         if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
390             panic!("invalid args");
391         }
392         Arguments { pieces, fmt: None, args }
393     }
394
395     /// This function is used to specify nonstandard formatting parameters.
396     ///
397     /// An `UnsafeArg` is required because the following invariants must be held
398     /// in order for this function to be safe:
399     /// 1. The `pieces` slice must be at least as long as `fmt`.
400     /// 2. Every [`rt::v1::Argument::position`] value within `fmt` must be a
401     ///    valid index of `args`.
402     /// 3. Every [`Count::Param`] within `fmt` must contain a valid index of
403     ///    `args`.
404     #[doc(hidden)]
405     #[inline]
406     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
407     #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
408     pub const fn new_v1_formatted(
409         pieces: &'a [&'static str],
410         args: &'a [ArgumentV1<'a>],
411         fmt: &'a [rt::v1::Argument],
412         _unsafe_arg: UnsafeArg,
413     ) -> Arguments<'a> {
414         Arguments { pieces, fmt: Some(fmt), args }
415     }
416
417     /// Estimates the length of the formatted text.
418     ///
419     /// This is intended to be used for setting initial `String` capacity
420     /// when using `format!`. Note: this is neither the lower nor upper bound.
421     #[doc(hidden)]
422     #[inline]
423     #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
424     pub fn estimated_capacity(&self) -> usize {
425         let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
426
427         if self.args.is_empty() {
428             pieces_length
429         } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
430             // If the format string starts with an argument,
431             // don't preallocate anything, unless length
432             // of pieces is significant.
433             0
434         } else {
435             // There are some arguments, so any additional push
436             // will reallocate the string. To avoid that,
437             // we're "pre-doubling" the capacity here.
438             pieces_length.checked_mul(2).unwrap_or(0)
439         }
440     }
441 }
442
443 /// This structure represents a safely precompiled version of a format string
444 /// and its arguments. This cannot be generated at runtime because it cannot
445 /// safely be done, so no constructors are given and the fields are private
446 /// to prevent modification.
447 ///
448 /// The [`format_args!`] macro will safely create an instance of this structure.
449 /// The macro validates the format string at compile-time so usage of the
450 /// [`write()`] and [`format()`] functions can be safely performed.
451 ///
452 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
453 /// and `Display` contexts as seen below. The example also shows that `Debug`
454 /// and `Display` format to the same thing: the interpolated format string
455 /// in `format_args!`.
456 ///
457 /// ```rust
458 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
459 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
460 /// assert_eq!("1 foo 2", display);
461 /// assert_eq!(display, debug);
462 /// ```
463 ///
464 /// [`format()`]: ../../std/fmt/fn.format.html
465 #[stable(feature = "rust1", since = "1.0.0")]
466 #[cfg_attr(not(test), rustc_diagnostic_item = "Arguments")]
467 #[derive(Copy, Clone)]
468 pub struct Arguments<'a> {
469     // Format string pieces to print.
470     pieces: &'a [&'static str],
471
472     // Placeholder specs, or `None` if all specs are default (as in "{}{}").
473     fmt: Option<&'a [rt::v1::Argument]>,
474
475     // Dynamic arguments for interpolation, to be interleaved with string
476     // pieces. (Every argument is preceded by a string piece.)
477     args: &'a [ArgumentV1<'a>],
478 }
479
480 impl<'a> Arguments<'a> {
481     /// Get the formatted string, if it has no arguments to be formatted.
482     ///
483     /// This can be used to avoid allocations in the most trivial case.
484     ///
485     /// # Examples
486     ///
487     /// ```rust
488     /// use std::fmt::Arguments;
489     ///
490     /// fn write_str(_: &str) { /* ... */ }
491     ///
492     /// fn write_fmt(args: &Arguments) {
493     ///     if let Some(s) = args.as_str() {
494     ///         write_str(s)
495     ///     } else {
496     ///         write_str(&args.to_string());
497     ///     }
498     /// }
499     /// ```
500     ///
501     /// ```rust
502     /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
503     /// assert_eq!(format_args!("").as_str(), Some(""));
504     /// assert_eq!(format_args!("{}", 1).as_str(), None);
505     /// ```
506     #[stable(feature = "fmt_as_str", since = "1.52.0")]
507     #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "none")]
508     #[must_use]
509     #[inline]
510     pub const fn as_str(&self) -> Option<&'static str> {
511         match (self.pieces, self.args) {
512             ([], []) => Some(""),
513             ([s], []) => Some(s),
514             _ => None,
515         }
516     }
517 }
518
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl Debug for Arguments<'_> {
521     fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
522         Display::fmt(self, fmt)
523     }
524 }
525
526 #[stable(feature = "rust1", since = "1.0.0")]
527 impl Display for Arguments<'_> {
528     fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
529         write(fmt.buf, *self)
530     }
531 }
532
533 /// `?` formatting.
534 ///
535 /// `Debug` should format the output in a programmer-facing, debugging context.
536 ///
537 /// Generally speaking, you should just `derive` a `Debug` implementation.
538 ///
539 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
540 ///
541 /// For more information on formatters, see [the module-level documentation][module].
542 ///
543 /// [module]: ../../std/fmt/index.html
544 ///
545 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
546 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
547 /// comma-separated list of each field's name and `Debug` value, then `}`. For
548 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
549 /// `Debug` values of the fields, then `)`.
550 ///
551 /// # Stability
552 ///
553 /// Derived `Debug` formats are not stable, and so may change with future Rust
554 /// versions. Additionally, `Debug` implementations of types provided by the
555 /// standard library (`libstd`, `libcore`, `liballoc`, etc.) are not stable, and
556 /// may also change with future Rust versions.
557 ///
558 /// # Examples
559 ///
560 /// Deriving an implementation:
561 ///
562 /// ```
563 /// #[derive(Debug)]
564 /// struct Point {
565 ///     x: i32,
566 ///     y: i32,
567 /// }
568 ///
569 /// let origin = Point { x: 0, y: 0 };
570 ///
571 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
572 /// ```
573 ///
574 /// Manually implementing:
575 ///
576 /// ```
577 /// use std::fmt;
578 ///
579 /// struct Point {
580 ///     x: i32,
581 ///     y: i32,
582 /// }
583 ///
584 /// impl fmt::Debug for Point {
585 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
586 ///         f.debug_struct("Point")
587 ///          .field("x", &self.x)
588 ///          .field("y", &self.y)
589 ///          .finish()
590 ///     }
591 /// }
592 ///
593 /// let origin = Point { x: 0, y: 0 };
594 ///
595 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
596 /// ```
597 ///
598 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
599 /// implementations, such as [`debug_struct`].
600 ///
601 /// [`debug_struct`]: Formatter::debug_struct
602 ///
603 /// Types that do not wish to use the standard suite of debug representations
604 /// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
605 /// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
606 /// manually writing an arbitrary representation to the `Formatter`.
607 ///
608 /// ```
609 /// # use std::fmt;
610 /// # struct Point {
611 /// #     x: i32,
612 /// #     y: i32,
613 /// # }
614 /// #
615 /// impl fmt::Debug for Point {
616 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
617 ///         write!(f, "Point [{} {}]", self.x, self.y)
618 ///     }
619 /// }
620 /// ```
621 ///
622 /// `Debug` implementations using either `derive` or the debug builder API
623 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
624 ///
625 /// Pretty-printing with `#?`:
626 ///
627 /// ```
628 /// #[derive(Debug)]
629 /// struct Point {
630 ///     x: i32,
631 ///     y: i32,
632 /// }
633 ///
634 /// let origin = Point { x: 0, y: 0 };
635 ///
636 /// assert_eq!(format!("The origin is: {origin:#?}"),
637 /// "The origin is: Point {
638 ///     x: 0,
639 ///     y: 0,
640 /// }");
641 /// ```
642
643 #[stable(feature = "rust1", since = "1.0.0")]
644 #[rustc_on_unimplemented(
645     on(
646         crate_local,
647         label = "`{Self}` cannot be formatted using `{{:?}}`",
648         note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
649     ),
650     message = "`{Self}` doesn't implement `{Debug}`",
651     label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
652 )]
653 #[doc(alias = "{:?}")]
654 #[rustc_diagnostic_item = "Debug"]
655 #[rustc_trivial_field_reads]
656 pub trait Debug {
657     /// Formats the value using the given formatter.
658     ///
659     /// # Examples
660     ///
661     /// ```
662     /// use std::fmt;
663     ///
664     /// struct Position {
665     ///     longitude: f32,
666     ///     latitude: f32,
667     /// }
668     ///
669     /// impl fmt::Debug for Position {
670     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671     ///         f.debug_tuple("")
672     ///          .field(&self.longitude)
673     ///          .field(&self.latitude)
674     ///          .finish()
675     ///     }
676     /// }
677     ///
678     /// let position = Position { longitude: 1.987, latitude: 2.983 };
679     /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
680     ///
681     /// assert_eq!(format!("{position:#?}"), "(
682     ///     1.987,
683     ///     2.983,
684     /// )");
685     /// ```
686     #[stable(feature = "rust1", since = "1.0.0")]
687     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
688 }
689
690 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
691 pub(crate) mod macros {
692     /// Derive macro generating an impl of the trait `Debug`.
693     #[rustc_builtin_macro]
694     #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
695     #[allow_internal_unstable(core_intrinsics)]
696     pub macro Debug($item:item) {
697         /* compiler built-in */
698     }
699 }
700 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
701 #[doc(inline)]
702 pub use macros::Debug;
703
704 /// Format trait for an empty format, `{}`.
705 ///
706 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
707 /// output, and so cannot be derived.
708 ///
709 /// For more information on formatters, see [the module-level documentation][module].
710 ///
711 /// [module]: ../../std/fmt/index.html
712 ///
713 /// # Examples
714 ///
715 /// Implementing `Display` on a type:
716 ///
717 /// ```
718 /// use std::fmt;
719 ///
720 /// struct Point {
721 ///     x: i32,
722 ///     y: i32,
723 /// }
724 ///
725 /// impl fmt::Display for Point {
726 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
727 ///         write!(f, "({}, {})", self.x, self.y)
728 ///     }
729 /// }
730 ///
731 /// let origin = Point { x: 0, y: 0 };
732 ///
733 /// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
734 /// ```
735 #[rustc_on_unimplemented(
736     on(
737         any(_Self = "std::path::Path", _Self = "std::path::PathBuf"),
738         label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
739         note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
740                 as they may contain non-Unicode data"
741     ),
742     message = "`{Self}` doesn't implement `{Display}`",
743     label = "`{Self}` cannot be formatted with the default formatter",
744     note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
745 )]
746 #[doc(alias = "{}")]
747 #[rustc_diagnostic_item = "Display"]
748 #[stable(feature = "rust1", since = "1.0.0")]
749 pub trait Display {
750     /// Formats the value using the given formatter.
751     ///
752     /// # Examples
753     ///
754     /// ```
755     /// use std::fmt;
756     ///
757     /// struct Position {
758     ///     longitude: f32,
759     ///     latitude: f32,
760     /// }
761     ///
762     /// impl fmt::Display for Position {
763     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
764     ///         write!(f, "({}, {})", self.longitude, self.latitude)
765     ///     }
766     /// }
767     ///
768     /// assert_eq!("(1.987, 2.983)",
769     ///            format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
770     /// ```
771     #[stable(feature = "rust1", since = "1.0.0")]
772     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
773 }
774
775 /// `o` formatting.
776 ///
777 /// The `Octal` trait should format its output as a number in base-8.
778 ///
779 /// For primitive signed integers (`i8` to `i128`, and `isize`),
780 /// negative values are formatted as the two’s complement representation.
781 ///
782 /// The alternate flag, `#`, adds a `0o` in front of the output.
783 ///
784 /// For more information on formatters, see [the module-level documentation][module].
785 ///
786 /// [module]: ../../std/fmt/index.html
787 ///
788 /// # Examples
789 ///
790 /// Basic usage with `i32`:
791 ///
792 /// ```
793 /// let x = 42; // 42 is '52' in octal
794 ///
795 /// assert_eq!(format!("{x:o}"), "52");
796 /// assert_eq!(format!("{x:#o}"), "0o52");
797 ///
798 /// assert_eq!(format!("{:o}", -16), "37777777760");
799 /// ```
800 ///
801 /// Implementing `Octal` on a type:
802 ///
803 /// ```
804 /// use std::fmt;
805 ///
806 /// struct Length(i32);
807 ///
808 /// impl fmt::Octal for Length {
809 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
810 ///         let val = self.0;
811 ///
812 ///         fmt::Octal::fmt(&val, f) // delegate to i32's implementation
813 ///     }
814 /// }
815 ///
816 /// let l = Length(9);
817 ///
818 /// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
819 ///
820 /// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
821 /// ```
822 #[stable(feature = "rust1", since = "1.0.0")]
823 pub trait Octal {
824     /// Formats the value using the given formatter.
825     #[stable(feature = "rust1", since = "1.0.0")]
826     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
827 }
828
829 /// `b` formatting.
830 ///
831 /// The `Binary` trait should format its output as a number in binary.
832 ///
833 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
834 /// negative values are formatted as the two’s complement representation.
835 ///
836 /// The alternate flag, `#`, adds a `0b` in front of the output.
837 ///
838 /// For more information on formatters, see [the module-level documentation][module].
839 ///
840 /// [module]: ../../std/fmt/index.html
841 ///
842 /// # Examples
843 ///
844 /// Basic usage with [`i32`]:
845 ///
846 /// ```
847 /// let x = 42; // 42 is '101010' in binary
848 ///
849 /// assert_eq!(format!("{x:b}"), "101010");
850 /// assert_eq!(format!("{x:#b}"), "0b101010");
851 ///
852 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
853 /// ```
854 ///
855 /// Implementing `Binary` on a type:
856 ///
857 /// ```
858 /// use std::fmt;
859 ///
860 /// struct Length(i32);
861 ///
862 /// impl fmt::Binary for Length {
863 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
864 ///         let val = self.0;
865 ///
866 ///         fmt::Binary::fmt(&val, f) // delegate to i32's implementation
867 ///     }
868 /// }
869 ///
870 /// let l = Length(107);
871 ///
872 /// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
873 ///
874 /// assert_eq!(
875 ///     format!("l as binary is: {l:#032b}"),
876 ///     "l as binary is: 0b000000000000000000000001101011"
877 /// );
878 /// ```
879 #[stable(feature = "rust1", since = "1.0.0")]
880 pub trait Binary {
881     /// Formats the value using the given formatter.
882     #[stable(feature = "rust1", since = "1.0.0")]
883     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
884 }
885
886 /// `x` formatting.
887 ///
888 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
889 /// in lower case.
890 ///
891 /// For primitive signed integers (`i8` to `i128`, and `isize`),
892 /// negative values are formatted as the two’s complement representation.
893 ///
894 /// The alternate flag, `#`, adds a `0x` in front of the output.
895 ///
896 /// For more information on formatters, see [the module-level documentation][module].
897 ///
898 /// [module]: ../../std/fmt/index.html
899 ///
900 /// # Examples
901 ///
902 /// Basic usage with `i32`:
903 ///
904 /// ```
905 /// let x = 42; // 42 is '2a' in hex
906 ///
907 /// assert_eq!(format!("{x:x}"), "2a");
908 /// assert_eq!(format!("{x:#x}"), "0x2a");
909 ///
910 /// assert_eq!(format!("{:x}", -16), "fffffff0");
911 /// ```
912 ///
913 /// Implementing `LowerHex` on a type:
914 ///
915 /// ```
916 /// use std::fmt;
917 ///
918 /// struct Length(i32);
919 ///
920 /// impl fmt::LowerHex for Length {
921 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
922 ///         let val = self.0;
923 ///
924 ///         fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
925 ///     }
926 /// }
927 ///
928 /// let l = Length(9);
929 ///
930 /// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
931 ///
932 /// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
933 /// ```
934 #[stable(feature = "rust1", since = "1.0.0")]
935 pub trait LowerHex {
936     /// Formats the value using the given formatter.
937     #[stable(feature = "rust1", since = "1.0.0")]
938     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
939 }
940
941 /// `X` formatting.
942 ///
943 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
944 /// in upper case.
945 ///
946 /// For primitive signed integers (`i8` to `i128`, and `isize`),
947 /// negative values are formatted as the two’s complement representation.
948 ///
949 /// The alternate flag, `#`, adds a `0x` in front of the output.
950 ///
951 /// For more information on formatters, see [the module-level documentation][module].
952 ///
953 /// [module]: ../../std/fmt/index.html
954 ///
955 /// # Examples
956 ///
957 /// Basic usage with `i32`:
958 ///
959 /// ```
960 /// let x = 42; // 42 is '2A' in hex
961 ///
962 /// assert_eq!(format!("{x:X}"), "2A");
963 /// assert_eq!(format!("{x:#X}"), "0x2A");
964 ///
965 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
966 /// ```
967 ///
968 /// Implementing `UpperHex` on a type:
969 ///
970 /// ```
971 /// use std::fmt;
972 ///
973 /// struct Length(i32);
974 ///
975 /// impl fmt::UpperHex for Length {
976 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
977 ///         let val = self.0;
978 ///
979 ///         fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
980 ///     }
981 /// }
982 ///
983 /// let l = Length(i32::MAX);
984 ///
985 /// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
986 ///
987 /// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
988 /// ```
989 #[stable(feature = "rust1", since = "1.0.0")]
990 pub trait UpperHex {
991     /// Formats the value using the given formatter.
992     #[stable(feature = "rust1", since = "1.0.0")]
993     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
994 }
995
996 /// `p` formatting.
997 ///
998 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
999 /// as hexadecimal.
1000 ///
1001 /// For more information on formatters, see [the module-level documentation][module].
1002 ///
1003 /// [module]: ../../std/fmt/index.html
1004 ///
1005 /// # Examples
1006 ///
1007 /// Basic usage with `&i32`:
1008 ///
1009 /// ```
1010 /// let x = &42;
1011 ///
1012 /// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
1013 /// ```
1014 ///
1015 /// Implementing `Pointer` on a type:
1016 ///
1017 /// ```
1018 /// use std::fmt;
1019 ///
1020 /// struct Length(i32);
1021 ///
1022 /// impl fmt::Pointer for Length {
1023 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1024 ///         // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1025 ///
1026 ///         let ptr = self as *const Self;
1027 ///         fmt::Pointer::fmt(&ptr, f)
1028 ///     }
1029 /// }
1030 ///
1031 /// let l = Length(42);
1032 ///
1033 /// println!("l is in memory here: {l:p}");
1034 ///
1035 /// let l_ptr = format!("{l:018p}");
1036 /// assert_eq!(l_ptr.len(), 18);
1037 /// assert_eq!(&l_ptr[..2], "0x");
1038 /// ```
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 #[rustc_diagnostic_item = "Pointer"]
1041 pub trait Pointer {
1042     /// Formats the value using the given formatter.
1043     #[stable(feature = "rust1", since = "1.0.0")]
1044     #[rustc_diagnostic_item = "pointer_trait_fmt"]
1045     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1046 }
1047
1048 /// `e` formatting.
1049 ///
1050 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1051 ///
1052 /// For more information on formatters, see [the module-level documentation][module].
1053 ///
1054 /// [module]: ../../std/fmt/index.html
1055 ///
1056 /// # Examples
1057 ///
1058 /// Basic usage with `f64`:
1059 ///
1060 /// ```
1061 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1062 ///
1063 /// assert_eq!(format!("{x:e}"), "4.2e1");
1064 /// ```
1065 ///
1066 /// Implementing `LowerExp` on a type:
1067 ///
1068 /// ```
1069 /// use std::fmt;
1070 ///
1071 /// struct Length(i32);
1072 ///
1073 /// impl fmt::LowerExp for Length {
1074 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1075 ///         let val = f64::from(self.0);
1076 ///         fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1077 ///     }
1078 /// }
1079 ///
1080 /// let l = Length(100);
1081 ///
1082 /// assert_eq!(
1083 ///     format!("l in scientific notation is: {l:e}"),
1084 ///     "l in scientific notation is: 1e2"
1085 /// );
1086 ///
1087 /// assert_eq!(
1088 ///     format!("l in scientific notation is: {l:05e}"),
1089 ///     "l in scientific notation is: 001e2"
1090 /// );
1091 /// ```
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 pub trait LowerExp {
1094     /// Formats the value using the given formatter.
1095     #[stable(feature = "rust1", since = "1.0.0")]
1096     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1097 }
1098
1099 /// `E` formatting.
1100 ///
1101 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1102 ///
1103 /// For more information on formatters, see [the module-level documentation][module].
1104 ///
1105 /// [module]: ../../std/fmt/index.html
1106 ///
1107 /// # Examples
1108 ///
1109 /// Basic usage with `f64`:
1110 ///
1111 /// ```
1112 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1113 ///
1114 /// assert_eq!(format!("{x:E}"), "4.2E1");
1115 /// ```
1116 ///
1117 /// Implementing `UpperExp` on a type:
1118 ///
1119 /// ```
1120 /// use std::fmt;
1121 ///
1122 /// struct Length(i32);
1123 ///
1124 /// impl fmt::UpperExp for Length {
1125 ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1126 ///         let val = f64::from(self.0);
1127 ///         fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1128 ///     }
1129 /// }
1130 ///
1131 /// let l = Length(100);
1132 ///
1133 /// assert_eq!(
1134 ///     format!("l in scientific notation is: {l:E}"),
1135 ///     "l in scientific notation is: 1E2"
1136 /// );
1137 ///
1138 /// assert_eq!(
1139 ///     format!("l in scientific notation is: {l:05E}"),
1140 ///     "l in scientific notation is: 001E2"
1141 /// );
1142 /// ```
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 pub trait UpperExp {
1145     /// Formats the value using the given formatter.
1146     #[stable(feature = "rust1", since = "1.0.0")]
1147     fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1148 }
1149
1150 /// The `write` function takes an output stream, and an `Arguments` struct
1151 /// that can be precompiled with the `format_args!` macro.
1152 ///
1153 /// The arguments will be formatted according to the specified format string
1154 /// into the output stream provided.
1155 ///
1156 /// # Examples
1157 ///
1158 /// Basic usage:
1159 ///
1160 /// ```
1161 /// use std::fmt;
1162 ///
1163 /// let mut output = String::new();
1164 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1165 ///     .expect("Error occurred while trying to write in String");
1166 /// assert_eq!(output, "Hello world!");
1167 /// ```
1168 ///
1169 /// Please note that using [`write!`] might be preferable. Example:
1170 ///
1171 /// ```
1172 /// use std::fmt::Write;
1173 ///
1174 /// let mut output = String::new();
1175 /// write!(&mut output, "Hello {}!", "world")
1176 ///     .expect("Error occurred while trying to write in String");
1177 /// assert_eq!(output, "Hello world!");
1178 /// ```
1179 ///
1180 /// [`write!`]: crate::write!
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1183     let mut formatter = Formatter::new(output);
1184     let mut idx = 0;
1185
1186     match args.fmt {
1187         None => {
1188             // We can use default formatting parameters for all arguments.
1189             for (i, arg) in args.args.iter().enumerate() {
1190                 // SAFETY: args.args and args.pieces come from the same Arguments,
1191                 // which guarantees the indexes are always within bounds.
1192                 let piece = unsafe { args.pieces.get_unchecked(i) };
1193                 if !piece.is_empty() {
1194                     formatter.buf.write_str(*piece)?;
1195                 }
1196                 (arg.formatter)(arg.value, &mut formatter)?;
1197                 idx += 1;
1198             }
1199         }
1200         Some(fmt) => {
1201             // Every spec has a corresponding argument that is preceded by
1202             // a string piece.
1203             for (i, arg) in fmt.iter().enumerate() {
1204                 // SAFETY: fmt and args.pieces come from the same Arguments,
1205                 // which guarantees the indexes are always within bounds.
1206                 let piece = unsafe { args.pieces.get_unchecked(i) };
1207                 if !piece.is_empty() {
1208                     formatter.buf.write_str(*piece)?;
1209                 }
1210                 // SAFETY: arg and args.args come from the same Arguments,
1211                 // which guarantees the indexes are always within bounds.
1212                 unsafe { run(&mut formatter, arg, args.args) }?;
1213                 idx += 1;
1214             }
1215         }
1216     }
1217
1218     // There can be only one trailing string piece left.
1219     if let Some(piece) = args.pieces.get(idx) {
1220         formatter.buf.write_str(*piece)?;
1221     }
1222
1223     Ok(())
1224 }
1225
1226 unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1227     fmt.fill = arg.format.fill;
1228     fmt.align = arg.format.align;
1229     fmt.flags = arg.format.flags;
1230     // SAFETY: arg and args come from the same Arguments,
1231     // which guarantees the indexes are always within bounds.
1232     unsafe {
1233         fmt.width = getcount(args, &arg.format.width);
1234         fmt.precision = getcount(args, &arg.format.precision);
1235     }
1236
1237     // Extract the correct argument
1238     debug_assert!(arg.position < args.len());
1239     // SAFETY: arg and args come from the same Arguments,
1240     // which guarantees its index is always within bounds.
1241     let value = unsafe { args.get_unchecked(arg.position) };
1242
1243     // Then actually do some printing
1244     (value.formatter)(value.value, fmt)
1245 }
1246
1247 unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1248     match *cnt {
1249         rt::v1::Count::Is(n) => Some(n),
1250         rt::v1::Count::Implied => None,
1251         rt::v1::Count::Param(i) => {
1252             debug_assert!(i < args.len());
1253             // SAFETY: cnt and args come from the same Arguments,
1254             // which guarantees this index is always within bounds.
1255             unsafe { args.get_unchecked(i).as_usize() }
1256         }
1257     }
1258 }
1259
1260 /// Padding after the end of something. Returned by `Formatter::padding`.
1261 #[must_use = "don't forget to write the post padding"]
1262 pub(crate) struct PostPadding {
1263     fill: char,
1264     padding: usize,
1265 }
1266
1267 impl PostPadding {
1268     fn new(fill: char, padding: usize) -> PostPadding {
1269         PostPadding { fill, padding }
1270     }
1271
1272     /// Write this post padding.
1273     pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1274         for _ in 0..self.padding {
1275             f.buf.write_char(self.fill)?;
1276         }
1277         Ok(())
1278     }
1279 }
1280
1281 impl<'a> Formatter<'a> {
1282     fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1283     where
1284         'b: 'c,
1285         F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1286     {
1287         Formatter {
1288             // We want to change this
1289             buf: wrap(self.buf),
1290
1291             // And preserve these
1292             flags: self.flags,
1293             fill: self.fill,
1294             align: self.align,
1295             width: self.width,
1296             precision: self.precision,
1297         }
1298     }
1299
1300     // Helper methods used for padding and processing formatting arguments that
1301     // all formatting traits can use.
1302
1303     /// Performs the correct padding for an integer which has already been
1304     /// emitted into a str. The str should *not* contain the sign for the
1305     /// integer, that will be added by this method.
1306     ///
1307     /// # Arguments
1308     ///
1309     /// * is_nonnegative - whether the original integer was either positive or zero.
1310     /// * prefix - if the '#' character (Alternate) is provided, this
1311     ///   is the prefix to put in front of the number.
1312     /// * buf - the byte array that the number has been formatted into
1313     ///
1314     /// This function will correctly account for the flags provided as well as
1315     /// the minimum width. It will not take precision into account.
1316     ///
1317     /// # Examples
1318     ///
1319     /// ```
1320     /// use std::fmt;
1321     ///
1322     /// struct Foo { nb: i32 }
1323     ///
1324     /// impl Foo {
1325     ///     fn new(nb: i32) -> Foo {
1326     ///         Foo {
1327     ///             nb,
1328     ///         }
1329     ///     }
1330     /// }
1331     ///
1332     /// impl fmt::Display for Foo {
1333     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1334     ///         // We need to remove "-" from the number output.
1335     ///         let tmp = self.nb.abs().to_string();
1336     ///
1337     ///         formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1338     ///     }
1339     /// }
1340     ///
1341     /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1342     /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1343     /// assert_eq!(&format!("{}", Foo::new(0)), "0");
1344     /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1345     /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1346     /// ```
1347     #[stable(feature = "rust1", since = "1.0.0")]
1348     pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1349         let mut width = buf.len();
1350
1351         let mut sign = None;
1352         if !is_nonnegative {
1353             sign = Some('-');
1354             width += 1;
1355         } else if self.sign_plus() {
1356             sign = Some('+');
1357             width += 1;
1358         }
1359
1360         let prefix = if self.alternate() {
1361             width += prefix.chars().count();
1362             Some(prefix)
1363         } else {
1364             None
1365         };
1366
1367         // Writes the sign if it exists, and then the prefix if it was requested
1368         #[inline(never)]
1369         fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1370             if let Some(c) = sign {
1371                 f.buf.write_char(c)?;
1372             }
1373             if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1374         }
1375
1376         // The `width` field is more of a `min-width` parameter at this point.
1377         match self.width {
1378             // If there's no minimum length requirements then we can just
1379             // write the bytes.
1380             None => {
1381                 write_prefix(self, sign, prefix)?;
1382                 self.buf.write_str(buf)
1383             }
1384             // Check if we're over the minimum width, if so then we can also
1385             // just write the bytes.
1386             Some(min) if width >= min => {
1387                 write_prefix(self, sign, prefix)?;
1388                 self.buf.write_str(buf)
1389             }
1390             // The sign and prefix goes before the padding if the fill character
1391             // is zero
1392             Some(min) if self.sign_aware_zero_pad() => {
1393                 let old_fill = crate::mem::replace(&mut self.fill, '0');
1394                 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1395                 write_prefix(self, sign, prefix)?;
1396                 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1397                 self.buf.write_str(buf)?;
1398                 post_padding.write(self)?;
1399                 self.fill = old_fill;
1400                 self.align = old_align;
1401                 Ok(())
1402             }
1403             // Otherwise, the sign and prefix goes after the padding
1404             Some(min) => {
1405                 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1406                 write_prefix(self, sign, prefix)?;
1407                 self.buf.write_str(buf)?;
1408                 post_padding.write(self)
1409             }
1410         }
1411     }
1412
1413     /// This function takes a string slice and emits it to the internal buffer
1414     /// after applying the relevant formatting flags specified. The flags
1415     /// recognized for generic strings are:
1416     ///
1417     /// * width - the minimum width of what to emit
1418     /// * fill/align - what to emit and where to emit it if the string
1419     ///                provided needs to be padded
1420     /// * precision - the maximum length to emit, the string is truncated if it
1421     ///               is longer than this length
1422     ///
1423     /// Notably this function ignores the `flag` parameters.
1424     ///
1425     /// # Examples
1426     ///
1427     /// ```
1428     /// use std::fmt;
1429     ///
1430     /// struct Foo;
1431     ///
1432     /// impl fmt::Display for Foo {
1433     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1434     ///         formatter.pad("Foo")
1435     ///     }
1436     /// }
1437     ///
1438     /// assert_eq!(&format!("{Foo:<4}"), "Foo ");
1439     /// assert_eq!(&format!("{Foo:0>4}"), "0Foo");
1440     /// ```
1441     #[stable(feature = "rust1", since = "1.0.0")]
1442     pub fn pad(&mut self, s: &str) -> Result {
1443         // Make sure there's a fast path up front
1444         if self.width.is_none() && self.precision.is_none() {
1445             return self.buf.write_str(s);
1446         }
1447         // The `precision` field can be interpreted as a `max-width` for the
1448         // string being formatted.
1449         let s = if let Some(max) = self.precision {
1450             // If our string is longer that the precision, then we must have
1451             // truncation. However other flags like `fill`, `width` and `align`
1452             // must act as always.
1453             if let Some((i, _)) = s.char_indices().nth(max) {
1454                 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1455                 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1456                 // `unsafe` and otherwise don't emit any panic-related code
1457                 // here.
1458                 s.get(..i).unwrap_or(s)
1459             } else {
1460                 &s
1461             }
1462         } else {
1463             &s
1464         };
1465         // The `width` field is more of a `min-width` parameter at this point.
1466         match self.width {
1467             // If we're under the maximum length, and there's no minimum length
1468             // requirements, then we can just emit the string
1469             None => self.buf.write_str(s),
1470             Some(width) => {
1471                 let chars_count = s.chars().count();
1472                 // If we're under the maximum width, check if we're over the minimum
1473                 // width, if so it's as easy as just emitting the string.
1474                 if chars_count >= width {
1475                     self.buf.write_str(s)
1476                 }
1477                 // If we're under both the maximum and the minimum width, then fill
1478                 // up the minimum width with the specified string + some alignment.
1479                 else {
1480                     let align = rt::v1::Alignment::Left;
1481                     let post_padding = self.padding(width - chars_count, align)?;
1482                     self.buf.write_str(s)?;
1483                     post_padding.write(self)
1484                 }
1485             }
1486         }
1487     }
1488
1489     /// Write the pre-padding and return the unwritten post-padding. Callers are
1490     /// responsible for ensuring post-padding is written after the thing that is
1491     /// being padded.
1492     pub(crate) fn padding(
1493         &mut self,
1494         padding: usize,
1495         default: rt::v1::Alignment,
1496     ) -> result::Result<PostPadding, Error> {
1497         let align = match self.align {
1498             rt::v1::Alignment::Unknown => default,
1499             _ => self.align,
1500         };
1501
1502         let (pre_pad, post_pad) = match align {
1503             rt::v1::Alignment::Left => (0, padding),
1504             rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1505             rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1506         };
1507
1508         for _ in 0..pre_pad {
1509             self.buf.write_char(self.fill)?;
1510         }
1511
1512         Ok(PostPadding::new(self.fill, post_pad))
1513     }
1514
1515     /// Takes the formatted parts and applies the padding.
1516     /// Assumes that the caller already has rendered the parts with required precision,
1517     /// so that `self.precision` can be ignored.
1518     fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1519         if let Some(mut width) = self.width {
1520             // for the sign-aware zero padding, we render the sign first and
1521             // behave as if we had no sign from the beginning.
1522             let mut formatted = formatted.clone();
1523             let old_fill = self.fill;
1524             let old_align = self.align;
1525             let mut align = old_align;
1526             if self.sign_aware_zero_pad() {
1527                 // a sign always goes first
1528                 let sign = formatted.sign;
1529                 self.buf.write_str(sign)?;
1530
1531                 // remove the sign from the formatted parts
1532                 formatted.sign = "";
1533                 width = width.saturating_sub(sign.len());
1534                 align = rt::v1::Alignment::Right;
1535                 self.fill = '0';
1536                 self.align = rt::v1::Alignment::Right;
1537             }
1538
1539             // remaining parts go through the ordinary padding process.
1540             let len = formatted.len();
1541             let ret = if width <= len {
1542                 // no padding
1543                 self.write_formatted_parts(&formatted)
1544             } else {
1545                 let post_padding = self.padding(width - len, align)?;
1546                 self.write_formatted_parts(&formatted)?;
1547                 post_padding.write(self)
1548             };
1549             self.fill = old_fill;
1550             self.align = old_align;
1551             ret
1552         } else {
1553             // this is the common case and we take a shortcut
1554             self.write_formatted_parts(formatted)
1555         }
1556     }
1557
1558     fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1559         fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1560             // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1561             // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1562             // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1563             // It's also probably safe in practice to use for `numfmt::Part::Copy(buf)`
1564             // since `buf` should be plain ASCII, but it's possible for someone to pass
1565             // in a bad value for `buf` into `numfmt::to_shortest_str` since it is a
1566             // public function.
1567             // FIXME: Determine whether this could result in UB.
1568             buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1569         }
1570
1571         if !formatted.sign.is_empty() {
1572             self.buf.write_str(formatted.sign)?;
1573         }
1574         for part in formatted.parts {
1575             match *part {
1576                 numfmt::Part::Zero(mut nzeroes) => {
1577                     const ZEROES: &str = // 64 zeroes
1578                         "0000000000000000000000000000000000000000000000000000000000000000";
1579                     while nzeroes > ZEROES.len() {
1580                         self.buf.write_str(ZEROES)?;
1581                         nzeroes -= ZEROES.len();
1582                     }
1583                     if nzeroes > 0 {
1584                         self.buf.write_str(&ZEROES[..nzeroes])?;
1585                     }
1586                 }
1587                 numfmt::Part::Num(mut v) => {
1588                     let mut s = [0; 5];
1589                     let len = part.len();
1590                     for c in s[..len].iter_mut().rev() {
1591                         *c = b'0' + (v % 10) as u8;
1592                         v /= 10;
1593                     }
1594                     write_bytes(self.buf, &s[..len])?;
1595                 }
1596                 numfmt::Part::Copy(buf) => {
1597                     write_bytes(self.buf, buf)?;
1598                 }
1599             }
1600         }
1601         Ok(())
1602     }
1603
1604     /// Writes some data to the underlying buffer contained within this
1605     /// formatter.
1606     ///
1607     /// # Examples
1608     ///
1609     /// ```
1610     /// use std::fmt;
1611     ///
1612     /// struct Foo;
1613     ///
1614     /// impl fmt::Display for Foo {
1615     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1616     ///         formatter.write_str("Foo")
1617     ///         // This is equivalent to:
1618     ///         // write!(formatter, "Foo")
1619     ///     }
1620     /// }
1621     ///
1622     /// assert_eq!(&format!("{Foo}"), "Foo");
1623     /// assert_eq!(&format!("{Foo:0>8}"), "Foo");
1624     /// ```
1625     #[stable(feature = "rust1", since = "1.0.0")]
1626     pub fn write_str(&mut self, data: &str) -> Result {
1627         self.buf.write_str(data)
1628     }
1629
1630     /// Writes some formatted information into this instance.
1631     ///
1632     /// # Examples
1633     ///
1634     /// ```
1635     /// use std::fmt;
1636     ///
1637     /// struct Foo(i32);
1638     ///
1639     /// impl fmt::Display for Foo {
1640     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1641     ///         formatter.write_fmt(format_args!("Foo {}", self.0))
1642     ///     }
1643     /// }
1644     ///
1645     /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1646     /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1647     /// ```
1648     #[stable(feature = "rust1", since = "1.0.0")]
1649     pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1650         write(self.buf, fmt)
1651     }
1652
1653     /// Flags for formatting
1654     #[must_use]
1655     #[stable(feature = "rust1", since = "1.0.0")]
1656     #[deprecated(
1657         since = "1.24.0",
1658         note = "use the `sign_plus`, `sign_minus`, `alternate`, \
1659                 or `sign_aware_zero_pad` methods instead"
1660     )]
1661     pub fn flags(&self) -> u32 {
1662         self.flags
1663     }
1664
1665     /// Character used as 'fill' whenever there is alignment.
1666     ///
1667     /// # Examples
1668     ///
1669     /// ```
1670     /// use std::fmt;
1671     ///
1672     /// struct Foo;
1673     ///
1674     /// impl fmt::Display for Foo {
1675     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1676     ///         let c = formatter.fill();
1677     ///         if let Some(width) = formatter.width() {
1678     ///             for _ in 0..width {
1679     ///                 write!(formatter, "{c}")?;
1680     ///             }
1681     ///             Ok(())
1682     ///         } else {
1683     ///             write!(formatter, "{c}")
1684     ///         }
1685     ///     }
1686     /// }
1687     ///
1688     /// // We set alignment to the right with ">".
1689     /// assert_eq!(&format!("{Foo:G>3}"), "GGG");
1690     /// assert_eq!(&format!("{Foo:t>6}"), "tttttt");
1691     /// ```
1692     #[must_use]
1693     #[stable(feature = "fmt_flags", since = "1.5.0")]
1694     pub fn fill(&self) -> char {
1695         self.fill
1696     }
1697
1698     /// Flag indicating what form of alignment was requested.
1699     ///
1700     /// # Examples
1701     ///
1702     /// ```
1703     /// extern crate core;
1704     ///
1705     /// use std::fmt::{self, Alignment};
1706     ///
1707     /// struct Foo;
1708     ///
1709     /// impl fmt::Display for Foo {
1710     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1711     ///         let s = if let Some(s) = formatter.align() {
1712     ///             match s {
1713     ///                 Alignment::Left    => "left",
1714     ///                 Alignment::Right   => "right",
1715     ///                 Alignment::Center  => "center",
1716     ///             }
1717     ///         } else {
1718     ///             "into the void"
1719     ///         };
1720     ///         write!(formatter, "{s}")
1721     ///     }
1722     /// }
1723     ///
1724     /// assert_eq!(&format!("{Foo:<}"), "left");
1725     /// assert_eq!(&format!("{Foo:>}"), "right");
1726     /// assert_eq!(&format!("{Foo:^}"), "center");
1727     /// assert_eq!(&format!("{Foo}"), "into the void");
1728     /// ```
1729     #[must_use]
1730     #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1731     pub fn align(&self) -> Option<Alignment> {
1732         match self.align {
1733             rt::v1::Alignment::Left => Some(Alignment::Left),
1734             rt::v1::Alignment::Right => Some(Alignment::Right),
1735             rt::v1::Alignment::Center => Some(Alignment::Center),
1736             rt::v1::Alignment::Unknown => None,
1737         }
1738     }
1739
1740     /// Optionally specified integer width that the output should be.
1741     ///
1742     /// # Examples
1743     ///
1744     /// ```
1745     /// use std::fmt;
1746     ///
1747     /// struct Foo(i32);
1748     ///
1749     /// impl fmt::Display for Foo {
1750     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1751     ///         if let Some(width) = formatter.width() {
1752     ///             // If we received a width, we use it
1753     ///             write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1754     ///         } else {
1755     ///             // Otherwise we do nothing special
1756     ///             write!(formatter, "Foo({})", self.0)
1757     ///         }
1758     ///     }
1759     /// }
1760     ///
1761     /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23)   ");
1762     /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1763     /// ```
1764     #[must_use]
1765     #[stable(feature = "fmt_flags", since = "1.5.0")]
1766     pub fn width(&self) -> Option<usize> {
1767         self.width
1768     }
1769
1770     /// Optionally specified precision for numeric types. Alternatively, the
1771     /// maximum width for string types.
1772     ///
1773     /// # Examples
1774     ///
1775     /// ```
1776     /// use std::fmt;
1777     ///
1778     /// struct Foo(f32);
1779     ///
1780     /// impl fmt::Display for Foo {
1781     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1782     ///         if let Some(precision) = formatter.precision() {
1783     ///             // If we received a precision, we use it.
1784     ///             write!(formatter, "Foo({1:.*})", precision, self.0)
1785     ///         } else {
1786     ///             // Otherwise we default to 2.
1787     ///             write!(formatter, "Foo({:.2})", self.0)
1788     ///         }
1789     ///     }
1790     /// }
1791     ///
1792     /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1793     /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1794     /// ```
1795     #[must_use]
1796     #[stable(feature = "fmt_flags", since = "1.5.0")]
1797     pub fn precision(&self) -> Option<usize> {
1798         self.precision
1799     }
1800
1801     /// Determines if the `+` flag was specified.
1802     ///
1803     /// # Examples
1804     ///
1805     /// ```
1806     /// use std::fmt;
1807     ///
1808     /// struct Foo(i32);
1809     ///
1810     /// impl fmt::Display for Foo {
1811     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1812     ///         if formatter.sign_plus() {
1813     ///             write!(formatter,
1814     ///                    "Foo({}{})",
1815     ///                    if self.0 < 0 { '-' } else { '+' },
1816     ///                    self.0)
1817     ///         } else {
1818     ///             write!(formatter, "Foo({})", self.0)
1819     ///         }
1820     ///     }
1821     /// }
1822     ///
1823     /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1824     /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1825     /// ```
1826     #[must_use]
1827     #[stable(feature = "fmt_flags", since = "1.5.0")]
1828     pub fn sign_plus(&self) -> bool {
1829         self.flags & (1 << FlagV1::SignPlus as u32) != 0
1830     }
1831
1832     /// Determines if the `-` flag was specified.
1833     ///
1834     /// # Examples
1835     ///
1836     /// ```
1837     /// use std::fmt;
1838     ///
1839     /// struct Foo(i32);
1840     ///
1841     /// impl fmt::Display for Foo {
1842     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1843     ///         if formatter.sign_minus() {
1844     ///             // You want a minus sign? Have one!
1845     ///             write!(formatter, "-Foo({})", self.0)
1846     ///         } else {
1847     ///             write!(formatter, "Foo({})", self.0)
1848     ///         }
1849     ///     }
1850     /// }
1851     ///
1852     /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1853     /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1854     /// ```
1855     #[must_use]
1856     #[stable(feature = "fmt_flags", since = "1.5.0")]
1857     pub fn sign_minus(&self) -> bool {
1858         self.flags & (1 << FlagV1::SignMinus as u32) != 0
1859     }
1860
1861     /// Determines if the `#` flag was specified.
1862     ///
1863     /// # Examples
1864     ///
1865     /// ```
1866     /// use std::fmt;
1867     ///
1868     /// struct Foo(i32);
1869     ///
1870     /// impl fmt::Display for Foo {
1871     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1872     ///         if formatter.alternate() {
1873     ///             write!(formatter, "Foo({})", self.0)
1874     ///         } else {
1875     ///             write!(formatter, "{}", self.0)
1876     ///         }
1877     ///     }
1878     /// }
1879     ///
1880     /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1881     /// assert_eq!(&format!("{}", Foo(23)), "23");
1882     /// ```
1883     #[must_use]
1884     #[stable(feature = "fmt_flags", since = "1.5.0")]
1885     pub fn alternate(&self) -> bool {
1886         self.flags & (1 << FlagV1::Alternate as u32) != 0
1887     }
1888
1889     /// Determines if the `0` flag was specified.
1890     ///
1891     /// # Examples
1892     ///
1893     /// ```
1894     /// use std::fmt;
1895     ///
1896     /// struct Foo(i32);
1897     ///
1898     /// impl fmt::Display for Foo {
1899     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1900     ///         assert!(formatter.sign_aware_zero_pad());
1901     ///         assert_eq!(formatter.width(), Some(4));
1902     ///         // We ignore the formatter's options.
1903     ///         write!(formatter, "{}", self.0)
1904     ///     }
1905     /// }
1906     ///
1907     /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1908     /// ```
1909     #[must_use]
1910     #[stable(feature = "fmt_flags", since = "1.5.0")]
1911     pub fn sign_aware_zero_pad(&self) -> bool {
1912         self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1913     }
1914
1915     // FIXME: Decide what public API we want for these two flags.
1916     // https://github.com/rust-lang/rust/issues/48584
1917     fn debug_lower_hex(&self) -> bool {
1918         self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1919     }
1920
1921     fn debug_upper_hex(&self) -> bool {
1922         self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1923     }
1924
1925     /// Creates a [`DebugStruct`] builder designed to assist with creation of
1926     /// [`fmt::Debug`] implementations for structs.
1927     ///
1928     /// [`fmt::Debug`]: self::Debug
1929     ///
1930     /// # Examples
1931     ///
1932     /// ```rust
1933     /// use std::fmt;
1934     /// use std::net::Ipv4Addr;
1935     ///
1936     /// struct Foo {
1937     ///     bar: i32,
1938     ///     baz: String,
1939     ///     addr: Ipv4Addr,
1940     /// }
1941     ///
1942     /// impl fmt::Debug for Foo {
1943     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1944     ///         fmt.debug_struct("Foo")
1945     ///             .field("bar", &self.bar)
1946     ///             .field("baz", &self.baz)
1947     ///             .field("addr", &format_args!("{}", self.addr))
1948     ///             .finish()
1949     ///     }
1950     /// }
1951     ///
1952     /// assert_eq!(
1953     ///     "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1954     ///     format!("{:?}", Foo {
1955     ///         bar: 10,
1956     ///         baz: "Hello World".to_string(),
1957     ///         addr: Ipv4Addr::new(127, 0, 0, 1),
1958     ///     })
1959     /// );
1960     /// ```
1961     #[stable(feature = "debug_builders", since = "1.2.0")]
1962     pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1963         builders::debug_struct_new(self, name)
1964     }
1965
1966     /// Creates a `DebugTuple` builder designed to assist with creation of
1967     /// `fmt::Debug` implementations for tuple structs.
1968     ///
1969     /// # Examples
1970     ///
1971     /// ```rust
1972     /// use std::fmt;
1973     /// use std::marker::PhantomData;
1974     ///
1975     /// struct Foo<T>(i32, String, PhantomData<T>);
1976     ///
1977     /// impl<T> fmt::Debug for Foo<T> {
1978     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1979     ///         fmt.debug_tuple("Foo")
1980     ///             .field(&self.0)
1981     ///             .field(&self.1)
1982     ///             .field(&format_args!("_"))
1983     ///             .finish()
1984     ///     }
1985     /// }
1986     ///
1987     /// assert_eq!(
1988     ///     "Foo(10, \"Hello\", _)",
1989     ///     format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1990     /// );
1991     /// ```
1992     #[stable(feature = "debug_builders", since = "1.2.0")]
1993     pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1994         builders::debug_tuple_new(self, name)
1995     }
1996
1997     /// Creates a `DebugList` builder designed to assist with creation of
1998     /// `fmt::Debug` implementations for list-like structures.
1999     ///
2000     /// # Examples
2001     ///
2002     /// ```rust
2003     /// use std::fmt;
2004     ///
2005     /// struct Foo(Vec<i32>);
2006     ///
2007     /// impl fmt::Debug for Foo {
2008     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2009     ///         fmt.debug_list().entries(self.0.iter()).finish()
2010     ///     }
2011     /// }
2012     ///
2013     /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2014     /// ```
2015     #[stable(feature = "debug_builders", since = "1.2.0")]
2016     pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2017         builders::debug_list_new(self)
2018     }
2019
2020     /// Creates a `DebugSet` builder designed to assist with creation of
2021     /// `fmt::Debug` implementations for set-like structures.
2022     ///
2023     /// # Examples
2024     ///
2025     /// ```rust
2026     /// use std::fmt;
2027     ///
2028     /// struct Foo(Vec<i32>);
2029     ///
2030     /// impl fmt::Debug for Foo {
2031     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2032     ///         fmt.debug_set().entries(self.0.iter()).finish()
2033     ///     }
2034     /// }
2035     ///
2036     /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2037     /// ```
2038     ///
2039     /// [`format_args!`]: crate::format_args
2040     ///
2041     /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2042     /// to build a list of match arms:
2043     ///
2044     /// ```rust
2045     /// use std::fmt;
2046     ///
2047     /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
2048     /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
2049     ///
2050     /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2051     /// where
2052     ///     L: 'a + fmt::Debug, R: 'a + fmt::Debug
2053     /// {
2054     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2055     ///         L::fmt(&(self.0).0, fmt)?;
2056     ///         fmt.write_str(" => ")?;
2057     ///         R::fmt(&(self.0).1, fmt)
2058     ///     }
2059     /// }
2060     ///
2061     /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2062     /// where
2063     ///     K: 'a + fmt::Debug, V: 'a + fmt::Debug
2064     /// {
2065     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2066     ///         fmt.debug_set()
2067     ///         .entries(self.0.iter().map(Arm))
2068     ///         .entry(&Arm(&(format_args!("_"), &self.1)))
2069     ///         .finish()
2070     ///     }
2071     /// }
2072     /// ```
2073     #[stable(feature = "debug_builders", since = "1.2.0")]
2074     pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2075         builders::debug_set_new(self)
2076     }
2077
2078     /// Creates a `DebugMap` builder designed to assist with creation of
2079     /// `fmt::Debug` implementations for map-like structures.
2080     ///
2081     /// # Examples
2082     ///
2083     /// ```rust
2084     /// use std::fmt;
2085     ///
2086     /// struct Foo(Vec<(String, i32)>);
2087     ///
2088     /// impl fmt::Debug for Foo {
2089     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2090     ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2091     ///     }
2092     /// }
2093     ///
2094     /// assert_eq!(
2095     ///     format!("{:?}",  Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2096     ///     r#"{"A": 10, "B": 11}"#
2097     ///  );
2098     /// ```
2099     #[stable(feature = "debug_builders", since = "1.2.0")]
2100     pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2101         builders::debug_map_new(self)
2102     }
2103 }
2104
2105 #[stable(since = "1.2.0", feature = "formatter_write")]
2106 impl Write for Formatter<'_> {
2107     fn write_str(&mut self, s: &str) -> Result {
2108         self.buf.write_str(s)
2109     }
2110
2111     fn write_char(&mut self, c: char) -> Result {
2112         self.buf.write_char(c)
2113     }
2114
2115     fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2116         write(self.buf, args)
2117     }
2118 }
2119
2120 #[stable(feature = "rust1", since = "1.0.0")]
2121 impl Display for Error {
2122     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2123         Display::fmt("an error occurred when formatting an argument", f)
2124     }
2125 }
2126
2127 // Implementations of the core formatting traits
2128
2129 macro_rules! fmt_refs {
2130     ($($tr:ident),*) => {
2131         $(
2132         #[stable(feature = "rust1", since = "1.0.0")]
2133         impl<T: ?Sized + $tr> $tr for &T {
2134             fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2135         }
2136         #[stable(feature = "rust1", since = "1.0.0")]
2137         impl<T: ?Sized + $tr> $tr for &mut T {
2138             fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2139         }
2140         )*
2141     }
2142 }
2143
2144 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2145
2146 #[unstable(feature = "never_type", issue = "35121")]
2147 impl Debug for ! {
2148     fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2149         *self
2150     }
2151 }
2152
2153 #[unstable(feature = "never_type", issue = "35121")]
2154 impl Display for ! {
2155     fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2156         *self
2157     }
2158 }
2159
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 impl Debug for bool {
2162     #[inline]
2163     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2164         Display::fmt(self, f)
2165     }
2166 }
2167
2168 #[stable(feature = "rust1", since = "1.0.0")]
2169 impl Display for bool {
2170     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2171         Display::fmt(if *self { "true" } else { "false" }, f)
2172     }
2173 }
2174
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 impl Debug for str {
2177     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2178         f.write_char('"')?;
2179         let mut from = 0;
2180         for (i, c) in self.char_indices() {
2181             let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2182                 escape_grapheme_extended: true,
2183                 escape_single_quote: false,
2184                 escape_double_quote: true,
2185             });
2186             // If char needs escaping, flush backlog so far and write, else skip
2187             if esc.len() != 1 {
2188                 f.write_str(&self[from..i])?;
2189                 for c in esc {
2190                     f.write_char(c)?;
2191                 }
2192                 from = i + c.len_utf8();
2193             }
2194         }
2195         f.write_str(&self[from..])?;
2196         f.write_char('"')
2197     }
2198 }
2199
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 impl Display for str {
2202     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2203         f.pad(self)
2204     }
2205 }
2206
2207 #[stable(feature = "rust1", since = "1.0.0")]
2208 impl Debug for char {
2209     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2210         f.write_char('\'')?;
2211         for c in self.escape_debug_ext(EscapeDebugExtArgs {
2212             escape_grapheme_extended: true,
2213             escape_single_quote: true,
2214             escape_double_quote: false,
2215         }) {
2216             f.write_char(c)?
2217         }
2218         f.write_char('\'')
2219     }
2220 }
2221
2222 #[stable(feature = "rust1", since = "1.0.0")]
2223 impl Display for char {
2224     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2225         if f.width.is_none() && f.precision.is_none() {
2226             f.write_char(*self)
2227         } else {
2228             f.pad(self.encode_utf8(&mut [0; 4]))
2229         }
2230     }
2231 }
2232
2233 #[stable(feature = "rust1", since = "1.0.0")]
2234 impl<T: ?Sized> Pointer for *const T {
2235     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2236         // Cast is needed here because `.addr()` requires `T: Sized`.
2237         pointer_fmt_inner((*self as *const ()).addr(), f)
2238     }
2239 }
2240
2241 /// Since the formatting will be identical for all pointer types, use a non-monomorphized
2242 /// implementation for the actual formatting to reduce the amount of codegen work needed.
2243 ///
2244 /// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
2245 /// `fn(...) -> ...` without using [problematic] "Oxford Casts".
2246 ///
2247 /// [problematic]: https://github.com/rust-lang/rust/issues/95489
2248 pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
2249     let old_width = f.width;
2250     let old_flags = f.flags;
2251
2252     // The alternate flag is already treated by LowerHex as being special-
2253     // it denotes whether to prefix with 0x. We use it to work out whether
2254     // or not to zero extend, and then unconditionally set it to get the
2255     // prefix.
2256     if f.alternate() {
2257         f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2258
2259         if f.width.is_none() {
2260             f.width = Some((usize::BITS / 4) as usize + 2);
2261         }
2262     }
2263     f.flags |= 1 << (FlagV1::Alternate as u32);
2264
2265     let ret = LowerHex::fmt(&ptr_addr, f);
2266
2267     f.width = old_width;
2268     f.flags = old_flags;
2269
2270     ret
2271 }
2272
2273 #[stable(feature = "rust1", since = "1.0.0")]
2274 impl<T: ?Sized> Pointer for *mut T {
2275     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2276         Pointer::fmt(&(*self as *const T), f)
2277     }
2278 }
2279
2280 #[stable(feature = "rust1", since = "1.0.0")]
2281 impl<T: ?Sized> Pointer for &T {
2282     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2283         Pointer::fmt(&(*self as *const T), f)
2284     }
2285 }
2286
2287 #[stable(feature = "rust1", since = "1.0.0")]
2288 impl<T: ?Sized> Pointer for &mut T {
2289     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2290         Pointer::fmt(&(&**self as *const T), f)
2291     }
2292 }
2293
2294 // Implementation of Display/Debug for various core types
2295
2296 #[stable(feature = "rust1", since = "1.0.0")]
2297 impl<T: ?Sized> Debug for *const T {
2298     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2299         Pointer::fmt(self, f)
2300     }
2301 }
2302 #[stable(feature = "rust1", since = "1.0.0")]
2303 impl<T: ?Sized> Debug for *mut T {
2304     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2305         Pointer::fmt(self, f)
2306     }
2307 }
2308
2309 macro_rules! peel {
2310     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2311 }
2312
2313 macro_rules! tuple {
2314     () => ();
2315     ( $($name:ident,)+ ) => (
2316         maybe_tuple_doc! {
2317             $($name)+ @
2318             #[stable(feature = "rust1", since = "1.0.0")]
2319             impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2320                 #[allow(non_snake_case, unused_assignments)]
2321                 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2322                     let mut builder = f.debug_tuple("");
2323                     let ($(ref $name,)+) = *self;
2324                     $(
2325                         builder.field(&$name);
2326                     )+
2327
2328                     builder.finish()
2329                 }
2330             }
2331         }
2332         peel! { $($name,)+ }
2333     )
2334 }
2335
2336 macro_rules! maybe_tuple_doc {
2337     ($a:ident @ #[$meta:meta] $item:item) => {
2338         #[doc = "This trait is implemented for tuples up to twelve items long."]
2339         #[$meta]
2340         $item
2341     };
2342     ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
2343         #[doc(hidden)]
2344         #[$meta]
2345         $item
2346     };
2347 }
2348
2349 macro_rules! last_type {
2350     ($a:ident,) => { $a };
2351     ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2352 }
2353
2354 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2355
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 impl<T: Debug> Debug for [T] {
2358     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2359         f.debug_list().entries(self.iter()).finish()
2360     }
2361 }
2362
2363 #[stable(feature = "rust1", since = "1.0.0")]
2364 impl Debug for () {
2365     #[inline]
2366     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2367         f.pad("()")
2368     }
2369 }
2370 #[stable(feature = "rust1", since = "1.0.0")]
2371 impl<T: ?Sized> Debug for PhantomData<T> {
2372     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2373         f.debug_struct("PhantomData").finish()
2374     }
2375 }
2376
2377 #[stable(feature = "rust1", since = "1.0.0")]
2378 impl<T: Copy + Debug> Debug for Cell<T> {
2379     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2380         f.debug_struct("Cell").field("value", &self.get()).finish()
2381     }
2382 }
2383
2384 #[stable(feature = "rust1", since = "1.0.0")]
2385 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2386     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2387         match self.try_borrow() {
2388             Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2389             Err(_) => {
2390                 // The RefCell is mutably borrowed so we can't look at its value
2391                 // here. Show a placeholder instead.
2392                 struct BorrowedPlaceholder;
2393
2394                 impl Debug for BorrowedPlaceholder {
2395                     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2396                         f.write_str("<borrowed>")
2397                     }
2398                 }
2399
2400                 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2401             }
2402         }
2403     }
2404 }
2405
2406 #[stable(feature = "rust1", since = "1.0.0")]
2407 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2408     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2409         Debug::fmt(&**self, f)
2410     }
2411 }
2412
2413 #[stable(feature = "rust1", since = "1.0.0")]
2414 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2415     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2416         Debug::fmt(&*(self.deref()), f)
2417     }
2418 }
2419
2420 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2421 impl<T: ?Sized> Debug for UnsafeCell<T> {
2422     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2423         f.debug_struct("UnsafeCell").finish_non_exhaustive()
2424     }
2425 }
2426
2427 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2428 impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
2429     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2430         f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
2431     }
2432 }
2433
2434 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2435 // it's a lot easier than creating all of the rt::Piece structures here.
2436 // There are also tests in the alloc crate, for those that need allocations.