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