1 //! Utilities for formatting and printing strings.
3 #![stable(feature = "rust1", since = "1.0.0")]
5 use crate::cell::{UnsafeCell, Cell, RefCell, Ref, RefMut};
6 use crate::marker::PhantomData;
8 use crate::num::flt2dec;
18 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
19 /// Possible alignments returned by `Formatter::align`
22 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
23 /// Indication that contents should be left-aligned.
25 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
26 /// Indication that contents should be right-aligned.
28 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
29 /// Indication that contents should be center-aligned.
33 #[stable(feature = "debug_builders", since = "1.2.0")]
34 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
36 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
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 /// println!("{}", pythagorean_triple);
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 slice of bytes into this writer, returning whether the write
114 /// This method can only succeed if the entire byte 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),
236 curarg: slice::Iter<'a, ArgumentV1<'a>>,
237 args: &'a [ArgumentV1<'a>],
240 // NB. Argument is essentially an optimized partially applied formatting function,
241 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
245 /// Erases all oibits, because `Void` erases the type of the object that
246 /// will be used to produce formatted output. Since we do not know what
247 /// oibits the real types have (and they can have any or none), we need to
248 /// take the most conservative approach and forbid all oibits.
250 /// It was added after #45197 showed that one could share a `!Sync`
251 /// object across threads by passing it into `format_args!`.
252 _oibit_remover: PhantomData<*mut dyn Fn()>,
255 /// This struct represents the generic "argument" which is taken by the Xprintf
256 /// family of functions. It contains a function to format the given value. At
257 /// compile time it is ensured that the function and the value have the correct
258 /// types, and then this struct is used to canonicalize arguments to one type.
259 #[derive(Copy, Clone)]
260 #[allow(missing_debug_implementations)]
261 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
264 pub struct ArgumentV1<'a> {
266 formatter: fn(&Void, &mut Formatter<'_>) -> Result,
269 impl<'a> ArgumentV1<'a> {
271 fn show_usize(x: &usize, f: &mut Formatter<'_>) -> Result {
276 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
278 pub fn new<'b, T>(x: &'b T,
279 f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
282 formatter: mem::transmute(f),
283 value: mem::transmute(x)
289 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
291 pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
292 ArgumentV1::new(x, ArgumentV1::show_usize)
295 fn as_usize(&self) -> Option<usize> {
296 if self.formatter as usize == ArgumentV1::show_usize as usize {
297 Some(unsafe { *(self.value as *const _ as *const usize) })
304 // flags available in the v1 format of format_args
305 #[derive(Copy, Clone)]
306 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, DebugLowerHex, DebugUpperHex }
308 impl<'a> Arguments<'a> {
309 /// When using the format_args!() macro, this function is used to generate the
310 /// Arguments structure.
311 #[doc(hidden)] #[inline]
312 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
314 pub fn new_v1(pieces: &'a [&'a str],
315 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
323 /// This function is used to specify nonstandard formatting parameters.
324 /// The `pieces` array must be at least as long as `fmt` to construct
325 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
326 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
327 /// created with `argumentusize`. However, failing to do so doesn't cause
328 /// unsafety, but will ignore invalid .
329 #[doc(hidden)] #[inline]
330 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
332 pub fn new_v1_formatted(pieces: &'a [&'a str],
333 args: &'a [ArgumentV1<'a>],
334 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
342 /// Estimates the length of the formatted text.
344 /// This is intended to be used for setting initial `String` capacity
345 /// when using `format!`. Note: this is neither the lower nor upper bound.
346 #[doc(hidden)] #[inline]
347 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
349 pub fn estimated_capacity(&self) -> usize {
350 let pieces_length: usize = self.pieces.iter()
351 .map(|x| x.len()).sum();
353 if self.args.is_empty() {
355 } else if self.pieces[0] == "" && pieces_length < 16 {
356 // If the format string starts with an argument,
357 // don't preallocate anything, unless length
358 // of pieces is significant.
361 // There are some arguments, so any additional push
362 // will reallocate the string. To avoid that,
363 // we're "pre-doubling" the capacity here.
364 pieces_length.checked_mul(2).unwrap_or(0)
369 /// This structure represents a safely precompiled version of a format string
370 /// and its arguments. This cannot be generated at runtime because it cannot
371 /// safely be done, so no constructors are given and the fields are private
372 /// to prevent modification.
374 /// The [`format_args!`] macro will safely create an instance of this structure.
375 /// The macro validates the format string at compile-time so usage of the
376 /// [`write`] and [`format`] functions can be safely performed.
378 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
379 /// and `Display` contexts as seen below. The example also shows that `Debug`
380 /// and `Display` format to the same thing: the interpolated format string
381 /// in `format_args!`.
384 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
385 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
386 /// assert_eq!("1 foo 2", display);
387 /// assert_eq!(display, debug);
390 /// [`format_args!`]: ../../std/macro.format_args.html
391 /// [`format`]: ../../std/fmt/fn.format.html
392 /// [`write`]: ../../std/fmt/fn.write.html
393 #[stable(feature = "rust1", since = "1.0.0")]
394 #[derive(Copy, Clone)]
395 pub struct Arguments<'a> {
396 // Format string pieces to print.
397 pieces: &'a [&'a str],
399 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
400 fmt: Option<&'a [rt::v1::Argument]>,
402 // Dynamic arguments for interpolation, to be interleaved with string
403 // pieces. (Every argument is preceded by a string piece.)
404 args: &'a [ArgumentV1<'a>],
407 #[stable(feature = "rust1", since = "1.0.0")]
408 impl Debug for Arguments<'_> {
409 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
410 Display::fmt(self, fmt)
414 #[stable(feature = "rust1", since = "1.0.0")]
415 impl Display for Arguments<'_> {
416 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
417 write(fmt.buf, *self)
423 /// `Debug` should format the output in a programmer-facing, debugging context.
425 /// Generally speaking, you should just `derive` a `Debug` implementation.
427 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
429 /// For more information on formatters, see [the module-level documentation][module].
431 /// [module]: ../../std/fmt/index.html
433 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
434 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
435 /// comma-separated list of each field's name and `Debug` value, then `}`. For
436 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
437 /// `Debug` values of the fields, then `)`.
441 /// Deriving an implementation:
450 /// let origin = Point { x: 0, y: 0 };
452 /// println!("The origin is: {:?}", origin);
455 /// Manually implementing:
465 /// impl fmt::Debug for Point {
466 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
467 /// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
471 /// let origin = Point { x: 0, y: 0 };
473 /// println!("The origin is: {:?}", origin);
479 /// The origin is: Point { x: 0, y: 0 }
482 /// There are a number of `debug_*` methods on [`Formatter`] to help you with manual
483 /// implementations, such as [`debug_struct`][debug_struct].
485 /// `Debug` implementations using either `derive` or the debug builder API
486 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
488 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
489 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
491 /// Pretty-printing with `#?`:
500 /// let origin = Point { x: 0, y: 0 };
502 /// println!("The origin is: {:#?}", origin);
508 /// The origin is: Point {
513 #[stable(feature = "rust1", since = "1.0.0")]
514 #[rustc_on_unimplemented(
515 on(crate_local, label="`{Self}` cannot be formatted using `{{:?}}`",
516 note="add `#[derive(Debug)]` or manually implement `{Debug}`"),
517 message="`{Self}` doesn't implement `{Debug}`",
518 label="`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`",
520 #[doc(alias = "{:?}")]
521 #[lang = "debug_trait"]
523 /// Formats the value using the given formatter.
530 /// struct Position {
535 /// impl fmt::Debug for Position {
536 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537 /// write!(f, "({:?}, {:?})", self.longitude, self.latitude)
541 /// assert_eq!("(1.987, 2.983)".to_owned(),
542 /// format!("{:?}", Position { longitude: 1.987, latitude: 2.983, }));
544 #[stable(feature = "rust1", since = "1.0.0")]
545 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
548 /// Format trait for an empty format, `{}`.
550 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
551 /// output, and so cannot be derived.
553 /// [debug]: trait.Debug.html
555 /// For more information on formatters, see [the module-level documentation][module].
557 /// [module]: ../../std/fmt/index.html
561 /// Implementing `Display` on a type:
571 /// impl fmt::Display for Point {
572 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573 /// write!(f, "({}, {})", self.x, self.y)
577 /// let origin = Point { x: 0, y: 0 };
579 /// println!("The origin is: {}", origin);
581 #[rustc_on_unimplemented(
583 _Self="std::path::Path",
584 label="`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
585 note="call `.display()` or `.to_string_lossy()` to safely print paths, \
586 as they may contain non-Unicode data"
588 message="`{Self}` doesn't implement `{Display}`",
589 label="`{Self}` cannot be formatted with the default formatter",
590 note="in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead",
593 #[stable(feature = "rust1", since = "1.0.0")]
595 /// Formats the value using the given formatter.
602 /// struct Position {
607 /// impl fmt::Display for Position {
608 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
609 /// write!(f, "({}, {})", self.longitude, self.latitude)
613 /// assert_eq!("(1.987, 2.983)".to_owned(),
614 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
616 #[stable(feature = "rust1", since = "1.0.0")]
617 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
622 /// The `Octal` trait should format its output as a number in base-8.
624 /// For primitive signed integers (`i8` to `i128`, and `isize`),
625 /// negative values are formatted as the two’s complement representation.
627 /// The alternate flag, `#`, adds a `0o` in front of the output.
629 /// For more information on formatters, see [the module-level documentation][module].
631 /// [module]: ../../std/fmt/index.html
635 /// Basic usage with `i32`:
638 /// let x = 42; // 42 is '52' in octal
640 /// assert_eq!(format!("{:o}", x), "52");
641 /// assert_eq!(format!("{:#o}", x), "0o52");
643 /// assert_eq!(format!("{:o}", -16), "37777777760");
646 /// Implementing `Octal` on a type:
651 /// struct Length(i32);
653 /// impl fmt::Octal for Length {
654 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 /// let val = self.0;
657 /// write!(f, "{:o}", val) // delegate to i32's implementation
661 /// let l = Length(9);
663 /// println!("l as octal is: {:o}", l);
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 /// write!(f, "{:b}", val) // delegate to i32's implementation
711 /// let l = Length(107);
713 /// println!("l as binary is: {:b}", l);
716 /// [module]: ../../std/fmt/index.html
717 /// [`i8`]: ../../std/primitive.i8.html
718 /// [`i128`]: ../../std/primitive.i128.html
719 /// [`isize`]: ../../std/primitive.isize.html
720 /// [`i32`]: ../../std/primitive.i32.html
721 #[stable(feature = "rust1", since = "1.0.0")]
723 /// Formats the value using the given formatter.
724 #[stable(feature = "rust1", since = "1.0.0")]
725 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
730 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
733 /// For primitive signed integers (`i8` to `i128`, and `isize`),
734 /// negative values are formatted as the two’s complement representation.
736 /// The alternate flag, `#`, adds a `0x` in front of the output.
738 /// For more information on formatters, see [the module-level documentation][module].
740 /// [module]: ../../std/fmt/index.html
744 /// Basic usage with `i32`:
747 /// let x = 42; // 42 is '2a' in hex
749 /// assert_eq!(format!("{:x}", x), "2a");
750 /// assert_eq!(format!("{:#x}", x), "0x2a");
752 /// assert_eq!(format!("{:x}", -16), "fffffff0");
755 /// Implementing `LowerHex` on a type:
760 /// struct Length(i32);
762 /// impl fmt::LowerHex for Length {
763 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
764 /// let val = self.0;
766 /// write!(f, "{:x}", val) // delegate to i32's implementation
770 /// let l = Length(9);
772 /// println!("l as hex is: {:x}", l);
774 #[stable(feature = "rust1", since = "1.0.0")]
776 /// Formats the value using the given formatter.
777 #[stable(feature = "rust1", since = "1.0.0")]
778 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
783 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
786 /// For primitive signed integers (`i8` to `i128`, and `isize`),
787 /// negative values are formatted as the two’s complement representation.
789 /// The alternate flag, `#`, adds a `0x` in front of the output.
791 /// For more information on formatters, see [the module-level documentation][module].
793 /// [module]: ../../std/fmt/index.html
797 /// Basic usage with `i32`:
800 /// let x = 42; // 42 is '2A' in hex
802 /// assert_eq!(format!("{:X}", x), "2A");
803 /// assert_eq!(format!("{:#X}", x), "0x2A");
805 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
808 /// Implementing `UpperHex` on a type:
813 /// struct Length(i32);
815 /// impl fmt::UpperHex for Length {
816 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
817 /// let val = self.0;
819 /// write!(f, "{:X}", val) // delegate to i32's implementation
823 /// let l = Length(9);
825 /// println!("l as hex is: {:X}", l);
827 #[stable(feature = "rust1", since = "1.0.0")]
829 /// Formats the value using the given formatter.
830 #[stable(feature = "rust1", since = "1.0.0")]
831 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
836 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
839 /// For more information on formatters, see [the module-level documentation][module].
841 /// [module]: ../../std/fmt/index.html
845 /// Basic usage with `&i32`:
850 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
853 /// Implementing `Pointer` on a type:
858 /// struct Length(i32);
860 /// impl fmt::Pointer for Length {
861 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
862 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
864 /// write!(f, "{:p}", self as *const Length)
868 /// let l = Length(42);
870 /// println!("l is in memory here: {:p}", l);
872 #[stable(feature = "rust1", since = "1.0.0")]
874 /// Formats the value using the given formatter.
875 #[stable(feature = "rust1", since = "1.0.0")]
876 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
881 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
883 /// For more information on formatters, see [the module-level documentation][module].
885 /// [module]: ../../std/fmt/index.html
889 /// Basic usage with `i32`:
892 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
894 /// assert_eq!(format!("{:e}", x), "4.2e1");
897 /// Implementing `LowerExp` on a type:
902 /// struct Length(i32);
904 /// impl fmt::LowerExp for Length {
905 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
906 /// let val = self.0;
907 /// write!(f, "{}e1", val / 10)
911 /// let l = Length(100);
913 /// println!("l in scientific notation is: {:e}", l);
915 #[stable(feature = "rust1", since = "1.0.0")]
917 /// Formats the value using the given formatter.
918 #[stable(feature = "rust1", since = "1.0.0")]
919 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
924 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
926 /// For more information on formatters, see [the module-level documentation][module].
928 /// [module]: ../../std/fmt/index.html
932 /// Basic usage with `f32`:
935 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
937 /// assert_eq!(format!("{:E}", x), "4.2E1");
940 /// Implementing `UpperExp` on a type:
945 /// struct Length(i32);
947 /// impl fmt::UpperExp for Length {
948 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
949 /// let val = self.0;
950 /// write!(f, "{}E1", val / 10)
954 /// let l = Length(100);
956 /// println!("l in scientific notation is: {:E}", l);
958 #[stable(feature = "rust1", since = "1.0.0")]
960 /// Formats the value using the given formatter.
961 #[stable(feature = "rust1", since = "1.0.0")]
962 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
965 /// The `write` function takes an output stream, and an `Arguments` struct
966 /// that can be precompiled with the `format_args!` macro.
968 /// The arguments will be formatted according to the specified format string
969 /// into the output stream provided.
978 /// let mut output = String::new();
979 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
980 /// .expect("Error occurred while trying to write in String");
981 /// assert_eq!(output, "Hello world!");
984 /// Please note that using [`write!`] might be preferable. Example:
987 /// use std::fmt::Write;
989 /// let mut output = String::new();
990 /// write!(&mut output, "Hello {}!", "world")
991 /// .expect("Error occurred while trying to write in String");
992 /// assert_eq!(output, "Hello world!");
995 /// [`write!`]: ../../std/macro.write.html
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
998 let mut formatter = Formatter {
1003 align: rt::v1::Alignment::Unknown,
1006 curarg: args.args.iter(),
1013 // We can use default formatting parameters for all arguments.
1014 for (arg, piece) in args.args.iter().zip(args.pieces.iter()) {
1015 formatter.buf.write_str(*piece)?;
1016 (arg.formatter)(arg.value, &mut formatter)?;
1021 // Every spec has a corresponding argument that is preceded by
1023 for (arg, piece) in fmt.iter().zip(args.pieces.iter()) {
1024 formatter.buf.write_str(*piece)?;
1025 formatter.run(arg)?;
1031 // There can be only one trailing string piece left.
1032 if let Some(piece) = args.pieces.get(idx) {
1033 formatter.buf.write_str(*piece)?;
1039 /// Padding after the end of something. Returned by `Formatter::padding`.
1040 #[must_use = "don't forget to write the post padding"]
1041 struct PostPadding {
1047 fn new(fill: char, padding: usize) -> PostPadding {
1048 PostPadding { fill, padding }
1051 /// Write this post padding.
1052 fn write(self, buf: &mut dyn Write) -> Result {
1053 for _ in 0..self.padding {
1054 buf.write_char(self.fill)?;
1060 impl<'a> Formatter<'a> {
1061 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1062 where 'b: 'c, F: FnOnce(&'b mut (dyn Write+'b)) -> &'c mut (dyn Write+'c)
1065 // We want to change this
1066 buf: wrap(self.buf),
1068 // And preserve these
1073 precision: self.precision,
1075 // These only exist in the struct for the `run` method,
1076 // which won’t be used together with this method.
1077 curarg: self.curarg.clone(),
1082 // First up is the collection of functions used to execute a format string
1083 // at runtime. This consumes all of the compile-time statics generated by
1084 // the format! syntax extension.
1085 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1086 // Fill in the format parameters into the formatter
1087 self.fill = arg.format.fill;
1088 self.align = arg.format.align;
1089 self.flags = arg.format.flags;
1090 self.width = self.getcount(&arg.format.width);
1091 self.precision = self.getcount(&arg.format.precision);
1093 // Extract the correct argument
1094 let value = match arg.position {
1095 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1096 rt::v1::Position::At(i) => self.args[i],
1099 // Then actually do some printing
1100 (value.formatter)(value.value, self)
1103 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1105 rt::v1::Count::Is(n) => Some(n),
1106 rt::v1::Count::Implied => None,
1107 rt::v1::Count::Param(i) => {
1108 self.args[i].as_usize()
1110 rt::v1::Count::NextParam => {
1111 self.curarg.next()?.as_usize()
1116 // Helper methods used for padding and processing formatting arguments that
1117 // all formatting traits can use.
1119 /// Performs the correct padding for an integer which has already been
1120 /// emitted into a str. The str should *not* contain the sign for the
1121 /// integer, that will be added by this method.
1125 /// * is_nonnegative - whether the original integer was either positive or zero.
1126 /// * prefix - if the '#' character (Alternate) is provided, this
1127 /// is the prefix to put in front of the number.
1128 /// * buf - the byte array that the number has been formatted into
1130 /// This function will correctly account for the flags provided as well as
1131 /// the minimum width. It will not take precision into account.
1138 /// struct Foo { nb: i32 };
1141 /// fn new(nb: i32) -> Foo {
1148 /// impl fmt::Display for Foo {
1149 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1150 /// // We need to remove "-" from the number output.
1151 /// let tmp = self.nb.abs().to_string();
1153 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1157 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1158 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1159 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1160 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 pub fn pad_integral(&mut self,
1164 is_nonnegative: bool,
1168 let mut width = buf.len();
1170 let mut sign = None;
1171 if !is_nonnegative {
1172 sign = Some('-'); width += 1;
1173 } else if self.sign_plus() {
1174 sign = Some('+'); width += 1;
1177 let prefix = if self.alternate() {
1178 width += prefix.chars().count();
1184 // Writes the sign if it exists, and then the prefix if it was requested
1186 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1187 if let Some(c) = sign {
1188 f.buf.write_char(c)?;
1190 if let Some(prefix) = prefix {
1191 f.buf.write_str(prefix)
1197 // The `width` field is more of a `min-width` parameter at this point.
1199 // If there's no minimum length requirements then we can just
1202 write_prefix(self, sign, prefix)?;
1203 self.buf.write_str(buf)
1205 // Check if we're over the minimum width, if so then we can also
1206 // just write the bytes.
1207 Some(min) if width >= min => {
1208 write_prefix(self, sign, prefix)?;
1209 self.buf.write_str(buf)
1211 // The sign and prefix goes before the padding if the fill character
1213 Some(min) if self.sign_aware_zero_pad() => {
1215 self.align = rt::v1::Alignment::Right;
1216 write_prefix(self, sign, prefix)?;
1217 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1218 self.buf.write_str(buf)?;
1219 post_padding.write(self.buf)
1221 // Otherwise, the sign and prefix goes after the padding
1223 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1224 write_prefix(self, sign, prefix)?;
1225 self.buf.write_str(buf)?;
1226 post_padding.write(self.buf)
1231 /// This function takes a string slice and emits it to the internal buffer
1232 /// after applying the relevant formatting flags specified. The flags
1233 /// recognized for generic strings are:
1235 /// * width - the minimum width of what to emit
1236 /// * fill/align - what to emit and where to emit it if the string
1237 /// provided needs to be padded
1238 /// * precision - the maximum length to emit, the string is truncated if it
1239 /// is longer than this length
1241 /// Notably this function ignores the `flag` parameters.
1250 /// impl fmt::Display for Foo {
1251 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1252 /// formatter.pad("Foo")
1256 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1257 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1259 #[stable(feature = "rust1", since = "1.0.0")]
1260 pub fn pad(&mut self, s: &str) -> Result {
1261 // Make sure there's a fast path up front
1262 if self.width.is_none() && self.precision.is_none() {
1263 return self.buf.write_str(s);
1265 // The `precision` field can be interpreted as a `max-width` for the
1266 // string being formatted.
1267 let s = if let Some(max) = self.precision {
1268 // If our string is longer that the precision, then we must have
1269 // truncation. However other flags like `fill`, `width` and `align`
1270 // must act as always.
1271 if let Some((i, _)) = s.char_indices().nth(max) {
1272 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1273 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1274 // `unsafe` and otherwise don't emit any panic-related code
1276 s.get(..i).unwrap_or(&s)
1283 // The `width` field is more of a `min-width` parameter at this point.
1285 // If we're under the maximum length, and there's no minimum length
1286 // requirements, then we can just emit the string
1287 None => self.buf.write_str(s),
1288 // If we're under the maximum width, check if we're over the minimum
1289 // width, if so it's as easy as just emitting the string.
1290 Some(width) if s.chars().count() >= width => {
1291 self.buf.write_str(s)
1293 // If we're under both the maximum and the minimum width, then fill
1294 // up the minimum width with the specified string + some alignment.
1296 let align = rt::v1::Alignment::Left;
1297 let post_padding = self.padding(width - s.chars().count(), align)?;
1298 self.buf.write_str(s)?;
1299 post_padding.write(self.buf)
1304 /// Write the pre-padding and return the unwritten post-padding. Callers are
1305 /// responsible for ensuring post-padding is written after the thing that is
1310 default: rt::v1::Alignment
1311 ) -> result::Result<PostPadding, Error> {
1312 let align = match self.align {
1313 rt::v1::Alignment::Unknown => default,
1317 let (pre_pad, post_pad) = match align {
1318 rt::v1::Alignment::Left => (0, padding),
1319 rt::v1::Alignment::Right |
1320 rt::v1::Alignment::Unknown => (padding, 0),
1321 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1324 for _ in 0..pre_pad {
1325 self.buf.write_char(self.fill)?;
1328 Ok(PostPadding::new(self.fill, post_pad))
1331 /// Takes the formatted parts and applies the padding.
1332 /// Assumes that the caller already has rendered the parts with required precision,
1333 /// so that `self.precision` can be ignored.
1334 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted<'_>) -> Result {
1335 if let Some(mut width) = self.width {
1336 // for the sign-aware zero padding, we render the sign first and
1337 // behave as if we had no sign from the beginning.
1338 let mut formatted = formatted.clone();
1339 let old_fill = self.fill;
1340 let old_align = self.align;
1341 let mut align = old_align;
1342 if self.sign_aware_zero_pad() {
1343 // a sign always goes first
1344 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1345 self.buf.write_str(sign)?;
1347 // remove the sign from the formatted parts
1348 formatted.sign = b"";
1349 width = width.saturating_sub(sign.len());
1350 align = rt::v1::Alignment::Right;
1352 self.align = rt::v1::Alignment::Right;
1355 // remaining parts go through the ordinary padding process.
1356 let len = formatted.len();
1357 let ret = if width <= len { // no padding
1358 self.write_formatted_parts(&formatted)
1360 let post_padding = self.padding(width - len, align)?;
1361 self.write_formatted_parts(&formatted)?;
1362 post_padding.write(self.buf)
1364 self.fill = old_fill;
1365 self.align = old_align;
1368 // this is the common case and we take a shortcut
1369 self.write_formatted_parts(formatted)
1373 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted<'_>) -> Result {
1374 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1375 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1378 if !formatted.sign.is_empty() {
1379 write_bytes(self.buf, formatted.sign)?;
1381 for part in formatted.parts {
1383 flt2dec::Part::Zero(mut nzeroes) => {
1384 const ZEROES: &str = // 64 zeroes
1385 "0000000000000000000000000000000000000000000000000000000000000000";
1386 while nzeroes > ZEROES.len() {
1387 self.buf.write_str(ZEROES)?;
1388 nzeroes -= ZEROES.len();
1391 self.buf.write_str(&ZEROES[..nzeroes])?;
1394 flt2dec::Part::Num(mut v) => {
1396 let len = part.len();
1397 for c in s[..len].iter_mut().rev() {
1398 *c = b'0' + (v % 10) as u8;
1401 write_bytes(self.buf, &s[..len])?;
1403 flt2dec::Part::Copy(buf) => {
1404 write_bytes(self.buf, buf)?;
1411 /// Writes some data to the underlying buffer contained within this
1421 /// impl fmt::Display for Foo {
1422 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1423 /// formatter.write_str("Foo")
1424 /// // This is equivalent to:
1425 /// // write!(formatter, "Foo")
1429 /// assert_eq!(&format!("{}", Foo), "Foo");
1430 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 pub fn write_str(&mut self, data: &str) -> Result {
1434 self.buf.write_str(data)
1437 /// Writes some formatted information into this instance.
1444 /// struct Foo(i32);
1446 /// impl fmt::Display for Foo {
1447 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1448 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1452 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1453 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1457 write(self.buf, fmt)
1460 /// Flags for formatting
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 #[rustc_deprecated(since = "1.24.0",
1463 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1464 or `sign_aware_zero_pad` methods instead")]
1465 pub fn flags(&self) -> u32 { self.flags }
1467 /// Character used as 'fill' whenever there is alignment.
1476 /// impl fmt::Display for Foo {
1477 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1478 /// let c = formatter.fill();
1479 /// if let Some(width) = formatter.width() {
1480 /// for _ in 0..width {
1481 /// write!(formatter, "{}", c)?;
1485 /// write!(formatter, "{}", c)
1490 /// // We set alignment to the left with ">".
1491 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1492 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1494 #[stable(feature = "fmt_flags", since = "1.5.0")]
1495 pub fn fill(&self) -> char { self.fill }
1497 /// Flag indicating what form of alignment was requested.
1502 /// extern crate core;
1504 /// use std::fmt::{self, Alignment};
1508 /// impl fmt::Display for Foo {
1509 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1510 /// let s = if let Some(s) = formatter.align() {
1512 /// Alignment::Left => "left",
1513 /// Alignment::Right => "right",
1514 /// Alignment::Center => "center",
1519 /// write!(formatter, "{}", s)
1524 /// assert_eq!(&format!("{:<}", Foo), "left");
1525 /// assert_eq!(&format!("{:>}", Foo), "right");
1526 /// assert_eq!(&format!("{:^}", Foo), "center");
1527 /// assert_eq!(&format!("{}", Foo), "into the void");
1530 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1531 pub fn align(&self) -> Option<Alignment> {
1533 rt::v1::Alignment::Left => Some(Alignment::Left),
1534 rt::v1::Alignment::Right => Some(Alignment::Right),
1535 rt::v1::Alignment::Center => Some(Alignment::Center),
1536 rt::v1::Alignment::Unknown => None,
1540 /// Optionally specified integer width that the output should be.
1547 /// struct Foo(i32);
1549 /// impl fmt::Display for Foo {
1550 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1551 /// if let Some(width) = formatter.width() {
1552 /// // If we received a width, we use it
1553 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1555 /// // Otherwise we do nothing special
1556 /// write!(formatter, "Foo({})", self.0)
1561 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1562 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1564 #[stable(feature = "fmt_flags", since = "1.5.0")]
1565 pub fn width(&self) -> Option<usize> { self.width }
1567 /// Optionally specified precision for numeric types.
1574 /// struct Foo(f32);
1576 /// impl fmt::Display for Foo {
1577 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1578 /// if let Some(precision) = formatter.precision() {
1579 /// // If we received a precision, we use it.
1580 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1582 /// // Otherwise we default to 2.
1583 /// write!(formatter, "Foo({:.2})", self.0)
1588 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1589 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1591 #[stable(feature = "fmt_flags", since = "1.5.0")]
1592 pub fn precision(&self) -> Option<usize> { self.precision }
1594 /// Determines if the `+` flag was specified.
1601 /// struct Foo(i32);
1603 /// impl fmt::Display for Foo {
1604 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1605 /// if formatter.sign_plus() {
1606 /// write!(formatter,
1608 /// if self.0 < 0 { '-' } else { '+' },
1611 /// write!(formatter, "Foo({})", self.0)
1616 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1617 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1619 #[stable(feature = "fmt_flags", since = "1.5.0")]
1620 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1622 /// Determines if the `-` flag was specified.
1629 /// struct Foo(i32);
1631 /// impl fmt::Display for Foo {
1632 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1633 /// if formatter.sign_minus() {
1634 /// // You want a minus sign? Have one!
1635 /// write!(formatter, "-Foo({})", self.0)
1637 /// write!(formatter, "Foo({})", self.0)
1642 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1643 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1645 #[stable(feature = "fmt_flags", since = "1.5.0")]
1646 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1648 /// Determines if the `#` flag was specified.
1655 /// struct Foo(i32);
1657 /// impl fmt::Display for Foo {
1658 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1659 /// if formatter.alternate() {
1660 /// write!(formatter, "Foo({})", self.0)
1662 /// write!(formatter, "{}", self.0)
1667 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1668 /// assert_eq!(&format!("{}", Foo(23)), "23");
1670 #[stable(feature = "fmt_flags", since = "1.5.0")]
1671 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1673 /// Determines if the `0` flag was specified.
1680 /// struct Foo(i32);
1682 /// impl fmt::Display for Foo {
1683 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1684 /// assert!(formatter.sign_aware_zero_pad());
1685 /// assert_eq!(formatter.width(), Some(4));
1686 /// // We ignore the formatter's options.
1687 /// write!(formatter, "{}", self.0)
1691 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1693 #[stable(feature = "fmt_flags", since = "1.5.0")]
1694 pub fn sign_aware_zero_pad(&self) -> bool {
1695 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1698 // FIXME: Decide what public API we want for these two flags.
1699 // https://github.com/rust-lang/rust/issues/48584
1700 fn debug_lower_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0 }
1702 fn debug_upper_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0 }
1704 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1705 /// [`fmt::Debug`] implementations for structs.
1707 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1708 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1714 /// use std::net::Ipv4Addr;
1722 /// impl fmt::Debug for Foo {
1723 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1724 /// fmt.debug_struct("Foo")
1725 /// .field("bar", &self.bar)
1726 /// .field("baz", &self.baz)
1727 /// .field("addr", &format_args!("{}", self.addr))
1733 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1734 /// format!("{:?}", Foo {
1736 /// baz: "Hello World".to_string(),
1737 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1741 #[stable(feature = "debug_builders", since = "1.2.0")]
1742 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1743 builders::debug_struct_new(self, name)
1746 /// Creates a `DebugTuple` builder designed to assist with creation of
1747 /// `fmt::Debug` implementations for tuple structs.
1753 /// use std::marker::PhantomData;
1755 /// struct Foo<T>(i32, String, PhantomData<T>);
1757 /// impl<T> fmt::Debug for Foo<T> {
1758 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1759 /// fmt.debug_tuple("Foo")
1762 /// .field(&format_args!("_"))
1768 /// "Foo(10, \"Hello\", _)",
1769 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1772 #[stable(feature = "debug_builders", since = "1.2.0")]
1773 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1774 builders::debug_tuple_new(self, name)
1777 /// Creates a `DebugList` builder designed to assist with creation of
1778 /// `fmt::Debug` implementations for list-like structures.
1785 /// struct Foo(Vec<i32>);
1787 /// impl fmt::Debug for Foo {
1788 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1789 /// fmt.debug_list().entries(self.0.iter()).finish()
1793 /// // prints "[10, 11]"
1794 /// println!("{:?}", Foo(vec![10, 11]));
1796 #[stable(feature = "debug_builders", since = "1.2.0")]
1797 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1798 builders::debug_list_new(self)
1801 /// Creates a `DebugSet` builder designed to assist with creation of
1802 /// `fmt::Debug` implementations for set-like structures.
1809 /// struct Foo(Vec<i32>);
1811 /// impl fmt::Debug for Foo {
1812 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1813 /// fmt.debug_set().entries(self.0.iter()).finish()
1817 /// // prints "{10, 11}"
1818 /// println!("{:?}", Foo(vec![10, 11]));
1821 /// [`format_args!`]: ../../std/macro.format_args.html
1823 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1824 /// to build a list of match arms:
1829 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1830 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1832 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1834 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1836 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1837 /// L::fmt(&(self.0).0, fmt)?;
1838 /// fmt.write_str(" => ")?;
1839 /// R::fmt(&(self.0).1, fmt)
1843 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1845 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1847 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1849 /// .entries(self.0.iter().map(Arm))
1850 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1855 #[stable(feature = "debug_builders", since = "1.2.0")]
1856 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1857 builders::debug_set_new(self)
1860 /// Creates a `DebugMap` builder designed to assist with creation of
1861 /// `fmt::Debug` implementations for map-like structures.
1868 /// struct Foo(Vec<(String, i32)>);
1870 /// impl fmt::Debug for Foo {
1871 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1872 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1876 /// // prints "{"A": 10, "B": 11}"
1877 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1879 #[stable(feature = "debug_builders", since = "1.2.0")]
1880 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1881 builders::debug_map_new(self)
1885 #[stable(since = "1.2.0", feature = "formatter_write")]
1886 impl Write for Formatter<'_> {
1887 fn write_str(&mut self, s: &str) -> Result {
1888 self.buf.write_str(s)
1891 fn write_char(&mut self, c: char) -> Result {
1892 self.buf.write_char(c)
1895 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
1896 write(self.buf, args)
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 impl Display for Error {
1902 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1903 Display::fmt("an error occurred when formatting an argument", f)
1907 // Implementations of the core formatting traits
1909 macro_rules! fmt_refs {
1910 ($($tr:ident),*) => {
1912 #[stable(feature = "rust1", since = "1.0.0")]
1913 impl<T: ?Sized + $tr> $tr for &T {
1914 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
1916 #[stable(feature = "rust1", since = "1.0.0")]
1917 impl<T: ?Sized + $tr> $tr for &mut T {
1918 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
1924 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1926 #[unstable(feature = "never_type", issue = "35121")]
1928 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
1933 #[unstable(feature = "never_type", issue = "35121")]
1934 impl Display for ! {
1935 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
1940 #[stable(feature = "rust1", since = "1.0.0")]
1941 impl Debug for bool {
1943 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1944 Display::fmt(self, f)
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 impl Display for bool {
1950 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1951 Display::fmt(if *self { "true" } else { "false" }, f)
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl Debug for str {
1957 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1960 for (i, c) in self.char_indices() {
1961 let esc = c.escape_debug();
1962 // If char needs escaping, flush backlog so far and write, else skip
1964 f.write_str(&self[from..i])?;
1968 from = i + c.len_utf8();
1971 f.write_str(&self[from..])?;
1976 #[stable(feature = "rust1", since = "1.0.0")]
1977 impl Display for str {
1978 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl Debug for char {
1985 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1986 f.write_char('\'')?;
1987 for c in self.escape_debug() {
1994 #[stable(feature = "rust1", since = "1.0.0")]
1995 impl Display for char {
1996 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1997 if f.width.is_none() && f.precision.is_none() {
2000 f.pad(self.encode_utf8(&mut [0; 4]))
2005 #[stable(feature = "rust1", since = "1.0.0")]
2006 impl<T: ?Sized> Pointer for *const T {
2007 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2008 let old_width = f.width;
2009 let old_flags = f.flags;
2011 // The alternate flag is already treated by LowerHex as being special-
2012 // it denotes whether to prefix with 0x. We use it to work out whether
2013 // or not to zero extend, and then unconditionally set it to get the
2016 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2018 if let None = f.width {
2019 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2022 f.flags |= 1 << (FlagV1::Alternate as u32);
2024 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2026 f.width = old_width;
2027 f.flags = old_flags;
2033 #[stable(feature = "rust1", since = "1.0.0")]
2034 impl<T: ?Sized> Pointer for *mut T {
2035 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2036 Pointer::fmt(&(*self as *const T), f)
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 impl<T: ?Sized> Pointer for &T {
2042 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2043 Pointer::fmt(&(*self as *const T), f)
2047 #[stable(feature = "rust1", since = "1.0.0")]
2048 impl<T: ?Sized> Pointer for &mut T {
2049 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2050 Pointer::fmt(&(&**self as *const T), f)
2054 // Implementation of Display/Debug for various core types
2056 #[stable(feature = "rust1", since = "1.0.0")]
2057 impl<T: ?Sized> Debug for *const T {
2058 fn fmt(&self, f: &mut Formatter<'_>) -> Result { Pointer::fmt(self, f) }
2060 #[stable(feature = "rust1", since = "1.0.0")]
2061 impl<T: ?Sized> Debug for *mut T {
2062 fn fmt(&self, f: &mut Formatter<'_>) -> Result { Pointer::fmt(self, f) }
2066 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2069 macro_rules! tuple {
2071 ( $($name:ident,)+ ) => (
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
2074 #[allow(non_snake_case, unused_assignments)]
2075 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2076 let mut builder = f.debug_tuple("");
2077 let ($(ref $name,)*) = *self;
2079 builder.field(&$name);
2085 peel! { $($name,)* }
2089 macro_rules! last_type {
2090 ($a:ident,) => { $a };
2091 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2094 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2096 #[stable(feature = "rust1", since = "1.0.0")]
2097 impl<T: Debug> Debug for [T] {
2098 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2099 f.debug_list().entries(self.iter()).finish()
2103 #[stable(feature = "rust1", since = "1.0.0")]
2106 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2110 #[stable(feature = "rust1", since = "1.0.0")]
2111 impl<T: ?Sized> Debug for PhantomData<T> {
2112 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2113 f.pad("PhantomData")
2117 #[stable(feature = "rust1", since = "1.0.0")]
2118 impl<T: Copy + Debug> Debug for Cell<T> {
2119 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2120 f.debug_struct("Cell")
2121 .field("value", &self.get())
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2128 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2129 match self.try_borrow() {
2131 f.debug_struct("RefCell")
2132 .field("value", &borrow)
2136 // The RefCell is mutably borrowed so we can't look at its value
2137 // here. Show a placeholder instead.
2138 struct BorrowedPlaceholder;
2140 impl Debug for BorrowedPlaceholder {
2141 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2142 f.write_str("<borrowed>")
2146 f.debug_struct("RefCell")
2147 .field("value", &BorrowedPlaceholder)
2154 #[stable(feature = "rust1", since = "1.0.0")]
2155 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2156 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2157 Debug::fmt(&**self, f)
2161 #[stable(feature = "rust1", since = "1.0.0")]
2162 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2163 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2164 Debug::fmt(&*(self.deref()), f)
2168 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2169 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2170 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2175 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
2176 // it's a lot easier than creating all of the rt::Piece structures here.