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