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