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 /// 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(),
1009 let mut pieces = args.pieces.iter();
1013 // We can use default formatting parameters for all arguments.
1014 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
1015 formatter.buf.write_str(*piece)?;
1016 (arg.formatter)(arg.value, &mut formatter)?;
1020 // Every spec has a corresponding argument that is preceded by
1022 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
1023 formatter.buf.write_str(*piece)?;
1024 formatter.run(arg)?;
1029 // There can be only one trailing string piece left.
1030 if let Some(piece) = pieces.next() {
1031 formatter.buf.write_str(*piece)?;
1037 impl<'a> Formatter<'a> {
1038 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1039 where 'b: 'c, F: FnOnce(&'b mut (dyn Write+'b)) -> &'c mut (dyn Write+'c)
1042 // We want to change this
1043 buf: wrap(self.buf),
1045 // And preserve these
1050 precision: self.precision,
1052 // These only exist in the struct for the `run` method,
1053 // which won’t be used together with this method.
1054 curarg: self.curarg.clone(),
1059 // First up is the collection of functions used to execute a format string
1060 // at runtime. This consumes all of the compile-time statics generated by
1061 // the format! syntax extension.
1062 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1063 // Fill in the format parameters into the formatter
1064 self.fill = arg.format.fill;
1065 self.align = arg.format.align;
1066 self.flags = arg.format.flags;
1067 self.width = self.getcount(&arg.format.width);
1068 self.precision = self.getcount(&arg.format.precision);
1070 // Extract the correct argument
1071 let value = match arg.position {
1072 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1073 rt::v1::Position::At(i) => self.args[i],
1076 // Then actually do some printing
1077 (value.formatter)(value.value, self)
1080 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1082 rt::v1::Count::Is(n) => Some(n),
1083 rt::v1::Count::Implied => None,
1084 rt::v1::Count::Param(i) => {
1085 self.args[i].as_usize()
1087 rt::v1::Count::NextParam => {
1088 self.curarg.next()?.as_usize()
1093 // Helper methods used for padding and processing formatting arguments that
1094 // all formatting traits can use.
1096 /// Performs the correct padding for an integer which has already been
1097 /// emitted into a str. The str should *not* contain the sign for the
1098 /// integer, that will be added by this method.
1102 /// * is_nonnegative - whether the original integer was either positive or zero.
1103 /// * prefix - if the '#' character (Alternate) is provided, this
1104 /// is the prefix to put in front of the number.
1105 /// * buf - the byte array that the number has been formatted into
1107 /// This function will correctly account for the flags provided as well as
1108 /// the minimum width. It will not take precision into account.
1115 /// struct Foo { nb: i32 };
1118 /// fn new(nb: i32) -> Foo {
1125 /// impl fmt::Display for Foo {
1126 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1127 /// // We need to remove "-" from the number output.
1128 /// let tmp = self.nb.abs().to_string();
1130 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1134 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1135 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1136 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1137 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 pub fn pad_integral(&mut self,
1141 is_nonnegative: bool,
1145 let mut width = buf.len();
1147 let mut sign = None;
1148 if !is_nonnegative {
1149 sign = Some('-'); width += 1;
1150 } else if self.sign_plus() {
1151 sign = Some('+'); width += 1;
1154 let prefixed = self.alternate();
1156 width += prefix.chars().count();
1159 // Writes the sign if it exists, and then the prefix if it was requested
1160 let write_prefix = |f: &mut Formatter| {
1161 if let Some(c) = sign {
1162 f.buf.write_char(c)?;
1164 if prefixed { f.buf.write_str(prefix) }
1168 // The `width` field is more of a `min-width` parameter at this point.
1170 // If there's no minimum length requirements then we can just
1173 write_prefix(self)?; self.buf.write_str(buf)
1175 // Check if we're over the minimum width, if so then we can also
1176 // just write the bytes.
1177 Some(min) if width >= min => {
1178 write_prefix(self)?; self.buf.write_str(buf)
1180 // The sign and prefix goes before the padding if the fill character
1182 Some(min) if self.sign_aware_zero_pad() => {
1184 self.align = rt::v1::Alignment::Right;
1185 write_prefix(self)?;
1186 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1187 f.buf.write_str(buf)
1190 // Otherwise, the sign and prefix goes after the padding
1192 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1193 write_prefix(f)?; f.buf.write_str(buf)
1199 /// This function takes a string slice and emits it to the internal buffer
1200 /// after applying the relevant formatting flags specified. The flags
1201 /// recognized for generic strings are:
1203 /// * width - the minimum width of what to emit
1204 /// * fill/align - what to emit and where to emit it if the string
1205 /// provided needs to be padded
1206 /// * precision - the maximum length to emit, the string is truncated if it
1207 /// is longer than this length
1209 /// Notably this function ignores the `flag` parameters.
1218 /// impl fmt::Display for Foo {
1219 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1220 /// formatter.pad("Foo")
1224 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1225 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 pub fn pad(&mut self, s: &str) -> Result {
1229 // Make sure there's a fast path up front
1230 if self.width.is_none() && self.precision.is_none() {
1231 return self.buf.write_str(s);
1233 // The `precision` field can be interpreted as a `max-width` for the
1234 // string being formatted.
1235 let s = if let Some(max) = self.precision {
1236 // If our string is longer that the precision, then we must have
1237 // truncation. However other flags like `fill`, `width` and `align`
1238 // must act as always.
1239 if let Some((i, _)) = s.char_indices().nth(max) {
1240 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1241 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1242 // `unsafe` and otherwise don't emit any panic-related code
1244 s.get(..i).unwrap_or(&s)
1251 // The `width` field is more of a `min-width` parameter at this point.
1253 // If we're under the maximum length, and there's no minimum length
1254 // requirements, then we can just emit the string
1255 None => self.buf.write_str(s),
1256 // If we're under the maximum width, check if we're over the minimum
1257 // width, if so it's as easy as just emitting the string.
1258 Some(width) if s.chars().count() >= width => {
1259 self.buf.write_str(s)
1261 // If we're under both the maximum and the minimum width, then fill
1262 // up the minimum width with the specified string + some alignment.
1264 let align = rt::v1::Alignment::Left;
1265 self.with_padding(width - s.chars().count(), align, |me| {
1272 /// Runs a callback, emitting the correct padding either before or
1273 /// afterwards depending on whether right or left alignment is requested.
1274 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1276 where F: FnOnce(&mut Formatter) -> Result,
1278 let align = match self.align {
1279 rt::v1::Alignment::Unknown => default,
1283 let (pre_pad, post_pad) = match align {
1284 rt::v1::Alignment::Left => (0, padding),
1285 rt::v1::Alignment::Right |
1286 rt::v1::Alignment::Unknown => (padding, 0),
1287 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1290 let mut fill = [0; 4];
1291 let fill = self.fill.encode_utf8(&mut fill);
1293 for _ in 0..pre_pad {
1294 self.buf.write_str(fill)?;
1299 for _ in 0..post_pad {
1300 self.buf.write_str(fill)?;
1306 /// Takes the formatted parts and applies the padding.
1307 /// Assumes that the caller already has rendered the parts with required precision,
1308 /// so that `self.precision` can be ignored.
1309 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1310 if let Some(mut width) = self.width {
1311 // for the sign-aware zero padding, we render the sign first and
1312 // behave as if we had no sign from the beginning.
1313 let mut formatted = formatted.clone();
1314 let old_fill = self.fill;
1315 let old_align = self.align;
1316 let mut align = old_align;
1317 if self.sign_aware_zero_pad() {
1318 // a sign always goes first
1319 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1320 self.buf.write_str(sign)?;
1322 // remove the sign from the formatted parts
1323 formatted.sign = b"";
1324 width = width.saturating_sub(sign.len());
1325 align = rt::v1::Alignment::Right;
1327 self.align = rt::v1::Alignment::Right;
1330 // remaining parts go through the ordinary padding process.
1331 let len = formatted.len();
1332 let ret = if width <= len { // no padding
1333 self.write_formatted_parts(&formatted)
1335 self.with_padding(width - len, align, |f| {
1336 f.write_formatted_parts(&formatted)
1339 self.fill = old_fill;
1340 self.align = old_align;
1343 // this is the common case and we take a shortcut
1344 self.write_formatted_parts(formatted)
1348 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1349 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1350 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1353 if !formatted.sign.is_empty() {
1354 write_bytes(self.buf, formatted.sign)?;
1356 for part in formatted.parts {
1358 flt2dec::Part::Zero(mut nzeroes) => {
1359 const ZEROES: &str = // 64 zeroes
1360 "0000000000000000000000000000000000000000000000000000000000000000";
1361 while nzeroes > ZEROES.len() {
1362 self.buf.write_str(ZEROES)?;
1363 nzeroes -= ZEROES.len();
1366 self.buf.write_str(&ZEROES[..nzeroes])?;
1369 flt2dec::Part::Num(mut v) => {
1371 let len = part.len();
1372 for c in s[..len].iter_mut().rev() {
1373 *c = b'0' + (v % 10) as u8;
1376 write_bytes(self.buf, &s[..len])?;
1378 flt2dec::Part::Copy(buf) => {
1379 write_bytes(self.buf, buf)?;
1386 /// Writes some data to the underlying buffer contained within this
1396 /// impl fmt::Display for Foo {
1397 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1398 /// formatter.write_str("Foo")
1399 /// // This is equivalent to:
1400 /// // write!(formatter, "Foo")
1404 /// assert_eq!(&format!("{}", Foo), "Foo");
1405 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 pub fn write_str(&mut self, data: &str) -> Result {
1409 self.buf.write_str(data)
1412 /// Writes some formatted information into this instance.
1419 /// struct Foo(i32);
1421 /// impl fmt::Display for Foo {
1422 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1423 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1427 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1428 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1432 write(self.buf, fmt)
1435 /// Flags for formatting
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 #[rustc_deprecated(since = "1.24.0",
1438 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1439 or `sign_aware_zero_pad` methods instead")]
1440 pub fn flags(&self) -> u32 { self.flags }
1442 /// Character used as 'fill' whenever there is alignment.
1451 /// impl fmt::Display for Foo {
1452 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1453 /// let c = formatter.fill();
1454 /// if let Some(width) = formatter.width() {
1455 /// for _ in 0..width {
1456 /// write!(formatter, "{}", c)?;
1460 /// write!(formatter, "{}", c)
1465 /// // We set alignment to the left with ">".
1466 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1467 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1469 #[stable(feature = "fmt_flags", since = "1.5.0")]
1470 pub fn fill(&self) -> char { self.fill }
1472 /// Flag indicating what form of alignment was requested.
1477 /// extern crate core;
1479 /// use std::fmt::{self, Alignment};
1483 /// impl fmt::Display for Foo {
1484 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1485 /// let s = if let Some(s) = formatter.align() {
1487 /// Alignment::Left => "left",
1488 /// Alignment::Right => "right",
1489 /// Alignment::Center => "center",
1494 /// write!(formatter, "{}", s)
1499 /// assert_eq!(&format!("{:<}", Foo), "left");
1500 /// assert_eq!(&format!("{:>}", Foo), "right");
1501 /// assert_eq!(&format!("{:^}", Foo), "center");
1502 /// assert_eq!(&format!("{}", Foo), "into the void");
1505 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1506 pub fn align(&self) -> Option<Alignment> {
1508 rt::v1::Alignment::Left => Some(Alignment::Left),
1509 rt::v1::Alignment::Right => Some(Alignment::Right),
1510 rt::v1::Alignment::Center => Some(Alignment::Center),
1511 rt::v1::Alignment::Unknown => None,
1515 /// Optionally specified integer width that the output should be.
1522 /// struct Foo(i32);
1524 /// impl fmt::Display for Foo {
1525 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1526 /// if let Some(width) = formatter.width() {
1527 /// // If we received a width, we use it
1528 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1530 /// // Otherwise we do nothing special
1531 /// write!(formatter, "Foo({})", self.0)
1536 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1537 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1539 #[stable(feature = "fmt_flags", since = "1.5.0")]
1540 pub fn width(&self) -> Option<usize> { self.width }
1542 /// Optionally specified precision for numeric types.
1549 /// struct Foo(f32);
1551 /// impl fmt::Display for Foo {
1552 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1553 /// if let Some(precision) = formatter.precision() {
1554 /// // If we received a precision, we use it.
1555 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1557 /// // Otherwise we default to 2.
1558 /// write!(formatter, "Foo({:.2})", self.0)
1563 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1564 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1566 #[stable(feature = "fmt_flags", since = "1.5.0")]
1567 pub fn precision(&self) -> Option<usize> { self.precision }
1569 /// Determines if the `+` flag was specified.
1576 /// struct Foo(i32);
1578 /// impl fmt::Display for Foo {
1579 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1580 /// if formatter.sign_plus() {
1581 /// write!(formatter,
1583 /// if self.0 < 0 { '-' } else { '+' },
1586 /// write!(formatter, "Foo({})", self.0)
1591 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1592 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1594 #[stable(feature = "fmt_flags", since = "1.5.0")]
1595 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1597 /// Determines if the `-` flag was specified.
1604 /// struct Foo(i32);
1606 /// impl fmt::Display for Foo {
1607 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1608 /// if formatter.sign_minus() {
1609 /// // You want a minus sign? Have one!
1610 /// write!(formatter, "-Foo({})", self.0)
1612 /// write!(formatter, "Foo({})", self.0)
1617 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1618 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1620 #[stable(feature = "fmt_flags", since = "1.5.0")]
1621 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1623 /// Determines if the `#` flag was specified.
1630 /// struct Foo(i32);
1632 /// impl fmt::Display for Foo {
1633 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1634 /// if formatter.alternate() {
1635 /// write!(formatter, "Foo({})", self.0)
1637 /// write!(formatter, "{}", self.0)
1642 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1643 /// assert_eq!(&format!("{}", Foo(23)), "23");
1645 #[stable(feature = "fmt_flags", since = "1.5.0")]
1646 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1648 /// Determines if the `0` flag was specified.
1655 /// struct Foo(i32);
1657 /// impl fmt::Display for Foo {
1658 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1659 /// assert!(formatter.sign_aware_zero_pad());
1660 /// assert_eq!(formatter.width(), Some(4));
1661 /// // We ignore the formatter's options.
1662 /// write!(formatter, "{}", self.0)
1666 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1668 #[stable(feature = "fmt_flags", since = "1.5.0")]
1669 pub fn sign_aware_zero_pad(&self) -> bool {
1670 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1673 // FIXME: Decide what public API we want for these two flags.
1674 // https://github.com/rust-lang/rust/issues/48584
1675 fn debug_lower_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0 }
1677 fn debug_upper_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0 }
1679 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1680 /// [`fmt::Debug`] implementations for structs.
1682 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1683 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1689 /// use std::net::Ipv4Addr;
1697 /// impl fmt::Debug for Foo {
1698 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1699 /// fmt.debug_struct("Foo")
1700 /// .field("bar", &self.bar)
1701 /// .field("baz", &self.baz)
1702 /// .field("addr", &format_args!("{}", self.addr))
1708 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1709 /// format!("{:?}", Foo {
1711 /// baz: "Hello World".to_string(),
1712 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1716 #[stable(feature = "debug_builders", since = "1.2.0")]
1717 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1718 builders::debug_struct_new(self, name)
1721 /// Creates a `DebugTuple` builder designed to assist with creation of
1722 /// `fmt::Debug` implementations for tuple structs.
1728 /// use std::marker::PhantomData;
1730 /// struct Foo<T>(i32, String, PhantomData<T>);
1732 /// impl<T> fmt::Debug for Foo<T> {
1733 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1734 /// fmt.debug_tuple("Foo")
1737 /// .field(&format_args!("_"))
1743 /// "Foo(10, \"Hello\", _)",
1744 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1747 #[stable(feature = "debug_builders", since = "1.2.0")]
1748 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1749 builders::debug_tuple_new(self, name)
1752 /// Creates a `DebugList` builder designed to assist with creation of
1753 /// `fmt::Debug` implementations for list-like structures.
1760 /// struct Foo(Vec<i32>);
1762 /// impl fmt::Debug for Foo {
1763 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1764 /// fmt.debug_list().entries(self.0.iter()).finish()
1768 /// // prints "[10, 11]"
1769 /// println!("{:?}", Foo(vec![10, 11]));
1771 #[stable(feature = "debug_builders", since = "1.2.0")]
1772 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1773 builders::debug_list_new(self)
1776 /// Creates a `DebugSet` builder designed to assist with creation of
1777 /// `fmt::Debug` implementations for set-like structures.
1784 /// struct Foo(Vec<i32>);
1786 /// impl fmt::Debug for Foo {
1787 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1788 /// fmt.debug_set().entries(self.0.iter()).finish()
1792 /// // prints "{10, 11}"
1793 /// println!("{:?}", Foo(vec![10, 11]));
1796 /// [`format_args!`]: ../../std/macro.format_args.html
1798 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1799 /// to build a list of match arms:
1804 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1805 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1807 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1809 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1811 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1812 /// L::fmt(&(self.0).0, fmt)?;
1813 /// fmt.write_str(" => ")?;
1814 /// R::fmt(&(self.0).1, fmt)
1818 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1820 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1822 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1824 /// .entries(self.0.iter().map(Arm))
1825 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1830 #[stable(feature = "debug_builders", since = "1.2.0")]
1831 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1832 builders::debug_set_new(self)
1835 /// Creates a `DebugMap` builder designed to assist with creation of
1836 /// `fmt::Debug` implementations for map-like structures.
1843 /// struct Foo(Vec<(String, i32)>);
1845 /// impl fmt::Debug for Foo {
1846 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1847 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1851 /// // prints "{"A": 10, "B": 11}"
1852 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1854 #[stable(feature = "debug_builders", since = "1.2.0")]
1855 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1856 builders::debug_map_new(self)
1860 #[stable(since = "1.2.0", feature = "formatter_write")]
1861 impl Write for Formatter<'_> {
1862 fn write_str(&mut self, s: &str) -> Result {
1863 self.buf.write_str(s)
1866 fn write_char(&mut self, c: char) -> Result {
1867 self.buf.write_char(c)
1870 fn write_fmt(&mut self, args: Arguments) -> Result {
1871 write(self.buf, args)
1875 #[stable(feature = "rust1", since = "1.0.0")]
1876 impl Display for Error {
1877 fn fmt(&self, f: &mut Formatter) -> Result {
1878 Display::fmt("an error occurred when formatting an argument", f)
1882 // Implementations of the core formatting traits
1884 macro_rules! fmt_refs {
1885 ($($tr:ident),*) => {
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 impl<T: ?Sized + $tr> $tr for &T {
1889 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 impl<T: ?Sized + $tr> $tr for &mut T {
1893 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1899 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1901 #[unstable(feature = "never_type", issue = "35121")]
1903 fn fmt(&self, _: &mut Formatter) -> Result {
1908 #[unstable(feature = "never_type", issue = "35121")]
1909 impl Display for ! {
1910 fn fmt(&self, _: &mut Formatter) -> Result {
1915 #[stable(feature = "rust1", since = "1.0.0")]
1916 impl Debug for bool {
1918 fn fmt(&self, f: &mut Formatter) -> Result {
1919 Display::fmt(self, f)
1923 #[stable(feature = "rust1", since = "1.0.0")]
1924 impl Display for bool {
1925 fn fmt(&self, f: &mut Formatter) -> Result {
1926 Display::fmt(if *self { "true" } else { "false" }, f)
1930 #[stable(feature = "rust1", since = "1.0.0")]
1931 impl Debug for str {
1932 fn fmt(&self, f: &mut Formatter) -> Result {
1935 for (i, c) in self.char_indices() {
1936 let esc = c.escape_debug();
1937 // If char needs escaping, flush backlog so far and write, else skip
1939 f.write_str(&self[from..i])?;
1943 from = i + c.len_utf8();
1946 f.write_str(&self[from..])?;
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 impl Display for str {
1953 fn fmt(&self, f: &mut Formatter) -> Result {
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 impl Debug for char {
1960 fn fmt(&self, f: &mut Formatter) -> Result {
1961 f.write_char('\'')?;
1962 for c in self.escape_debug() {
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl Display for char {
1971 fn fmt(&self, f: &mut Formatter) -> Result {
1972 if f.width.is_none() && f.precision.is_none() {
1975 f.pad(self.encode_utf8(&mut [0; 4]))
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 impl<T: ?Sized> Pointer for *const T {
1982 fn fmt(&self, f: &mut Formatter) -> Result {
1983 let old_width = f.width;
1984 let old_flags = f.flags;
1986 // The alternate flag is already treated by LowerHex as being special-
1987 // it denotes whether to prefix with 0x. We use it to work out whether
1988 // or not to zero extend, and then unconditionally set it to get the
1991 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1993 if let None = f.width {
1994 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
1997 f.flags |= 1 << (FlagV1::Alternate as u32);
1999 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2001 f.width = old_width;
2002 f.flags = old_flags;
2008 #[stable(feature = "rust1", since = "1.0.0")]
2009 impl<T: ?Sized> Pointer for *mut T {
2010 fn fmt(&self, f: &mut Formatter) -> Result {
2011 Pointer::fmt(&(*self as *const T), f)
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 impl<T: ?Sized> Pointer for &T {
2017 fn fmt(&self, f: &mut Formatter) -> Result {
2018 Pointer::fmt(&(*self as *const T), f)
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 impl<T: ?Sized> Pointer for &mut T {
2024 fn fmt(&self, f: &mut Formatter) -> Result {
2025 Pointer::fmt(&(&**self as *const T), f)
2029 // Implementation of Display/Debug for various core types
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 impl<T: ?Sized> Debug for *const T {
2033 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2035 #[stable(feature = "rust1", since = "1.0.0")]
2036 impl<T: ?Sized> Debug for *mut T {
2037 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2041 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2044 macro_rules! tuple {
2046 ( $($name:ident,)+ ) => (
2047 #[stable(feature = "rust1", since = "1.0.0")]
2048 impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
2049 #[allow(non_snake_case, unused_assignments, deprecated)]
2050 fn fmt(&self, f: &mut Formatter) -> Result {
2051 let mut builder = f.debug_tuple("");
2052 let ($(ref $name,)*) = *self;
2054 builder.field(&$name);
2060 peel! { $($name,)* }
2064 macro_rules! last_type {
2065 ($a:ident,) => { $a };
2066 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2069 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2071 #[stable(feature = "rust1", since = "1.0.0")]
2072 impl<T: Debug> Debug for [T] {
2073 fn fmt(&self, f: &mut Formatter) -> Result {
2074 f.debug_list().entries(self.iter()).finish()
2078 #[stable(feature = "rust1", since = "1.0.0")]
2081 fn fmt(&self, f: &mut Formatter) -> Result {
2085 #[stable(feature = "rust1", since = "1.0.0")]
2086 impl<T: ?Sized> Debug for PhantomData<T> {
2087 fn fmt(&self, f: &mut Formatter) -> Result {
2088 f.pad("PhantomData")
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 impl<T: Copy + Debug> Debug for Cell<T> {
2094 fn fmt(&self, f: &mut Formatter) -> Result {
2095 f.debug_struct("Cell")
2096 .field("value", &self.get())
2101 #[stable(feature = "rust1", since = "1.0.0")]
2102 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2103 fn fmt(&self, f: &mut Formatter) -> Result {
2104 match self.try_borrow() {
2106 f.debug_struct("RefCell")
2107 .field("value", &borrow)
2111 // The RefCell is mutably borrowed so we can't look at its value
2112 // here. Show a placeholder instead.
2113 struct BorrowedPlaceholder;
2115 impl Debug for BorrowedPlaceholder {
2116 fn fmt(&self, f: &mut Formatter) -> Result {
2117 f.write_str("<borrowed>")
2121 f.debug_struct("RefCell")
2122 .field("value", &BorrowedPlaceholder)
2129 #[stable(feature = "rust1", since = "1.0.0")]
2130 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2131 fn fmt(&self, f: &mut Formatter) -> Result {
2132 Debug::fmt(&**self, f)
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2138 fn fmt(&self, f: &mut Formatter) -> Result {
2139 Debug::fmt(&*(self.deref()), f)
2143 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2144 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2145 fn fmt(&self, f: &mut Formatter) -> Result {
2150 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
2151 // it's a lot easier than creating all of the rt::Piece structures here.