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`.
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.
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()>,
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")]
261 pub struct ArgumentV1<'a> {
263 formatter: fn(&Void, &mut Formatter<'_>) -> Result,
266 impl<'a> ArgumentV1<'a> {
268 fn show_usize(x: &usize, f: &mut Formatter<'_>) -> Result {
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) } }
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)
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) })
293 // flags available in the v1 format of format_args
294 #[derive(Copy, Clone)]
304 impl<'a> Arguments<'a> {
305 /// When using the format_args!() macro, this function is used to generate the
306 /// Arguments structure.
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 }
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 .
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],
328 Arguments { pieces, fmt: Some(fmt), args }
331 /// Estimates the length of the formatted text.
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.
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();
341 if self.args.is_empty() {
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.
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)
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.
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.
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!`.
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);
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],
387 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
388 fmt: Option<&'a [rt::v1::Argument]>,
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>],
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)
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)
411 /// `Debug` should format the output in a programmer-facing, debugging context.
413 /// Generally speaking, you should just `derive` a `Debug` implementation.
415 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
417 /// For more information on formatters, see [the module-level documentation][module].
419 /// [module]: ../../std/fmt/index.html
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 `)`.
429 /// Deriving an implementation:
438 /// let origin = Point { x: 0, y: 0 };
440 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
443 /// Manually implementing:
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)
462 /// let origin = Point { x: 0, y: 0 };
464 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
467 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
468 /// implementations, such as [`debug_struct`].
470 /// `Debug` implementations using either `derive` or the debug builder API
471 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
473 /// [`debug_struct`]: ../../std/fmt/struct.Formatter.html#method.debug_struct
474 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
476 /// Pretty-printing with `#?`:
485 /// let origin = Point { x: 0, y: 0 };
487 /// assert_eq!(format!("The origin is: {:#?}", origin),
488 /// "The origin is: Point {
494 #[stable(feature = "rust1", since = "1.0.0")]
495 #[rustc_on_unimplemented(
498 label = "`{Self}` cannot be formatted using `{{:?}}`",
499 note = "add `#[derive(Debug)]` or manually implement `{Debug}`"
501 message = "`{Self}` doesn't implement `{Debug}`",
502 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
504 #[doc(alias = "{:?}")]
505 #[rustc_diagnostic_item = "debug_trait"]
507 /// Formats the value using the given formatter.
514 /// struct Position {
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)
528 /// let position = Position { longitude: 1.987, latitude: 2.983 };
529 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
531 /// assert_eq!(format!("{:#?}", position), "(
536 #[stable(feature = "rust1", since = "1.0.0")]
537 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
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 */
550 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
552 pub use macros::Debug;
554 /// Format trait for an empty format, `{}`.
556 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
557 /// output, and so cannot be derived.
559 /// [debug]: trait.Debug.html
561 /// For more information on formatters, see [the module-level documentation][module].
563 /// [module]: ../../std/fmt/index.html
567 /// Implementing `Display` on a type:
577 /// impl fmt::Display for Point {
578 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579 /// write!(f, "({}, {})", self.x, self.y)
583 /// let origin = Point { x: 0, y: 0 };
585 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
587 #[rustc_on_unimplemented(
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"
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"
599 #[stable(feature = "rust1", since = "1.0.0")]
601 /// Formats the value using the given formatter.
608 /// struct Position {
613 /// impl fmt::Display for Position {
614 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615 /// write!(f, "({}, {})", self.longitude, self.latitude)
619 /// assert_eq!("(1.987, 2.983)",
620 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
622 #[stable(feature = "rust1", since = "1.0.0")]
623 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
628 /// The `Octal` trait should format its output as a number in base-8.
630 /// For primitive signed integers (`i8` to `i128`, and `isize`),
631 /// negative values are formatted as the two’s complement representation.
633 /// The alternate flag, `#`, adds a `0o` in front of the output.
635 /// For more information on formatters, see [the module-level documentation][module].
637 /// [module]: ../../std/fmt/index.html
641 /// Basic usage with `i32`:
644 /// let x = 42; // 42 is '52' in octal
646 /// assert_eq!(format!("{:o}", x), "52");
647 /// assert_eq!(format!("{:#o}", x), "0o52");
649 /// assert_eq!(format!("{:o}", -16), "37777777760");
652 /// Implementing `Octal` on a type:
657 /// struct Length(i32);
659 /// impl fmt::Octal for Length {
660 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 /// let val = self.0;
663 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
667 /// let l = Length(9);
669 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
671 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
673 #[stable(feature = "rust1", since = "1.0.0")]
675 /// Formats the value using the given formatter.
676 #[stable(feature = "rust1", since = "1.0.0")]
677 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
682 /// The `Binary` trait should format its output as a number in binary.
684 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
685 /// negative values are formatted as the two’s complement representation.
687 /// The alternate flag, `#`, adds a `0b` in front of the output.
689 /// For more information on formatters, see [the module-level documentation][module].
693 /// Basic usage with [`i32`]:
696 /// let x = 42; // 42 is '101010' in binary
698 /// assert_eq!(format!("{:b}", x), "101010");
699 /// assert_eq!(format!("{:#b}", x), "0b101010");
701 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
704 /// Implementing `Binary` on a type:
709 /// struct Length(i32);
711 /// impl fmt::Binary for Length {
712 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
713 /// let val = self.0;
715 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
719 /// let l = Length(107);
721 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
724 /// format!("l as binary is: {:#032b}", l),
725 /// "l as binary is: 0b000000000000000000000001101011"
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")]
736 /// Formats the value using the given formatter.
737 #[stable(feature = "rust1", since = "1.0.0")]
738 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
743 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
746 /// For primitive signed integers (`i8` to `i128`, and `isize`),
747 /// negative values are formatted as the two’s complement representation.
749 /// The alternate flag, `#`, adds a `0x` in front of the output.
751 /// For more information on formatters, see [the module-level documentation][module].
753 /// [module]: ../../std/fmt/index.html
757 /// Basic usage with `i32`:
760 /// let x = 42; // 42 is '2a' in hex
762 /// assert_eq!(format!("{:x}", x), "2a");
763 /// assert_eq!(format!("{:#x}", x), "0x2a");
765 /// assert_eq!(format!("{:x}", -16), "fffffff0");
768 /// Implementing `LowerHex` on a type:
773 /// struct Length(i32);
775 /// impl fmt::LowerHex for Length {
776 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
777 /// let val = self.0;
779 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
783 /// let l = Length(9);
785 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
787 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
789 #[stable(feature = "rust1", since = "1.0.0")]
791 /// Formats the value using the given formatter.
792 #[stable(feature = "rust1", since = "1.0.0")]
793 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
798 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
801 /// For primitive signed integers (`i8` to `i128`, and `isize`),
802 /// negative values are formatted as the two’s complement representation.
804 /// The alternate flag, `#`, adds a `0x` in front of the output.
806 /// For more information on formatters, see [the module-level documentation][module].
808 /// [module]: ../../std/fmt/index.html
812 /// Basic usage with `i32`:
815 /// let x = 42; // 42 is '2A' in hex
817 /// assert_eq!(format!("{:X}", x), "2A");
818 /// assert_eq!(format!("{:#X}", x), "0x2A");
820 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
823 /// Implementing `UpperHex` on a type:
828 /// struct Length(i32);
830 /// impl fmt::UpperHex for Length {
831 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
832 /// let val = self.0;
834 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
838 /// let l = Length(i32::max_value());
840 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
842 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
844 #[stable(feature = "rust1", since = "1.0.0")]
846 /// Formats the value using the given formatter.
847 #[stable(feature = "rust1", since = "1.0.0")]
848 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
853 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
856 /// For more information on formatters, see [the module-level documentation][module].
858 /// [module]: ../../std/fmt/index.html
862 /// Basic usage with `&i32`:
867 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
870 /// Implementing `Pointer` on a type:
875 /// struct Length(i32);
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
881 /// let ptr = self as *const Self;
882 /// fmt::Pointer::fmt(&ptr, f)
886 /// let l = Length(42);
888 /// println!("l is in memory here: {:p}", l);
890 /// let l_ptr = format!("{:018p}", l);
891 /// assert_eq!(l_ptr.len(), 18);
892 /// assert_eq!(&l_ptr[..2], "0x");
894 #[stable(feature = "rust1", since = "1.0.0")]
896 /// Formats the value using the given formatter.
897 #[stable(feature = "rust1", since = "1.0.0")]
898 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
903 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
905 /// For more information on formatters, see [the module-level documentation][module].
907 /// [module]: ../../std/fmt/index.html
911 /// Basic usage with `f64`:
914 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
916 /// assert_eq!(format!("{:e}", x), "4.2e1");
919 /// Implementing `LowerExp` on a type:
924 /// struct Length(i32);
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
933 /// let l = Length(100);
936 /// format!("l in scientific notation is: {:e}", l),
937 /// "l in scientific notation is: 1e2"
941 /// format!("l in scientific notation is: {:05e}", l),
942 /// "l in scientific notation is: 001e2"
945 #[stable(feature = "rust1", since = "1.0.0")]
947 /// Formats the value using the given formatter.
948 #[stable(feature = "rust1", since = "1.0.0")]
949 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
954 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
956 /// For more information on formatters, see [the module-level documentation][module].
958 /// [module]: ../../std/fmt/index.html
962 /// Basic usage with `f64`:
965 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
967 /// assert_eq!(format!("{:E}", x), "4.2E1");
970 /// Implementing `UpperExp` on a type:
975 /// struct Length(i32);
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
984 /// let l = Length(100);
987 /// format!("l in scientific notation is: {:E}", l),
988 /// "l in scientific notation is: 1E2"
992 /// format!("l in scientific notation is: {:05E}", l),
993 /// "l in scientific notation is: 001E2"
996 #[stable(feature = "rust1", since = "1.0.0")]
998 /// Formats the value using the given formatter.
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1003 /// The `write` function takes an output stream, and an `Arguments` struct
1004 /// that can be precompiled with the `format_args!` macro.
1006 /// The arguments will be formatted according to the specified format string
1007 /// into the output stream provided.
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!");
1022 /// Please note that using [`write!`] might be preferable. Example:
1025 /// use std::fmt::Write;
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!");
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 {
1041 align: rt::v1::Alignment::Unknown,
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)?;
1057 // Every spec has a corresponding argument that is preceded by
1059 for (arg, piece) in fmt.iter().zip(args.pieces.iter()) {
1060 formatter.buf.write_str(*piece)?;
1061 run(&mut formatter, arg, &args.args)?;
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)?;
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);
1082 // Extract the correct argument
1086 match arg.position {
1087 rt::v1::Position::At(i) => args[i],
1090 #[cfg(not(bootstrap))]
1096 // Then actually do some printing
1097 (value.formatter)(value.value, fmt)
1100 fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1102 rt::v1::Count::Is(n) => Some(n),
1103 rt::v1::Count::Implied => None,
1104 rt::v1::Count::Param(i) => args[i].as_usize(),
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 {
1116 fn new(fill: char, padding: usize) -> PostPadding {
1117 PostPadding { fill, padding }
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)?;
1129 impl<'a> Formatter<'a> {
1130 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1133 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1136 // We want to change this
1137 buf: wrap(self.buf),
1139 // And preserve these
1144 precision: self.precision,
1148 // Helper methods used for padding and processing formatting arguments that
1149 // all formatting traits can use.
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.
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
1162 /// This function will correctly account for the flags provided as well as
1163 /// the minimum width. It will not take precision into account.
1170 /// struct Foo { nb: i32 };
1173 /// fn new(nb: i32) -> Foo {
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();
1185 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
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");
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();
1198 let mut sign = None;
1199 if !is_nonnegative {
1202 } else if self.sign_plus() {
1207 let prefix = if self.alternate() {
1208 width += prefix.chars().count();
1214 // Writes the sign if it exists, and then the prefix if it was requested
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)?;
1220 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1223 // The `width` field is more of a `min-width` parameter at this point.
1225 // If there's no minimum length requirements then we can just
1228 write_prefix(self, sign, prefix)?;
1229 self.buf.write_str(buf)
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)
1237 // The sign and prefix goes before the padding if the fill character
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;
1250 // Otherwise, the sign and prefix goes after the padding
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)
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:
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
1270 /// Notably this function ignores the `flag` parameters.
1279 /// impl fmt::Display for Foo {
1280 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1281 /// formatter.pad("Foo")
1285 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1286 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
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);
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
1305 s.get(..i).unwrap_or(&s)
1312 // The `width` field is more of a `min-width` parameter at this point.
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.
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)
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
1337 default: rt::v1::Alignment,
1338 ) -> result::Result<PostPadding, Error> {
1339 let align = match self.align {
1340 rt::v1::Alignment::Unknown => default,
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),
1350 for _ in 0..pre_pad {
1351 self.buf.write_char(self.fill)?;
1354 Ok(PostPadding::new(self.fill, post_pad))
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)?;
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;
1378 self.align = rt::v1::Alignment::Right;
1381 // remaining parts go through the ordinary padding process.
1382 let len = formatted.len();
1383 let ret = if width <= len {
1385 self.write_formatted_parts(&formatted)
1387 let post_padding = self.padding(width - len, align)?;
1388 self.write_formatted_parts(&formatted)?;
1389 post_padding.write(self.buf)
1391 self.fill = old_fill;
1392 self.align = old_align;
1395 // this is the common case and we take a shortcut
1396 self.write_formatted_parts(formatted)
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) })
1405 if !formatted.sign.is_empty() {
1406 write_bytes(self.buf, formatted.sign)?;
1408 for part in formatted.parts {
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();
1418 self.buf.write_str(&ZEROES[..nzeroes])?;
1421 flt2dec::Part::Num(mut v) => {
1423 let len = part.len();
1424 for c in s[..len].iter_mut().rev() {
1425 *c = b'0' + (v % 10) as u8;
1428 write_bytes(self.buf, &s[..len])?;
1430 flt2dec::Part::Copy(buf) => {
1431 write_bytes(self.buf, buf)?;
1438 /// Writes some data to the underlying buffer contained within this
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")
1456 /// assert_eq!(&format!("{}", Foo), "Foo");
1457 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 pub fn write_str(&mut self, data: &str) -> Result {
1461 self.buf.write_str(data)
1464 /// Writes some formatted information into this instance.
1471 /// struct Foo(i32);
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))
1479 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1480 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1484 write(self.buf, fmt)
1487 /// Flags for formatting
1488 #[stable(feature = "rust1", since = "1.0.0")]
1491 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1492 or `sign_aware_zero_pad` methods instead"
1494 pub fn flags(&self) -> u32 {
1498 /// Character used as 'fill' whenever there is alignment.
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)?;
1516 /// write!(formatter, "{}", c)
1521 /// // We set alignment to the left with ">".
1522 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1523 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1525 #[stable(feature = "fmt_flags", since = "1.5.0")]
1526 pub fn fill(&self) -> char {
1530 /// Flag indicating what form of alignment was requested.
1535 /// extern crate core;
1537 /// use std::fmt::{self, Alignment};
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() {
1545 /// Alignment::Left => "left",
1546 /// Alignment::Right => "right",
1547 /// Alignment::Center => "center",
1552 /// write!(formatter, "{}", s)
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");
1561 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1562 pub fn align(&self) -> Option<Alignment> {
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,
1571 /// Optionally specified integer width that the output should be.
1578 /// struct Foo(i32);
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)
1586 /// // Otherwise we do nothing special
1587 /// write!(formatter, "Foo({})", self.0)
1592 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1593 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1595 #[stable(feature = "fmt_flags", since = "1.5.0")]
1596 pub fn width(&self) -> Option<usize> {
1600 /// Optionally specified precision for numeric types.
1607 /// struct Foo(f32);
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)
1615 /// // Otherwise we default to 2.
1616 /// write!(formatter, "Foo({:.2})", self.0)
1621 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1622 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1624 #[stable(feature = "fmt_flags", since = "1.5.0")]
1625 pub fn precision(&self) -> Option<usize> {
1629 /// Determines if the `+` flag was specified.
1636 /// struct Foo(i32);
1638 /// impl fmt::Display for Foo {
1639 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1640 /// if formatter.sign_plus() {
1641 /// write!(formatter,
1643 /// if self.0 < 0 { '-' } else { '+' },
1646 /// write!(formatter, "Foo({})", self.0)
1651 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1652 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
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
1659 /// Determines if the `-` flag was specified.
1666 /// struct Foo(i32);
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)
1674 /// write!(formatter, "Foo({})", self.0)
1679 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1680 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
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
1687 /// Determines if the `#` flag was specified.
1694 /// struct Foo(i32);
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)
1701 /// write!(formatter, "{}", self.0)
1706 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1707 /// assert_eq!(&format!("{}", Foo(23)), "23");
1709 #[stable(feature = "fmt_flags", since = "1.5.0")]
1710 pub fn alternate(&self) -> bool {
1711 self.flags & (1 << FlagV1::Alternate as u32) != 0
1714 /// Determines if the `0` flag was specified.
1721 /// struct Foo(i32);
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)
1732 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
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
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
1745 fn debug_upper_hex(&self) -> bool {
1746 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1749 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1750 /// [`fmt::Debug`] implementations for structs.
1752 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1753 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1759 /// use std::net::Ipv4Addr;
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))
1778 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1779 /// format!("{:?}", Foo {
1781 /// baz: "Hello World".to_string(),
1782 /// addr: Ipv4Addr::new(127, 0, 0, 1),
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)
1791 /// Creates a `DebugTuple` builder designed to assist with creation of
1792 /// `fmt::Debug` implementations for tuple structs.
1798 /// use std::marker::PhantomData;
1800 /// struct Foo<T>(i32, String, PhantomData<T>);
1802 /// impl<T> fmt::Debug for Foo<T> {
1803 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1804 /// fmt.debug_tuple("Foo")
1807 /// .field(&format_args!("_"))
1813 /// "Foo(10, \"Hello\", _)",
1814 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
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)
1822 /// Creates a `DebugList` builder designed to assist with creation of
1823 /// `fmt::Debug` implementations for list-like structures.
1830 /// struct Foo(Vec<i32>);
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()
1838 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
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)
1845 /// Creates a `DebugSet` builder designed to assist with creation of
1846 /// `fmt::Debug` implementations for set-like structures.
1853 /// struct Foo(Vec<i32>);
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()
1861 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
1864 /// [`format_args!`]: ../../std/macro.format_args.html
1866 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1867 /// to build a list of match arms:
1872 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1873 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1875 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1877 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
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)
1886 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1888 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1890 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1892 /// .entries(self.0.iter().map(Arm))
1893 /// .entry(&Arm(&(format_args!("_"), &self.1)))
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)
1903 /// Creates a `DebugMap` builder designed to assist with creation of
1904 /// `fmt::Debug` implementations for map-like structures.
1911 /// struct Foo(Vec<(String, i32)>);
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()
1920 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1921 /// r#"{"A": 10, "B": 11}"#
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)
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)
1936 fn write_char(&mut self, c: char) -> Result {
1937 self.buf.write_char(c)
1940 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
1941 write(self.buf, args)
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)
1952 // Implementations of the core formatting traits
1954 macro_rules! fmt_refs {
1955 ($($tr:ident),*) => {
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) }
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) }
1969 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1971 #[unstable(feature = "never_type", issue = "35121")]
1973 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
1978 #[unstable(feature = "never_type", issue = "35121")]
1979 impl Display for ! {
1980 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 impl Debug for bool {
1988 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1989 Display::fmt(self, f)
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)
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl Debug for str {
2002 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
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
2009 f.write_str(&self[from..i])?;
2013 from = i + c.len_utf8();
2016 f.write_str(&self[from..])?;
2021 #[stable(feature = "rust1", since = "1.0.0")]
2022 impl Display for str {
2023 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
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() {
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() {
2045 f.pad(self.encode_utf8(&mut [0; 4]))
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;
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
2061 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2063 if f.width.is_none() {
2064 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2067 f.flags |= 1 << (FlagV1::Alternate as u32);
2069 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2071 f.width = old_width;
2072 f.flags = old_flags;
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)
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)
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)
2099 // Implementation of Display/Debug for various core types
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)
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)
2115 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2118 macro_rules! tuple {
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;
2128 builder.field(&$name);
2134 peel! { $($name,)+ }
2138 macro_rules! last_type {
2139 ($a:ident,) => { $a };
2140 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2143 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
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()
2152 #[stable(feature = "rust1", since = "1.0.0")]
2155 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
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")
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()
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(),
2179 // The RefCell is mutably borrowed so we can't look at its value
2180 // here. Show a placeholder instead.
2181 struct BorrowedPlaceholder;
2183 impl Debug for BorrowedPlaceholder {
2184 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2185 f.write_str("<borrowed>")
2189 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
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)
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)
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 {
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.