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