1 //! Utilities for formatting and printing strings.
3 #![stable(feature = "rust1", since = "1.0.0")]
5 use cell::{UnsafeCell, Cell, RefCell, Ref, RefMut};
6 use marker::PhantomData;
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 /// A struct to represent both where to emit formatting strings to and how they
215 /// should be formatted. A mutable version of this is passed to all formatting
217 #[allow(missing_debug_implementations)]
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub struct Formatter<'a> {
222 align: rt::v1::Alignment,
223 width: Option<usize>,
224 precision: Option<usize>,
226 buf: &'a mut (dyn Write+'a),
227 curarg: slice::Iter<'a, ArgumentV1<'a>>,
228 args: &'a [ArgumentV1<'a>],
231 // NB. Argument is essentially an optimized partially applied formatting function,
232 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
236 /// Erases all oibits, because `Void` erases the type of the object that
237 /// will be used to produce formatted output. Since we do not know what
238 /// oibits the real types have (and they can have any or none), we need to
239 /// take the most conservative approach and forbid all oibits.
241 /// It was added after #45197 showed that one could share a `!Sync`
242 /// object across threads by passing it into `format_args!`.
243 _oibit_remover: PhantomData<*mut dyn Fn()>,
246 /// This struct represents the generic "argument" which is taken by the Xprintf
247 /// family of functions. It contains a function to format the given value. At
248 /// compile time it is ensured that the function and the value have the correct
249 /// types, and then this struct is used to canonicalize arguments to one type.
250 #[derive(Copy, Clone)]
251 #[allow(missing_debug_implementations)]
252 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
255 pub struct ArgumentV1<'a> {
257 formatter: fn(&Void, &mut Formatter) -> Result,
260 impl<'a> ArgumentV1<'a> {
262 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
267 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
269 pub fn new<'b, T>(x: &'b T,
270 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
273 formatter: mem::transmute(f),
274 value: mem::transmute(x)
280 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
282 pub fn from_usize(x: &usize) -> ArgumentV1 {
283 ArgumentV1::new(x, ArgumentV1::show_usize)
286 fn as_usize(&self) -> Option<usize> {
287 if self.formatter as usize == ArgumentV1::show_usize as usize {
288 Some(unsafe { *(self.value as *const _ as *const usize) })
295 // flags available in the v1 format of format_args
296 #[derive(Copy, Clone)]
297 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, DebugLowerHex, DebugUpperHex }
299 impl<'a> Arguments<'a> {
300 /// When using the format_args!() macro, this function is used to generate the
301 /// Arguments structure.
302 #[doc(hidden)] #[inline]
303 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
305 pub fn new_v1(pieces: &'a [&'a str],
306 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
314 /// This function is used to specify nonstandard formatting parameters.
315 /// The `pieces` array must be at least as long as `fmt` to construct
316 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
317 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
318 /// created with `argumentusize`. However, failing to do so doesn't cause
319 /// unsafety, but will ignore invalid .
320 #[doc(hidden)] #[inline]
321 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
323 pub fn new_v1_formatted(pieces: &'a [&'a str],
324 args: &'a [ArgumentV1<'a>],
325 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
333 /// Estimates the length of the formatted text.
335 /// This is intended to be used for setting initial `String` capacity
336 /// when using `format!`. Note: this is neither the lower nor upper bound.
337 #[doc(hidden)] #[inline]
338 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
340 pub fn estimated_capacity(&self) -> usize {
341 let pieces_length: usize = self.pieces.iter()
342 .map(|x| x.len()).sum();
344 if self.args.is_empty() {
346 } else if self.pieces[0] == "" && pieces_length < 16 {
347 // If the format string starts with an argument,
348 // don't preallocate anything, unless length
349 // of pieces is significant.
352 // There are some arguments, so any additional push
353 // will reallocate the string. To avoid that,
354 // we're "pre-doubling" the capacity here.
355 pieces_length.checked_mul(2).unwrap_or(0)
360 /// This structure represents a safely precompiled version of a format string
361 /// and its arguments. This cannot be generated at runtime because it cannot
362 /// safely be done, so no constructors are given and the fields are private
363 /// to prevent modification.
365 /// The [`format_args!`] macro will safely create an instance of this structure.
366 /// The macro validates the format string at compile-time so usage of the
367 /// [`write`] and [`format`] functions can be safely performed.
369 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
370 /// and `Display` contexts as seen below. The example also shows that `Debug`
371 /// and `Display` format to the same thing: the interpolated format string
372 /// in `format_args!`.
375 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
376 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
377 /// assert_eq!("1 foo 2", display);
378 /// assert_eq!(display, debug);
381 /// [`format_args!`]: ../../std/macro.format_args.html
382 /// [`format`]: ../../std/fmt/fn.format.html
383 /// [`write`]: ../../std/fmt/fn.write.html
384 #[stable(feature = "rust1", since = "1.0.0")]
385 #[derive(Copy, Clone)]
386 pub struct Arguments<'a> {
387 // Format string pieces to print.
388 pieces: &'a [&'a str],
390 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
391 fmt: Option<&'a [rt::v1::Argument]>,
393 // Dynamic arguments for interpolation, to be interleaved with string
394 // pieces. (Every argument is preceded by a string piece.)
395 args: &'a [ArgumentV1<'a>],
398 #[stable(feature = "rust1", since = "1.0.0")]
399 impl Debug for Arguments<'_> {
400 fn fmt(&self, fmt: &mut Formatter) -> Result {
401 Display::fmt(self, fmt)
405 #[stable(feature = "rust1", since = "1.0.0")]
406 impl Display for Arguments<'_> {
407 fn fmt(&self, fmt: &mut Formatter) -> Result {
408 write(fmt.buf, *self)
414 /// `Debug` should format the output in a programmer-facing, debugging context.
416 /// Generally speaking, you should just `derive` a `Debug` implementation.
418 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
420 /// For more information on formatters, see [the module-level documentation][module].
422 /// [module]: ../../std/fmt/index.html
424 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
425 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
426 /// comma-separated list of each field's name and `Debug` value, then `}`. For
427 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
428 /// `Debug` values of the fields, then `)`.
432 /// Deriving an implementation:
441 /// let origin = Point { x: 0, y: 0 };
443 /// println!("The origin is: {:?}", origin);
446 /// Manually implementing:
456 /// impl fmt::Debug for Point {
457 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
458 /// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
462 /// let origin = Point { x: 0, y: 0 };
464 /// println!("The origin is: {:?}", origin);
470 /// The origin is: Point { x: 0, y: 0 }
473 /// There are a number of `debug_*` methods on [`Formatter`] to help you with manual
474 /// implementations, such as [`debug_struct`][debug_struct].
476 /// `Debug` implementations using either `derive` or the debug builder API
477 /// on [`Formatter`] support pretty printing using the alternate flag: `{:#?}`.
479 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
480 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
482 /// Pretty printing with `#?`:
491 /// let origin = Point { x: 0, y: 0 };
493 /// println!("The origin is: {:#?}", origin);
499 /// The origin is: Point {
504 #[stable(feature = "rust1", since = "1.0.0")]
505 #[rustc_on_unimplemented(
506 on(crate_local, label="`{Self}` cannot be formatted using `{{:?}}`",
507 note="add `#[derive(Debug)]` or manually implement `{Debug}`"),
508 message="`{Self}` doesn't implement `{Debug}`",
509 label="`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`",
511 #[doc(alias = "{:?}")]
512 #[lang = "debug_trait"]
514 /// Formats the value using the given formatter.
521 /// struct Position {
526 /// impl fmt::Debug for Position {
527 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
528 /// write!(f, "({:?}, {:?})", self.longitude, self.latitude)
532 /// assert_eq!("(1.987, 2.983)".to_owned(),
533 /// format!("{:?}", Position { longitude: 1.987, latitude: 2.983, }));
535 #[stable(feature = "rust1", since = "1.0.0")]
536 fn fmt(&self, f: &mut Formatter) -> Result;
539 /// Format trait for an empty format, `{}`.
541 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
542 /// output, and so cannot be derived.
544 /// [debug]: trait.Debug.html
546 /// For more information on formatters, see [the module-level documentation][module].
548 /// [module]: ../../std/fmt/index.html
552 /// Implementing `Display` on a type:
562 /// impl fmt::Display for Point {
563 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
564 /// write!(f, "({}, {})", self.x, self.y)
568 /// let origin = Point { x: 0, y: 0 };
570 /// println!("The origin is: {}", origin);
572 #[rustc_on_unimplemented(
574 _Self="std::path::Path",
575 label="`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
576 note="call `.display()` or `.to_string_lossy()` to safely print paths, \
577 as they may contain non-Unicode data"
579 message="`{Self}` doesn't implement `{Display}`",
580 label="`{Self}` cannot be formatted with the default formatter",
581 note="in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead",
584 #[stable(feature = "rust1", since = "1.0.0")]
586 /// Formats the value using the given formatter.
593 /// struct Position {
598 /// impl fmt::Display for Position {
599 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
600 /// write!(f, "({}, {})", self.longitude, self.latitude)
604 /// assert_eq!("(1.987, 2.983)".to_owned(),
605 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
607 #[stable(feature = "rust1", since = "1.0.0")]
608 fn fmt(&self, f: &mut Formatter) -> Result;
613 /// The `Octal` trait should format its output as a number in base-8.
615 /// For primitive signed integers (`i8` to `i128`, and `isize`),
616 /// negative values are formatted as the two’s complement representation.
618 /// The alternate flag, `#`, adds a `0o` in front of the output.
620 /// For more information on formatters, see [the module-level documentation][module].
622 /// [module]: ../../std/fmt/index.html
626 /// Basic usage with `i32`:
629 /// let x = 42; // 42 is '52' in octal
631 /// assert_eq!(format!("{:o}", x), "52");
632 /// assert_eq!(format!("{:#o}", x), "0o52");
634 /// assert_eq!(format!("{:o}", -16), "37777777760");
637 /// Implementing `Octal` on a type:
642 /// struct Length(i32);
644 /// impl fmt::Octal for Length {
645 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
646 /// let val = self.0;
648 /// write!(f, "{:o}", val) // delegate to i32's implementation
652 /// let l = Length(9);
654 /// println!("l as octal is: {:o}", l);
656 #[stable(feature = "rust1", since = "1.0.0")]
658 /// Formats the value using the given formatter.
659 #[stable(feature = "rust1", since = "1.0.0")]
660 fn fmt(&self, f: &mut Formatter) -> Result;
665 /// The `Binary` trait should format its output as a number in binary.
667 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
668 /// negative values are formatted as the two’s complement representation.
670 /// The alternate flag, `#`, adds a `0b` in front of the output.
672 /// For more information on formatters, see [the module-level documentation][module].
676 /// Basic usage with [`i32`]:
679 /// let x = 42; // 42 is '101010' in binary
681 /// assert_eq!(format!("{:b}", x), "101010");
682 /// assert_eq!(format!("{:#b}", x), "0b101010");
684 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
687 /// Implementing `Binary` on a type:
692 /// struct Length(i32);
694 /// impl fmt::Binary for Length {
695 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
696 /// let val = self.0;
698 /// write!(f, "{:b}", val) // delegate to i32's implementation
702 /// let l = Length(107);
704 /// println!("l as binary is: {:b}", l);
707 /// [module]: ../../std/fmt/index.html
708 /// [`i8`]: ../../std/primitive.i8.html
709 /// [`i128`]: ../../std/primitive.i128.html
710 /// [`isize`]: ../../std/primitive.isize.html
711 /// [`i32`]: ../../std/primitive.i32.html
712 #[stable(feature = "rust1", since = "1.0.0")]
714 /// Formats the value using the given formatter.
715 #[stable(feature = "rust1", since = "1.0.0")]
716 fn fmt(&self, f: &mut Formatter) -> Result;
721 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
724 /// For primitive signed integers (`i8` to `i128`, and `isize`),
725 /// negative values are formatted as the two’s complement representation.
727 /// The alternate flag, `#`, adds a `0x` in front of the output.
729 /// For more information on formatters, see [the module-level documentation][module].
731 /// [module]: ../../std/fmt/index.html
735 /// Basic usage with `i32`:
738 /// let x = 42; // 42 is '2a' in hex
740 /// assert_eq!(format!("{:x}", x), "2a");
741 /// assert_eq!(format!("{:#x}", x), "0x2a");
743 /// assert_eq!(format!("{:x}", -16), "fffffff0");
746 /// Implementing `LowerHex` on a type:
751 /// struct Length(i32);
753 /// impl fmt::LowerHex for Length {
754 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
755 /// let val = self.0;
757 /// write!(f, "{:x}", val) // delegate to i32's implementation
761 /// let l = Length(9);
763 /// println!("l as hex is: {:x}", l);
765 #[stable(feature = "rust1", since = "1.0.0")]
767 /// Formats the value using the given formatter.
768 #[stable(feature = "rust1", since = "1.0.0")]
769 fn fmt(&self, f: &mut Formatter) -> Result;
774 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
777 /// For primitive signed integers (`i8` to `i128`, and `isize`),
778 /// negative values are formatted as the two’s complement representation.
780 /// The alternate flag, `#`, adds a `0x` in front of the output.
782 /// For more information on formatters, see [the module-level documentation][module].
784 /// [module]: ../../std/fmt/index.html
788 /// Basic usage with `i32`:
791 /// let x = 42; // 42 is '2A' in hex
793 /// assert_eq!(format!("{:X}", x), "2A");
794 /// assert_eq!(format!("{:#X}", x), "0x2A");
796 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
799 /// Implementing `UpperHex` on a type:
804 /// struct Length(i32);
806 /// impl fmt::UpperHex for Length {
807 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
808 /// let val = self.0;
810 /// write!(f, "{:X}", val) // delegate to i32's implementation
814 /// let l = Length(9);
816 /// println!("l as hex is: {:X}", l);
818 #[stable(feature = "rust1", since = "1.0.0")]
820 /// Formats the value using the given formatter.
821 #[stable(feature = "rust1", since = "1.0.0")]
822 fn fmt(&self, f: &mut Formatter) -> Result;
827 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
830 /// For more information on formatters, see [the module-level documentation][module].
832 /// [module]: ../../std/fmt/index.html
836 /// Basic usage with `&i32`:
841 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
844 /// Implementing `Pointer` on a type:
849 /// struct Length(i32);
851 /// impl fmt::Pointer for Length {
852 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
853 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
855 /// write!(f, "{:p}", self as *const Length)
859 /// let l = Length(42);
861 /// println!("l is in memory here: {:p}", l);
863 #[stable(feature = "rust1", since = "1.0.0")]
865 /// Formats the value using the given formatter.
866 #[stable(feature = "rust1", since = "1.0.0")]
867 fn fmt(&self, f: &mut Formatter) -> Result;
872 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
874 /// For more information on formatters, see [the module-level documentation][module].
876 /// [module]: ../../std/fmt/index.html
880 /// Basic usage with `i32`:
883 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
885 /// assert_eq!(format!("{:e}", x), "4.2e1");
888 /// Implementing `LowerExp` on a type:
893 /// struct Length(i32);
895 /// impl fmt::LowerExp for Length {
896 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
897 /// let val = self.0;
898 /// write!(f, "{}e1", val / 10)
902 /// let l = Length(100);
904 /// println!("l in scientific notation is: {:e}", l);
906 #[stable(feature = "rust1", since = "1.0.0")]
908 /// Formats the value using the given formatter.
909 #[stable(feature = "rust1", since = "1.0.0")]
910 fn fmt(&self, f: &mut Formatter) -> Result;
915 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
917 /// For more information on formatters, see [the module-level documentation][module].
919 /// [module]: ../../std/fmt/index.html
923 /// Basic usage with `f32`:
926 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
928 /// assert_eq!(format!("{:E}", x), "4.2E1");
931 /// Implementing `UpperExp` on a type:
936 /// struct Length(i32);
938 /// impl fmt::UpperExp for Length {
939 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
940 /// let val = self.0;
941 /// write!(f, "{}E1", val / 10)
945 /// let l = Length(100);
947 /// println!("l in scientific notation is: {:E}", l);
949 #[stable(feature = "rust1", since = "1.0.0")]
951 /// Formats the value using the given formatter.
952 #[stable(feature = "rust1", since = "1.0.0")]
953 fn fmt(&self, f: &mut Formatter) -> Result;
956 /// The `write` function takes an output stream, and an `Arguments` struct
957 /// that can be precompiled with the `format_args!` macro.
959 /// The arguments will be formatted according to the specified format string
960 /// into the output stream provided.
969 /// let mut output = String::new();
970 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
971 /// .expect("Error occurred while trying to write in String");
972 /// assert_eq!(output, "Hello world!");
975 /// Please note that using [`write!`] might be preferable. Example:
978 /// use std::fmt::Write;
980 /// let mut output = String::new();
981 /// write!(&mut output, "Hello {}!", "world")
982 /// .expect("Error occurred while trying to write in String");
983 /// assert_eq!(output, "Hello world!");
986 /// [`write!`]: ../../std/macro.write.html
987 #[stable(feature = "rust1", since = "1.0.0")]
988 pub fn write(output: &mut dyn Write, args: Arguments) -> Result {
989 let mut formatter = Formatter {
994 align: rt::v1::Alignment::Unknown,
997 curarg: args.args.iter(),
1000 let mut pieces = args.pieces.iter();
1004 // We can use default formatting parameters for all arguments.
1005 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
1006 formatter.buf.write_str(*piece)?;
1007 (arg.formatter)(arg.value, &mut formatter)?;
1011 // Every spec has a corresponding argument that is preceded by
1013 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
1014 formatter.buf.write_str(*piece)?;
1015 formatter.run(arg)?;
1020 // There can be only one trailing string piece left.
1021 if let Some(piece) = pieces.next() {
1022 formatter.buf.write_str(*piece)?;
1028 impl<'a> Formatter<'a> {
1029 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1030 where 'b: 'c, F: FnOnce(&'b mut (dyn Write+'b)) -> &'c mut (dyn Write+'c)
1033 // We want to change this
1034 buf: wrap(self.buf),
1036 // And preserve these
1041 precision: self.precision,
1043 // These only exist in the struct for the `run` method,
1044 // which won’t be used together with this method.
1045 curarg: self.curarg.clone(),
1050 // First up is the collection of functions used to execute a format string
1051 // at runtime. This consumes all of the compile-time statics generated by
1052 // the format! syntax extension.
1053 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1054 // Fill in the format parameters into the formatter
1055 self.fill = arg.format.fill;
1056 self.align = arg.format.align;
1057 self.flags = arg.format.flags;
1058 self.width = self.getcount(&arg.format.width);
1059 self.precision = self.getcount(&arg.format.precision);
1061 // Extract the correct argument
1062 let value = match arg.position {
1063 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1064 rt::v1::Position::At(i) => self.args[i],
1067 // Then actually do some printing
1068 (value.formatter)(value.value, self)
1071 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1073 rt::v1::Count::Is(n) => Some(n),
1074 rt::v1::Count::Implied => None,
1075 rt::v1::Count::Param(i) => {
1076 self.args[i].as_usize()
1078 rt::v1::Count::NextParam => {
1079 self.curarg.next()?.as_usize()
1084 // Helper methods used for padding and processing formatting arguments that
1085 // all formatting traits can use.
1087 /// Performs the correct padding for an integer which has already been
1088 /// emitted into a str. The str should *not* contain the sign for the
1089 /// integer, that will be added by this method.
1093 /// * is_nonnegative - whether the original integer was either positive or zero.
1094 /// * prefix - if the '#' character (Alternate) is provided, this
1095 /// is the prefix to put in front of the number.
1096 /// * buf - the byte array that the number has been formatted into
1098 /// This function will correctly account for the flags provided as well as
1099 /// the minimum width. It will not take precision into account.
1106 /// struct Foo { nb: i32 };
1109 /// fn new(nb: i32) -> Foo {
1116 /// impl fmt::Display for Foo {
1117 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1118 /// // We need to remove "-" from the number output.
1119 /// let tmp = self.nb.abs().to_string();
1121 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1125 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1126 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1127 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1128 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 pub fn pad_integral(&mut self,
1132 is_nonnegative: bool,
1136 let mut width = buf.len();
1138 let mut sign = None;
1139 if !is_nonnegative {
1140 sign = Some('-'); width += 1;
1141 } else if self.sign_plus() {
1142 sign = Some('+'); width += 1;
1145 let prefixed = self.alternate();
1147 width += prefix.chars().count();
1150 // Writes the sign if it exists, and then the prefix if it was requested
1151 let write_prefix = |f: &mut Formatter| {
1152 if let Some(c) = sign {
1153 f.buf.write_char(c)?;
1155 if prefixed { f.buf.write_str(prefix) }
1159 // The `width` field is more of a `min-width` parameter at this point.
1161 // If there's no minimum length requirements then we can just
1164 write_prefix(self)?; self.buf.write_str(buf)
1166 // Check if we're over the minimum width, if so then we can also
1167 // just write the bytes.
1168 Some(min) if width >= min => {
1169 write_prefix(self)?; self.buf.write_str(buf)
1171 // The sign and prefix goes before the padding if the fill character
1173 Some(min) if self.sign_aware_zero_pad() => {
1175 self.align = rt::v1::Alignment::Right;
1176 write_prefix(self)?;
1177 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1178 f.buf.write_str(buf)
1181 // Otherwise, the sign and prefix goes after the padding
1183 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1184 write_prefix(f)?; f.buf.write_str(buf)
1190 /// This function takes a string slice and emits it to the internal buffer
1191 /// after applying the relevant formatting flags specified. The flags
1192 /// recognized for generic strings are:
1194 /// * width - the minimum width of what to emit
1195 /// * fill/align - what to emit and where to emit it if the string
1196 /// provided needs to be padded
1197 /// * precision - the maximum length to emit, the string is truncated if it
1198 /// is longer than this length
1200 /// Notably this function ignores the `flag` parameters.
1209 /// impl fmt::Display for Foo {
1210 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1211 /// formatter.pad("Foo")
1215 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1216 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 pub fn pad(&mut self, s: &str) -> Result {
1220 // Make sure there's a fast path up front
1221 if self.width.is_none() && self.precision.is_none() {
1222 return self.buf.write_str(s);
1224 // The `precision` field can be interpreted as a `max-width` for the
1225 // string being formatted.
1226 let s = if let Some(max) = self.precision {
1227 // If our string is longer that the precision, then we must have
1228 // truncation. However other flags like `fill`, `width` and `align`
1229 // must act as always.
1230 if let Some((i, _)) = s.char_indices().nth(max) {
1231 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1232 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1233 // `unsafe` and otherwise don't emit any panic-related code
1235 s.get(..i).unwrap_or(&s)
1242 // The `width` field is more of a `min-width` parameter at this point.
1244 // If we're under the maximum length, and there's no minimum length
1245 // requirements, then we can just emit the string
1246 None => self.buf.write_str(s),
1247 // If we're under the maximum width, check if we're over the minimum
1248 // width, if so it's as easy as just emitting the string.
1249 Some(width) if s.chars().count() >= width => {
1250 self.buf.write_str(s)
1252 // If we're under both the maximum and the minimum width, then fill
1253 // up the minimum width with the specified string + some alignment.
1255 let align = rt::v1::Alignment::Left;
1256 self.with_padding(width - s.chars().count(), align, |me| {
1263 /// Runs a callback, emitting the correct padding either before or
1264 /// afterwards depending on whether right or left alignment is requested.
1265 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1267 where F: FnOnce(&mut Formatter) -> Result,
1269 let align = match self.align {
1270 rt::v1::Alignment::Unknown => default,
1274 let (pre_pad, post_pad) = match align {
1275 rt::v1::Alignment::Left => (0, padding),
1276 rt::v1::Alignment::Right |
1277 rt::v1::Alignment::Unknown => (padding, 0),
1278 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1281 let mut fill = [0; 4];
1282 let fill = self.fill.encode_utf8(&mut fill);
1284 for _ in 0..pre_pad {
1285 self.buf.write_str(fill)?;
1290 for _ in 0..post_pad {
1291 self.buf.write_str(fill)?;
1297 /// Takes the formatted parts and applies the padding.
1298 /// Assumes that the caller already has rendered the parts with required precision,
1299 /// so that `self.precision` can be ignored.
1300 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1301 if let Some(mut width) = self.width {
1302 // for the sign-aware zero padding, we render the sign first and
1303 // behave as if we had no sign from the beginning.
1304 let mut formatted = formatted.clone();
1305 let old_fill = self.fill;
1306 let old_align = self.align;
1307 let mut align = old_align;
1308 if self.sign_aware_zero_pad() {
1309 // a sign always goes first
1310 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1311 self.buf.write_str(sign)?;
1313 // remove the sign from the formatted parts
1314 formatted.sign = b"";
1315 width = width.saturating_sub(sign.len());
1316 align = rt::v1::Alignment::Right;
1318 self.align = rt::v1::Alignment::Right;
1321 // remaining parts go through the ordinary padding process.
1322 let len = formatted.len();
1323 let ret = if width <= len { // no padding
1324 self.write_formatted_parts(&formatted)
1326 self.with_padding(width - len, align, |f| {
1327 f.write_formatted_parts(&formatted)
1330 self.fill = old_fill;
1331 self.align = old_align;
1334 // this is the common case and we take a shortcut
1335 self.write_formatted_parts(formatted)
1339 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1340 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1341 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1344 if !formatted.sign.is_empty() {
1345 write_bytes(self.buf, formatted.sign)?;
1347 for part in formatted.parts {
1349 flt2dec::Part::Zero(mut nzeroes) => {
1350 const ZEROES: &str = // 64 zeroes
1351 "0000000000000000000000000000000000000000000000000000000000000000";
1352 while nzeroes > ZEROES.len() {
1353 self.buf.write_str(ZEROES)?;
1354 nzeroes -= ZEROES.len();
1357 self.buf.write_str(&ZEROES[..nzeroes])?;
1360 flt2dec::Part::Num(mut v) => {
1362 let len = part.len();
1363 for c in s[..len].iter_mut().rev() {
1364 *c = b'0' + (v % 10) as u8;
1367 write_bytes(self.buf, &s[..len])?;
1369 flt2dec::Part::Copy(buf) => {
1370 write_bytes(self.buf, buf)?;
1377 /// Writes some data to the underlying buffer contained within this
1387 /// impl fmt::Display for Foo {
1388 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1389 /// formatter.write_str("Foo")
1390 /// // This is equivalent to:
1391 /// // write!(formatter, "Foo")
1395 /// assert_eq!(&format!("{}", Foo), "Foo");
1396 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 pub fn write_str(&mut self, data: &str) -> Result {
1400 self.buf.write_str(data)
1403 /// Writes some formatted information into this instance.
1410 /// struct Foo(i32);
1412 /// impl fmt::Display for Foo {
1413 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1414 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1418 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1419 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1423 write(self.buf, fmt)
1426 /// Flags for formatting
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 #[rustc_deprecated(since = "1.24.0",
1429 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1430 or `sign_aware_zero_pad` methods instead")]
1431 pub fn flags(&self) -> u32 { self.flags }
1433 /// Character used as 'fill' whenever there is alignment.
1442 /// impl fmt::Display for Foo {
1443 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1444 /// let c = formatter.fill();
1445 /// if let Some(width) = formatter.width() {
1446 /// for _ in 0..width {
1447 /// write!(formatter, "{}", c)?;
1451 /// write!(formatter, "{}", c)
1456 /// // We set alignment to the left with ">".
1457 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1458 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1460 #[stable(feature = "fmt_flags", since = "1.5.0")]
1461 pub fn fill(&self) -> char { self.fill }
1463 /// Flag indicating what form of alignment was requested.
1468 /// extern crate core;
1470 /// use std::fmt::{self, Alignment};
1474 /// impl fmt::Display for Foo {
1475 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1476 /// let s = if let Some(s) = formatter.align() {
1478 /// Alignment::Left => "left",
1479 /// Alignment::Right => "right",
1480 /// Alignment::Center => "center",
1485 /// write!(formatter, "{}", s)
1490 /// assert_eq!(&format!("{:<}", Foo), "left");
1491 /// assert_eq!(&format!("{:>}", Foo), "right");
1492 /// assert_eq!(&format!("{:^}", Foo), "center");
1493 /// assert_eq!(&format!("{}", Foo), "into the void");
1496 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1497 pub fn align(&self) -> Option<Alignment> {
1499 rt::v1::Alignment::Left => Some(Alignment::Left),
1500 rt::v1::Alignment::Right => Some(Alignment::Right),
1501 rt::v1::Alignment::Center => Some(Alignment::Center),
1502 rt::v1::Alignment::Unknown => None,
1506 /// Optionally specified integer width that the output should be.
1513 /// struct Foo(i32);
1515 /// impl fmt::Display for Foo {
1516 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1517 /// if let Some(width) = formatter.width() {
1518 /// // If we received a width, we use it
1519 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1521 /// // Otherwise we do nothing special
1522 /// write!(formatter, "Foo({})", self.0)
1527 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1528 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1530 #[stable(feature = "fmt_flags", since = "1.5.0")]
1531 pub fn width(&self) -> Option<usize> { self.width }
1533 /// Optionally specified precision for numeric types.
1540 /// struct Foo(f32);
1542 /// impl fmt::Display for Foo {
1543 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1544 /// if let Some(precision) = formatter.precision() {
1545 /// // If we received a precision, we use it.
1546 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1548 /// // Otherwise we default to 2.
1549 /// write!(formatter, "Foo({:.2})", self.0)
1554 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1555 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1557 #[stable(feature = "fmt_flags", since = "1.5.0")]
1558 pub fn precision(&self) -> Option<usize> { self.precision }
1560 /// Determines if the `+` flag was specified.
1567 /// struct Foo(i32);
1569 /// impl fmt::Display for Foo {
1570 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1571 /// if formatter.sign_plus() {
1572 /// write!(formatter,
1574 /// if self.0 < 0 { '-' } else { '+' },
1577 /// write!(formatter, "Foo({})", self.0)
1582 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1583 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1585 #[stable(feature = "fmt_flags", since = "1.5.0")]
1586 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1588 /// Determines if the `-` flag was specified.
1595 /// struct Foo(i32);
1597 /// impl fmt::Display for Foo {
1598 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1599 /// if formatter.sign_minus() {
1600 /// // You want a minus sign? Have one!
1601 /// write!(formatter, "-Foo({})", self.0)
1603 /// write!(formatter, "Foo({})", self.0)
1608 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1609 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1611 #[stable(feature = "fmt_flags", since = "1.5.0")]
1612 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1614 /// Determines if the `#` flag was specified.
1621 /// struct Foo(i32);
1623 /// impl fmt::Display for Foo {
1624 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1625 /// if formatter.alternate() {
1626 /// write!(formatter, "Foo({})", self.0)
1628 /// write!(formatter, "{}", self.0)
1633 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1634 /// assert_eq!(&format!("{}", Foo(23)), "23");
1636 #[stable(feature = "fmt_flags", since = "1.5.0")]
1637 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1639 /// Determines if the `0` flag was specified.
1646 /// struct Foo(i32);
1648 /// impl fmt::Display for Foo {
1649 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1650 /// assert!(formatter.sign_aware_zero_pad());
1651 /// assert_eq!(formatter.width(), Some(4));
1652 /// // We ignore the formatter's options.
1653 /// write!(formatter, "{}", self.0)
1657 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1659 #[stable(feature = "fmt_flags", since = "1.5.0")]
1660 pub fn sign_aware_zero_pad(&self) -> bool {
1661 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1664 // FIXME: Decide what public API we want for these two flags.
1665 // https://github.com/rust-lang/rust/issues/48584
1666 fn debug_lower_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0 }
1668 fn debug_upper_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0 }
1670 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1671 /// [`fmt::Debug`] implementations for structs.
1673 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1674 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1680 /// use std::net::Ipv4Addr;
1688 /// impl fmt::Debug for Foo {
1689 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1690 /// fmt.debug_struct("Foo")
1691 /// .field("bar", &self.bar)
1692 /// .field("baz", &self.baz)
1693 /// .field("addr", &format_args!("{}", self.addr))
1699 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1700 /// format!("{:?}", Foo {
1702 /// baz: "Hello World".to_string(),
1703 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1707 #[stable(feature = "debug_builders", since = "1.2.0")]
1708 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1709 builders::debug_struct_new(self, name)
1712 /// Creates a `DebugTuple` builder designed to assist with creation of
1713 /// `fmt::Debug` implementations for tuple structs.
1719 /// use std::marker::PhantomData;
1721 /// struct Foo<T>(i32, String, PhantomData<T>);
1723 /// impl<T> fmt::Debug for Foo<T> {
1724 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1725 /// fmt.debug_tuple("Foo")
1728 /// .field(&format_args!("_"))
1734 /// "Foo(10, \"Hello\", _)",
1735 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1738 #[stable(feature = "debug_builders", since = "1.2.0")]
1739 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1740 builders::debug_tuple_new(self, name)
1743 /// Creates a `DebugList` builder designed to assist with creation of
1744 /// `fmt::Debug` implementations for list-like structures.
1751 /// struct Foo(Vec<i32>);
1753 /// impl fmt::Debug for Foo {
1754 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1755 /// fmt.debug_list().entries(self.0.iter()).finish()
1759 /// // prints "[10, 11]"
1760 /// println!("{:?}", Foo(vec![10, 11]));
1762 #[stable(feature = "debug_builders", since = "1.2.0")]
1763 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1764 builders::debug_list_new(self)
1767 /// Creates a `DebugSet` builder designed to assist with creation of
1768 /// `fmt::Debug` implementations for set-like structures.
1775 /// struct Foo(Vec<i32>);
1777 /// impl fmt::Debug for Foo {
1778 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1779 /// fmt.debug_set().entries(self.0.iter()).finish()
1783 /// // prints "{10, 11}"
1784 /// println!("{:?}", Foo(vec![10, 11]));
1787 /// [`format_args!`]: ../../std/macro.format_args.html
1789 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1790 /// to build a list of match arms:
1795 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1796 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1798 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1800 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1802 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1803 /// L::fmt(&(self.0).0, fmt)?;
1804 /// fmt.write_str(" => ")?;
1805 /// R::fmt(&(self.0).1, fmt)
1809 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1811 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1813 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1815 /// .entries(self.0.iter().map(Arm))
1816 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1821 #[stable(feature = "debug_builders", since = "1.2.0")]
1822 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1823 builders::debug_set_new(self)
1826 /// Creates a `DebugMap` builder designed to assist with creation of
1827 /// `fmt::Debug` implementations for map-like structures.
1834 /// struct Foo(Vec<(String, i32)>);
1836 /// impl fmt::Debug for Foo {
1837 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1838 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1842 /// // prints "{"A": 10, "B": 11}"
1843 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1845 #[stable(feature = "debug_builders", since = "1.2.0")]
1846 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1847 builders::debug_map_new(self)
1851 #[stable(since = "1.2.0", feature = "formatter_write")]
1852 impl Write for Formatter<'_> {
1853 fn write_str(&mut self, s: &str) -> Result {
1854 self.buf.write_str(s)
1857 fn write_char(&mut self, c: char) -> Result {
1858 self.buf.write_char(c)
1861 fn write_fmt(&mut self, args: Arguments) -> Result {
1862 write(self.buf, args)
1866 #[stable(feature = "rust1", since = "1.0.0")]
1867 impl Display for Error {
1868 fn fmt(&self, f: &mut Formatter) -> Result {
1869 Display::fmt("an error occurred when formatting an argument", f)
1873 // Implementations of the core formatting traits
1875 macro_rules! fmt_refs {
1876 ($($tr:ident),*) => {
1878 #[stable(feature = "rust1", since = "1.0.0")]
1879 impl<T: ?Sized + $tr> $tr for &T {
1880 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 impl<T: ?Sized + $tr> $tr for &mut T {
1884 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1890 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1892 #[unstable(feature = "never_type", issue = "35121")]
1894 fn fmt(&self, _: &mut Formatter) -> Result {
1899 #[unstable(feature = "never_type", issue = "35121")]
1900 impl Display for ! {
1901 fn fmt(&self, _: &mut Formatter) -> Result {
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 impl Debug for bool {
1909 fn fmt(&self, f: &mut Formatter) -> Result {
1910 Display::fmt(self, f)
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 impl Display for bool {
1916 fn fmt(&self, f: &mut Formatter) -> Result {
1917 Display::fmt(if *self { "true" } else { "false" }, f)
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl Debug for str {
1923 fn fmt(&self, f: &mut Formatter) -> Result {
1926 for (i, c) in self.char_indices() {
1927 let esc = c.escape_debug();
1928 // If char needs escaping, flush backlog so far and write, else skip
1930 f.write_str(&self[from..i])?;
1934 from = i + c.len_utf8();
1937 f.write_str(&self[from..])?;
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 impl Display for str {
1944 fn fmt(&self, f: &mut Formatter) -> Result {
1949 #[stable(feature = "rust1", since = "1.0.0")]
1950 impl Debug for char {
1951 fn fmt(&self, f: &mut Formatter) -> Result {
1952 f.write_char('\'')?;
1953 for c in self.escape_debug() {
1960 #[stable(feature = "rust1", since = "1.0.0")]
1961 impl Display for char {
1962 fn fmt(&self, f: &mut Formatter) -> Result {
1963 if f.width.is_none() && f.precision.is_none() {
1966 f.pad(self.encode_utf8(&mut [0; 4]))
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 impl<T: ?Sized> Pointer for *const T {
1973 fn fmt(&self, f: &mut Formatter) -> Result {
1974 let old_width = f.width;
1975 let old_flags = f.flags;
1977 // The alternate flag is already treated by LowerHex as being special-
1978 // it denotes whether to prefix with 0x. We use it to work out whether
1979 // or not to zero extend, and then unconditionally set it to get the
1982 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1984 if let None = f.width {
1985 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
1988 f.flags |= 1 << (FlagV1::Alternate as u32);
1990 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
1992 f.width = old_width;
1993 f.flags = old_flags;
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 impl<T: ?Sized> Pointer for *mut T {
2001 fn fmt(&self, f: &mut Formatter) -> Result {
2002 Pointer::fmt(&(*self as *const T), f)
2006 #[stable(feature = "rust1", since = "1.0.0")]
2007 impl<T: ?Sized> Pointer for &T {
2008 fn fmt(&self, f: &mut Formatter) -> Result {
2009 Pointer::fmt(&(*self as *const T), f)
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl<T: ?Sized> Pointer for &mut T {
2015 fn fmt(&self, f: &mut Formatter) -> Result {
2016 Pointer::fmt(&(&**self as *const T), f)
2020 // Implementation of Display/Debug for various core types
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 impl<T: ?Sized> Debug for *const T {
2024 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2026 #[stable(feature = "rust1", since = "1.0.0")]
2027 impl<T: ?Sized> Debug for *mut T {
2028 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2032 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2035 macro_rules! tuple {
2037 ( $($name:ident,)+ ) => (
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
2040 #[allow(non_snake_case, unused_assignments, deprecated)]
2041 fn fmt(&self, f: &mut Formatter) -> Result {
2042 let mut builder = f.debug_tuple("");
2043 let ($(ref $name,)*) = *self;
2045 builder.field(&$name);
2051 peel! { $($name,)* }
2055 macro_rules! last_type {
2056 ($a:ident,) => { $a };
2057 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2060 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2062 #[stable(feature = "rust1", since = "1.0.0")]
2063 impl<T: Debug> Debug for [T] {
2064 fn fmt(&self, f: &mut Formatter) -> Result {
2065 f.debug_list().entries(self.iter()).finish()
2069 #[stable(feature = "rust1", since = "1.0.0")]
2072 fn fmt(&self, f: &mut Formatter) -> Result {
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 impl<T: ?Sized> Debug for PhantomData<T> {
2078 fn fmt(&self, f: &mut Formatter) -> Result {
2079 f.pad("PhantomData")
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 impl<T: Copy + Debug> Debug for Cell<T> {
2085 fn fmt(&self, f: &mut Formatter) -> Result {
2086 f.debug_struct("Cell")
2087 .field("value", &self.get())
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2094 fn fmt(&self, f: &mut Formatter) -> Result {
2095 match self.try_borrow() {
2097 f.debug_struct("RefCell")
2098 .field("value", &borrow)
2102 // The RefCell is mutably borrowed so we can't look at its value
2103 // here. Show a placeholder instead.
2104 struct BorrowedPlaceholder;
2106 impl Debug for BorrowedPlaceholder {
2107 fn fmt(&self, f: &mut Formatter) -> Result {
2108 f.write_str("<borrowed>")
2112 f.debug_struct("RefCell")
2113 .field("value", &BorrowedPlaceholder)
2120 #[stable(feature = "rust1", since = "1.0.0")]
2121 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2122 fn fmt(&self, f: &mut Formatter) -> Result {
2123 Debug::fmt(&**self, f)
2127 #[stable(feature = "rust1", since = "1.0.0")]
2128 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2129 fn fmt(&self, f: &mut Formatter) -> Result {
2130 Debug::fmt(&*(self.deref()), f)
2134 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2135 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2136 fn fmt(&self, f: &mut Formatter) -> Result {
2141 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
2142 // it's a lot easier than creating all of the rt::Piece structures here.