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