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