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