1 //! Utilities for formatting and printing strings.
3 // ignore-tidy-undocumented-unsafe
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use crate::cell::{Cell, Ref, RefCell, RefMut, UnsafeCell};
8 use crate::marker::PhantomData;
10 use crate::num::flt2dec;
11 use crate::ops::Deref;
19 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
20 /// Possible alignments returned by `Formatter::align`
23 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
24 /// Indication that contents should be left-aligned.
26 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
27 /// Indication that contents should be right-aligned.
29 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
30 /// Indication that contents should be center-aligned.
34 #[stable(feature = "debug_builders", since = "1.2.0")]
35 pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
37 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
43 /// The type returned by formatter methods.
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)
63 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
65 /// assert_eq!(format!("{}", pythagorean_triple), "(3, 4, 5)");
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub type Result = result::Result<(), Error>;
70 /// The error type which is returned from formatting a message into a stream.
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
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
80 /// [`std::io::Error`]: ../../std/io/struct.Error.html
81 /// [`std::error::Error`]: ../../std/error/trait.Error.html
86 /// use std::fmt::{self, write};
88 /// let mut output = String::new();
89 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
90 /// panic!("An error occurred");
93 #[stable(feature = "rust1", since = "1.0.0")]
94 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
97 /// A collection of methods that are required to format a message into a stream.
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.
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.
107 /// [`write!`]: ../../std/macro.write.html
108 /// [`io::Write`]: ../../std/io/trait.Write.html
109 #[stable(feature = "rust1", since = "1.0.0")]
111 /// Writes a string slice into this writer, returning whether the write
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.
120 /// This function will return an instance of [`Error`] on error.
122 /// [`Error`]: struct.Error.html
127 /// use std::fmt::{Error, Write};
129 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
133 /// let mut buf = String::new();
134 /// writer(&mut buf, "hola").unwrap();
135 /// assert_eq!(&buf, "hola");
137 #[stable(feature = "rust1", since = "1.0.0")]
138 fn write_str(&mut self, s: &str) -> Result;
140 /// Writes a [`char`] into this writer, returning whether the write succeeded.
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.
149 /// This function will return an instance of [`Error`] on error.
151 /// [`char`]: ../../std/primitive.char.html
152 /// [`Error`]: struct.Error.html
157 /// use std::fmt::{Error, Write};
159 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
163 /// let mut buf = String::new();
164 /// writer(&mut buf, 'a').unwrap();
165 /// writer(&mut buf, 'b').unwrap();
166 /// assert_eq!(&buf, "ab");
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]))
173 /// Glue for usage of the [`write!`] macro with implementors of this trait.
175 /// This method should generally not be invoked manually, but rather through
176 /// the [`write!`] macro itself.
178 /// [`write!`]: ../../std/macro.write.html
183 /// use std::fmt::{Error, Write};
185 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
186 /// f.write_fmt(format_args!("{}", s))
189 /// let mut buf = String::new();
190 /// writer(&mut buf, "world").unwrap();
191 /// assert_eq!(&buf, "world");
193 #[stable(feature = "rust1", since = "1.0.0")]
194 fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
195 write(&mut self, args)
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)
205 fn write_char(&mut self, c: char) -> Result {
206 (**self).write_char(c)
209 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
210 (**self).write_fmt(args)
214 /// Configuration for formatting.
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`].
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.
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> {
231 align: rt::v1::Alignment,
232 width: Option<usize>,
233 precision: Option<usize>,
235 buf: &'a mut (dyn Write + 'a),
238 // NB. Argument is essentially an optimized partially applied formatting function,
239 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
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")]
253 pub struct ArgumentV1<'a> {
255 formatter: fn(&Opaque, &mut Formatter<'_>) -> Result,
258 impl<'a> ArgumentV1<'a> {
260 fn show_usize(x: &usize, f: &mut Formatter<'_>) -> Result {
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) } }
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)
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) })
285 // flags available in the v1 format of format_args
286 #[derive(Copy, Clone)]
296 impl<'a> Arguments<'a> {
297 /// When using the format_args!() macro, this function is used to generate the
298 /// Arguments structure.
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 }
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 .
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],
320 Arguments { pieces, fmt: Some(fmt), args }
323 /// Estimates the length of the formatted text.
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.
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();
333 if self.args.is_empty() {
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.
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)
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.
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.
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!`.
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);
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],
379 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
380 fmt: Option<&'a [rt::v1::Argument]>,
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>],
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)
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)
403 /// `Debug` should format the output in a programmer-facing, debugging context.
405 /// Generally speaking, you should just `derive` a `Debug` implementation.
407 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
409 /// For more information on formatters, see [the module-level documentation][module].
411 /// [module]: ../../std/fmt/index.html
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 `)`.
421 /// Deriving an implementation:
430 /// let origin = Point { x: 0, y: 0 };
432 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
435 /// Manually implementing:
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)
454 /// let origin = Point { x: 0, y: 0 };
456 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
459 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
460 /// implementations, such as [`debug_struct`].
462 /// `Debug` implementations using either `derive` or the debug builder API
463 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
465 /// [`debug_struct`]: ../../std/fmt/struct.Formatter.html#method.debug_struct
466 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
468 /// Pretty-printing with `#?`:
477 /// let origin = Point { x: 0, y: 0 };
479 /// assert_eq!(format!("The origin is: {:#?}", origin),
480 /// "The origin is: Point {
486 #[stable(feature = "rust1", since = "1.0.0")]
487 #[rustc_on_unimplemented(
490 label = "`{Self}` cannot be formatted using `{{:?}}`",
491 note = "add `#[derive(Debug)]` or manually implement `{Debug}`"
493 message = "`{Self}` doesn't implement `{Debug}`",
494 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
496 #[doc(alias = "{:?}")]
497 #[rustc_diagnostic_item = "debug_trait"]
499 /// Formats the value using the given formatter.
506 /// struct Position {
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)
520 /// let position = Position { longitude: 1.987, latitude: 2.983 };
521 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
523 /// assert_eq!(format!("{:#?}", position), "(
528 #[stable(feature = "rust1", since = "1.0.0")]
529 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
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 */
542 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
544 pub use macros::Debug;
546 /// Format trait for an empty format, `{}`.
548 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
549 /// output, and so cannot be derived.
551 /// [debug]: trait.Debug.html
553 /// For more information on formatters, see [the module-level documentation][module].
555 /// [module]: ../../std/fmt/index.html
559 /// Implementing `Display` on a type:
569 /// impl fmt::Display for Point {
570 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571 /// write!(f, "({}, {})", self.x, self.y)
575 /// let origin = Point { x: 0, y: 0 };
577 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
579 #[rustc_on_unimplemented(
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"
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"
591 #[stable(feature = "rust1", since = "1.0.0")]
593 /// Formats the value using the given formatter.
600 /// struct Position {
605 /// impl fmt::Display for Position {
606 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607 /// write!(f, "({}, {})", self.longitude, self.latitude)
611 /// assert_eq!("(1.987, 2.983)",
612 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
614 #[stable(feature = "rust1", since = "1.0.0")]
615 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
620 /// The `Octal` trait should format its output as a number in base-8.
622 /// For primitive signed integers (`i8` to `i128`, and `isize`),
623 /// negative values are formatted as the two’s complement representation.
625 /// The alternate flag, `#`, adds a `0o` in front of the output.
627 /// For more information on formatters, see [the module-level documentation][module].
629 /// [module]: ../../std/fmt/index.html
633 /// Basic usage with `i32`:
636 /// let x = 42; // 42 is '52' in octal
638 /// assert_eq!(format!("{:o}", x), "52");
639 /// assert_eq!(format!("{:#o}", x), "0o52");
641 /// assert_eq!(format!("{:o}", -16), "37777777760");
644 /// Implementing `Octal` on a type:
649 /// struct Length(i32);
651 /// impl fmt::Octal for Length {
652 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
653 /// let val = self.0;
655 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
659 /// let l = Length(9);
661 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
663 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
665 #[stable(feature = "rust1", since = "1.0.0")]
667 /// Formats the value using the given formatter.
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
674 /// The `Binary` trait should format its output as a number in binary.
676 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
677 /// negative values are formatted as the two’s complement representation.
679 /// The alternate flag, `#`, adds a `0b` in front of the output.
681 /// For more information on formatters, see [the module-level documentation][module].
685 /// Basic usage with [`i32`]:
688 /// let x = 42; // 42 is '101010' in binary
690 /// assert_eq!(format!("{:b}", x), "101010");
691 /// assert_eq!(format!("{:#b}", x), "0b101010");
693 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
696 /// Implementing `Binary` on a type:
701 /// struct Length(i32);
703 /// impl fmt::Binary for Length {
704 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
705 /// let val = self.0;
707 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
711 /// let l = Length(107);
713 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
716 /// format!("l as binary is: {:#032b}", l),
717 /// "l as binary is: 0b000000000000000000000001101011"
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")]
728 /// Formats the value using the given formatter.
729 #[stable(feature = "rust1", since = "1.0.0")]
730 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
735 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
738 /// For primitive signed integers (`i8` to `i128`, and `isize`),
739 /// negative values are formatted as the two’s complement representation.
741 /// The alternate flag, `#`, adds a `0x` in front of the output.
743 /// For more information on formatters, see [the module-level documentation][module].
745 /// [module]: ../../std/fmt/index.html
749 /// Basic usage with `i32`:
752 /// let x = 42; // 42 is '2a' in hex
754 /// assert_eq!(format!("{:x}", x), "2a");
755 /// assert_eq!(format!("{:#x}", x), "0x2a");
757 /// assert_eq!(format!("{:x}", -16), "fffffff0");
760 /// Implementing `LowerHex` on a type:
765 /// struct Length(i32);
767 /// impl fmt::LowerHex for Length {
768 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 /// let val = self.0;
771 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
775 /// let l = Length(9);
777 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
779 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
781 #[stable(feature = "rust1", since = "1.0.0")]
783 /// Formats the value using the given formatter.
784 #[stable(feature = "rust1", since = "1.0.0")]
785 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
790 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
793 /// For primitive signed integers (`i8` to `i128`, and `isize`),
794 /// negative values are formatted as the two’s complement representation.
796 /// The alternate flag, `#`, adds a `0x` in front of the output.
798 /// For more information on formatters, see [the module-level documentation][module].
800 /// [module]: ../../std/fmt/index.html
804 /// Basic usage with `i32`:
807 /// let x = 42; // 42 is '2A' in hex
809 /// assert_eq!(format!("{:X}", x), "2A");
810 /// assert_eq!(format!("{:#X}", x), "0x2A");
812 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
815 /// Implementing `UpperHex` on a type:
820 /// struct Length(i32);
822 /// impl fmt::UpperHex for Length {
823 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
824 /// let val = self.0;
826 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
830 /// let l = Length(i32::max_value());
832 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
834 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
836 #[stable(feature = "rust1", since = "1.0.0")]
838 /// Formats the value using the given formatter.
839 #[stable(feature = "rust1", since = "1.0.0")]
840 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
845 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
848 /// For more information on formatters, see [the module-level documentation][module].
850 /// [module]: ../../std/fmt/index.html
854 /// Basic usage with `&i32`:
859 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
862 /// Implementing `Pointer` on a type:
867 /// struct Length(i32);
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
873 /// let ptr = self as *const Self;
874 /// fmt::Pointer::fmt(&ptr, f)
878 /// let l = Length(42);
880 /// println!("l is in memory here: {:p}", l);
882 /// let l_ptr = format!("{:018p}", l);
883 /// assert_eq!(l_ptr.len(), 18);
884 /// assert_eq!(&l_ptr[..2], "0x");
886 #[stable(feature = "rust1", since = "1.0.0")]
888 /// Formats the value using the given formatter.
889 #[stable(feature = "rust1", since = "1.0.0")]
890 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
895 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
897 /// For more information on formatters, see [the module-level documentation][module].
899 /// [module]: ../../std/fmt/index.html
903 /// Basic usage with `f64`:
906 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
908 /// assert_eq!(format!("{:e}", x), "4.2e1");
911 /// Implementing `LowerExp` on a type:
916 /// struct Length(i32);
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
925 /// let l = Length(100);
928 /// format!("l in scientific notation is: {:e}", l),
929 /// "l in scientific notation is: 1e2"
933 /// format!("l in scientific notation is: {:05e}", l),
934 /// "l in scientific notation is: 001e2"
937 #[stable(feature = "rust1", since = "1.0.0")]
939 /// Formats the value using the given formatter.
940 #[stable(feature = "rust1", since = "1.0.0")]
941 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
946 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
948 /// For more information on formatters, see [the module-level documentation][module].
950 /// [module]: ../../std/fmt/index.html
954 /// Basic usage with `f64`:
957 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
959 /// assert_eq!(format!("{:E}", x), "4.2E1");
962 /// Implementing `UpperExp` on a type:
967 /// struct Length(i32);
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
976 /// let l = Length(100);
979 /// format!("l in scientific notation is: {:E}", l),
980 /// "l in scientific notation is: 1E2"
984 /// format!("l in scientific notation is: {:05E}", l),
985 /// "l in scientific notation is: 001E2"
988 #[stable(feature = "rust1", since = "1.0.0")]
990 /// Formats the value using the given formatter.
991 #[stable(feature = "rust1", since = "1.0.0")]
992 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
995 /// The `write` function takes an output stream, and an `Arguments` struct
996 /// that can be precompiled with the `format_args!` macro.
998 /// The arguments will be formatted according to the specified format string
999 /// into the output stream provided.
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!");
1014 /// Please note that using [`write!`] might be preferable. Example:
1017 /// use std::fmt::Write;
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!");
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 {
1033 align: rt::v1::Alignment::Unknown,
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)?;
1049 // Every spec has a corresponding argument that is preceded by
1051 for (arg, piece) in fmt.iter().zip(args.pieces.iter()) {
1052 formatter.buf.write_str(*piece)?;
1053 run(&mut formatter, arg, &args.args)?;
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)?;
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);
1074 // Extract the correct argument
1075 let value = args[arg.position];
1077 // Then actually do some printing
1078 (value.formatter)(value.value, fmt)
1081 fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1083 rt::v1::Count::Is(n) => Some(n),
1084 rt::v1::Count::Implied => None,
1085 rt::v1::Count::Param(i) => args[i].as_usize(),
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 {
1097 fn new(fill: char, padding: usize) -> PostPadding {
1098 PostPadding { fill, padding }
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)?;
1110 impl<'a> Formatter<'a> {
1111 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1114 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1117 // We want to change this
1118 buf: wrap(self.buf),
1120 // And preserve these
1125 precision: self.precision,
1129 // Helper methods used for padding and processing formatting arguments that
1130 // all formatting traits can use.
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.
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
1143 /// This function will correctly account for the flags provided as well as
1144 /// the minimum width. It will not take precision into account.
1151 /// struct Foo { nb: i32 };
1154 /// fn new(nb: i32) -> Foo {
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();
1166 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
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");
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();
1179 let mut sign = None;
1180 if !is_nonnegative {
1183 } else if self.sign_plus() {
1188 let prefix = if self.alternate() {
1189 width += prefix.chars().count();
1195 // Writes the sign if it exists, and then the prefix if it was requested
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)?;
1201 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1204 // The `width` field is more of a `min-width` parameter at this point.
1206 // If there's no minimum length requirements then we can just
1209 write_prefix(self, sign, prefix)?;
1210 self.buf.write_str(buf)
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)
1218 // The sign and prefix goes before the padding if the fill character
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;
1231 // Otherwise, the sign and prefix goes after the padding
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)
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:
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
1251 /// Notably this function ignores the `flag` parameters.
1260 /// impl fmt::Display for Foo {
1261 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1262 /// formatter.pad("Foo")
1266 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1267 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
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);
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
1286 s.get(..i).unwrap_or(&s)
1293 // The `width` field is more of a `min-width` parameter at this point.
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.
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)
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
1318 default: rt::v1::Alignment,
1319 ) -> result::Result<PostPadding, Error> {
1320 let align = match self.align {
1321 rt::v1::Alignment::Unknown => default,
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),
1331 for _ in 0..pre_pad {
1332 self.buf.write_char(self.fill)?;
1335 Ok(PostPadding::new(self.fill, post_pad))
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)?;
1354 // remove the sign from the formatted parts
1355 formatted.sign = "";
1356 width = width.saturating_sub(sign.len());
1357 align = rt::v1::Alignment::Right;
1359 self.align = rt::v1::Alignment::Right;
1362 // remaining parts go through the ordinary padding process.
1363 let len = formatted.len();
1364 let ret = if width <= len {
1366 self.write_formatted_parts(&formatted)
1368 let post_padding = self.padding(width - len, align)?;
1369 self.write_formatted_parts(&formatted)?;
1370 post_padding.write(self.buf)
1372 self.fill = old_fill;
1373 self.align = old_align;
1376 // this is the common case and we take a shortcut
1377 self.write_formatted_parts(formatted)
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) })
1386 if !formatted.sign.is_empty() {
1387 self.buf.write_str(formatted.sign)?;
1389 for part in formatted.parts {
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();
1399 self.buf.write_str(&ZEROES[..nzeroes])?;
1402 flt2dec::Part::Num(mut v) => {
1404 let len = part.len();
1405 for c in s[..len].iter_mut().rev() {
1406 *c = b'0' + (v % 10) as u8;
1409 write_bytes(self.buf, &s[..len])?;
1411 flt2dec::Part::Copy(buf) => {
1412 write_bytes(self.buf, buf)?;
1419 /// Writes some data to the underlying buffer contained within this
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")
1437 /// assert_eq!(&format!("{}", Foo), "Foo");
1438 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 pub fn write_str(&mut self, data: &str) -> Result {
1442 self.buf.write_str(data)
1445 /// Writes some formatted information into this instance.
1452 /// struct Foo(i32);
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))
1460 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1461 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1465 write(self.buf, fmt)
1468 /// Flags for formatting
1469 #[stable(feature = "rust1", since = "1.0.0")]
1472 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1473 or `sign_aware_zero_pad` methods instead"
1475 pub fn flags(&self) -> u32 {
1479 /// Character used as 'fill' whenever there is alignment.
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)?;
1497 /// write!(formatter, "{}", c)
1502 /// // We set alignment to the left with ">".
1503 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1504 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1506 #[stable(feature = "fmt_flags", since = "1.5.0")]
1507 pub fn fill(&self) -> char {
1511 /// Flag indicating what form of alignment was requested.
1516 /// extern crate core;
1518 /// use std::fmt::{self, Alignment};
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() {
1526 /// Alignment::Left => "left",
1527 /// Alignment::Right => "right",
1528 /// Alignment::Center => "center",
1533 /// write!(formatter, "{}", s)
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");
1542 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1543 pub fn align(&self) -> Option<Alignment> {
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,
1552 /// Optionally specified integer width that the output should be.
1559 /// struct Foo(i32);
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)
1567 /// // Otherwise we do nothing special
1568 /// write!(formatter, "Foo({})", self.0)
1573 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1574 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1576 #[stable(feature = "fmt_flags", since = "1.5.0")]
1577 pub fn width(&self) -> Option<usize> {
1581 /// Optionally specified precision for numeric types.
1588 /// struct Foo(f32);
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)
1596 /// // Otherwise we default to 2.
1597 /// write!(formatter, "Foo({:.2})", self.0)
1602 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1603 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1605 #[stable(feature = "fmt_flags", since = "1.5.0")]
1606 pub fn precision(&self) -> Option<usize> {
1610 /// Determines if the `+` flag was specified.
1617 /// struct Foo(i32);
1619 /// impl fmt::Display for Foo {
1620 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1621 /// if formatter.sign_plus() {
1622 /// write!(formatter,
1624 /// if self.0 < 0 { '-' } else { '+' },
1627 /// write!(formatter, "Foo({})", self.0)
1632 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1633 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
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
1640 /// Determines if the `-` flag was specified.
1647 /// struct Foo(i32);
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)
1655 /// write!(formatter, "Foo({})", self.0)
1660 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1661 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
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
1668 /// Determines if the `#` flag was specified.
1675 /// struct Foo(i32);
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)
1682 /// write!(formatter, "{}", self.0)
1687 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1688 /// assert_eq!(&format!("{}", Foo(23)), "23");
1690 #[stable(feature = "fmt_flags", since = "1.5.0")]
1691 pub fn alternate(&self) -> bool {
1692 self.flags & (1 << FlagV1::Alternate as u32) != 0
1695 /// Determines if the `0` flag was specified.
1702 /// struct Foo(i32);
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)
1713 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
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
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
1726 fn debug_upper_hex(&self) -> bool {
1727 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1730 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1731 /// [`fmt::Debug`] implementations for structs.
1733 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1734 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1740 /// use std::net::Ipv4Addr;
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))
1759 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1760 /// format!("{:?}", Foo {
1762 /// baz: "Hello World".to_string(),
1763 /// addr: Ipv4Addr::new(127, 0, 0, 1),
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)
1772 /// Creates a `DebugTuple` builder designed to assist with creation of
1773 /// `fmt::Debug` implementations for tuple structs.
1779 /// use std::marker::PhantomData;
1781 /// struct Foo<T>(i32, String, PhantomData<T>);
1783 /// impl<T> fmt::Debug for Foo<T> {
1784 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1785 /// fmt.debug_tuple("Foo")
1788 /// .field(&format_args!("_"))
1794 /// "Foo(10, \"Hello\", _)",
1795 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
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)
1803 /// Creates a `DebugList` builder designed to assist with creation of
1804 /// `fmt::Debug` implementations for list-like structures.
1811 /// struct Foo(Vec<i32>);
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()
1819 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
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)
1826 /// Creates a `DebugSet` builder designed to assist with creation of
1827 /// `fmt::Debug` implementations for set-like structures.
1834 /// struct Foo(Vec<i32>);
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()
1842 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
1845 /// [`format_args!`]: ../../std/macro.format_args.html
1847 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1848 /// to build a list of match arms:
1853 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1854 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1856 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1858 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
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)
1867 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1869 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1871 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1873 /// .entries(self.0.iter().map(Arm))
1874 /// .entry(&Arm(&(format_args!("_"), &self.1)))
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)
1884 /// Creates a `DebugMap` builder designed to assist with creation of
1885 /// `fmt::Debug` implementations for map-like structures.
1892 /// struct Foo(Vec<(String, i32)>);
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()
1901 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1902 /// r#"{"A": 10, "B": 11}"#
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)
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)
1917 fn write_char(&mut self, c: char) -> Result {
1918 self.buf.write_char(c)
1921 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
1922 write(self.buf, args)
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)
1933 // Implementations of the core formatting traits
1935 macro_rules! fmt_refs {
1936 ($($tr:ident),*) => {
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) }
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) }
1950 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1952 #[unstable(feature = "never_type", issue = "35121")]
1954 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
1959 #[unstable(feature = "never_type", issue = "35121")]
1960 impl Display for ! {
1961 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
1966 #[stable(feature = "rust1", since = "1.0.0")]
1967 impl Debug for bool {
1969 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1970 Display::fmt(self, f)
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)
1981 #[stable(feature = "rust1", since = "1.0.0")]
1982 impl Debug for str {
1983 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
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
1990 f.write_str(&self[from..i])?;
1994 from = i + c.len_utf8();
1997 f.write_str(&self[from..])?;
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 impl Display for str {
2004 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
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() {
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() {
2026 f.pad(self.encode_utf8(&mut [0; 4]))
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;
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
2042 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2044 if f.width.is_none() {
2045 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2048 f.flags |= 1 << (FlagV1::Alternate as u32);
2050 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2052 f.width = old_width;
2053 f.flags = old_flags;
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)
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)
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)
2080 // Implementation of Display/Debug for various core types
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)
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)
2096 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2099 macro_rules! tuple {
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;
2109 builder.field(&$name);
2115 peel! { $($name,)+ }
2119 macro_rules! last_type {
2120 ($a:ident,) => { $a };
2121 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2124 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
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()
2133 #[stable(feature = "rust1", since = "1.0.0")]
2136 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
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")
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()
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(),
2160 // The RefCell is mutably borrowed so we can't look at its value
2161 // here. Show a placeholder instead.
2162 struct BorrowedPlaceholder;
2164 impl Debug for BorrowedPlaceholder {
2165 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2166 f.write_str("<borrowed>")
2170 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
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)
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)
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 {
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.