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, args: Arguments) -> Result {
195 // This Adapter is needed to allow `self` (of type `&mut
196 // Self`) to be cast to a Write (below) without
197 // requiring a `Sized` bound.
198 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
200 impl<T: ?Sized> Write for Adapter<'_, T>
203 fn write_str(&mut self, s: &str) -> Result {
207 fn write_char(&mut self, c: char) -> Result {
211 fn write_fmt(&mut self, args: Arguments) -> Result {
212 self.0.write_fmt(args)
216 write(&mut Adapter(self), args)
220 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
221 impl<W: Write + ?Sized> Write for &mut W {
222 fn write_str(&mut self, s: &str) -> Result {
223 (**self).write_str(s)
226 fn write_char(&mut self, c: char) -> Result {
227 (**self).write_char(c)
230 fn write_fmt(&mut self, args: Arguments) -> Result {
231 (**self).write_fmt(args)
235 /// A struct to represent both where to emit formatting strings to and how they
236 /// should be formatted. A mutable version of this is passed to all formatting
238 #[allow(missing_debug_implementations)]
239 #[stable(feature = "rust1", since = "1.0.0")]
240 pub struct Formatter<'a> {
243 align: rt::v1::Alignment,
244 width: Option<usize>,
245 precision: Option<usize>,
247 buf: &'a mut (dyn Write+'a),
248 curarg: slice::Iter<'a, ArgumentV1<'a>>,
249 args: &'a [ArgumentV1<'a>],
252 // NB. Argument is essentially an optimized partially applied formatting function,
253 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
257 /// Erases all oibits, because `Void` erases the type of the object that
258 /// will be used to produce formatted output. Since we do not know what
259 /// oibits the real types have (and they can have any or none), we need to
260 /// take the most conservative approach and forbid all oibits.
262 /// It was added after #45197 showed that one could share a `!Sync`
263 /// object across threads by passing it into `format_args!`.
264 _oibit_remover: PhantomData<*mut dyn Fn()>,
267 /// This struct represents the generic "argument" which is taken by the Xprintf
268 /// family of functions. It contains a function to format the given value. At
269 /// compile time it is ensured that the function and the value have the correct
270 /// types, and then this struct is used to canonicalize arguments to one type.
272 #[allow(missing_debug_implementations)]
273 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
276 pub struct ArgumentV1<'a> {
278 formatter: fn(&Void, &mut Formatter) -> Result,
281 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
283 impl Clone for ArgumentV1<'_> {
284 fn clone(&self) -> Self {
289 impl<'a> ArgumentV1<'a> {
291 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
296 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
298 pub fn new<'b, T>(x: &'b T,
299 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
302 formatter: mem::transmute(f),
303 value: mem::transmute(x)
309 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
311 pub fn from_usize(x: &usize) -> ArgumentV1 {
312 ArgumentV1::new(x, ArgumentV1::show_usize)
315 fn as_usize(&self) -> Option<usize> {
316 if self.formatter as usize == ArgumentV1::show_usize as usize {
317 Some(unsafe { *(self.value as *const _ as *const usize) })
324 // flags available in the v1 format of format_args
325 #[derive(Copy, Clone)]
326 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, DebugLowerHex, DebugUpperHex }
328 impl<'a> Arguments<'a> {
329 /// When using the format_args!() macro, this function is used to generate the
330 /// Arguments structure.
331 #[doc(hidden)] #[inline]
332 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
334 pub fn new_v1(pieces: &'a [&'a str],
335 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
343 /// This function is used to specify nonstandard formatting parameters.
344 /// The `pieces` array must be at least as long as `fmt` to construct
345 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
346 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
347 /// created with `argumentusize`. However, failing to do so doesn't cause
348 /// unsafety, but will ignore invalid .
349 #[doc(hidden)] #[inline]
350 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
352 pub fn new_v1_formatted(pieces: &'a [&'a str],
353 args: &'a [ArgumentV1<'a>],
354 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
362 /// Estimates the length of the formatted text.
364 /// This is intended to be used for setting initial `String` capacity
365 /// when using `format!`. Note: this is neither the lower nor upper bound.
366 #[doc(hidden)] #[inline]
367 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
369 pub fn estimated_capacity(&self) -> usize {
370 let pieces_length: usize = self.pieces.iter()
371 .map(|x| x.len()).sum();
373 if self.args.is_empty() {
375 } else if self.pieces[0] == "" && pieces_length < 16 {
376 // If the format string starts with an argument,
377 // don't preallocate anything, unless length
378 // of pieces is significant.
381 // There are some arguments, so any additional push
382 // will reallocate the string. To avoid that,
383 // we're "pre-doubling" the capacity here.
384 pieces_length.checked_mul(2).unwrap_or(0)
389 /// This structure represents a safely precompiled version of a format string
390 /// and its arguments. This cannot be generated at runtime because it cannot
391 /// safely be done, so no constructors are given and the fields are private
392 /// to prevent modification.
394 /// The [`format_args!`] macro will safely create an instance of this structure.
395 /// The macro validates the format string at compile-time so usage of the
396 /// [`write`] and [`format`] functions can be safely performed.
398 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
399 /// and `Display` contexts as seen below. The example also shows that `Debug`
400 /// and `Display` format to the same thing: the interpolated format string
401 /// in `format_args!`.
404 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
405 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
406 /// assert_eq!("1 foo 2", display);
407 /// assert_eq!(display, debug);
410 /// [`format_args!`]: ../../std/macro.format_args.html
411 /// [`format`]: ../../std/fmt/fn.format.html
412 /// [`write`]: ../../std/fmt/fn.write.html
413 #[stable(feature = "rust1", since = "1.0.0")]
414 #[derive(Copy, Clone)]
415 pub struct Arguments<'a> {
416 // Format string pieces to print.
417 pieces: &'a [&'a str],
419 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
420 fmt: Option<&'a [rt::v1::Argument]>,
422 // Dynamic arguments for interpolation, to be interleaved with string
423 // pieces. (Every argument is preceded by a string piece.)
424 args: &'a [ArgumentV1<'a>],
427 #[stable(feature = "rust1", since = "1.0.0")]
428 impl Debug for Arguments<'_> {
429 fn fmt(&self, fmt: &mut Formatter) -> Result {
430 Display::fmt(self, fmt)
434 #[stable(feature = "rust1", since = "1.0.0")]
435 impl Display for Arguments<'_> {
436 fn fmt(&self, fmt: &mut Formatter) -> Result {
437 write(fmt.buf, *self)
443 /// `Debug` should format the output in a programmer-facing, debugging context.
445 /// Generally speaking, you should just `derive` a `Debug` implementation.
447 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
449 /// For more information on formatters, see [the module-level documentation][module].
451 /// [module]: ../../std/fmt/index.html
453 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
454 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
455 /// comma-separated list of each field's name and `Debug` value, then `}`. For
456 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
457 /// `Debug` values of the fields, then `)`.
461 /// Deriving an implementation:
470 /// let origin = Point { x: 0, y: 0 };
472 /// println!("The origin is: {:?}", origin);
475 /// Manually implementing:
485 /// impl fmt::Debug for Point {
486 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
487 /// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
491 /// let origin = Point { x: 0, y: 0 };
493 /// println!("The origin is: {:?}", origin);
499 /// The origin is: Point { x: 0, y: 0 }
502 /// There are a number of `debug_*` methods on [`Formatter`] to help you with manual
503 /// implementations, such as [`debug_struct`][debug_struct].
505 /// `Debug` implementations using either `derive` or the debug builder API
506 /// on [`Formatter`] support pretty printing using the alternate flag: `{:#?}`.
508 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
509 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
511 /// Pretty printing with `#?`:
520 /// let origin = Point { x: 0, y: 0 };
522 /// println!("The origin is: {:#?}", origin);
528 /// The origin is: Point {
533 #[stable(feature = "rust1", since = "1.0.0")]
534 #[rustc_on_unimplemented(
535 on(crate_local, label="`{Self}` cannot be formatted using `{{:?}}`",
536 note="add `#[derive(Debug)]` or manually implement `{Debug}`"),
537 message="`{Self}` doesn't implement `{Debug}`",
538 label="`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`",
540 #[doc(alias = "{:?}")]
541 #[lang = "debug_trait"]
543 /// Formats the value using the given formatter.
550 /// struct Position {
555 /// impl fmt::Debug for Position {
556 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
557 /// write!(f, "({:?}, {:?})", self.longitude, self.latitude)
561 /// assert_eq!("(1.987, 2.983)".to_owned(),
562 /// format!("{:?}", Position { longitude: 1.987, latitude: 2.983, }));
564 #[stable(feature = "rust1", since = "1.0.0")]
565 fn fmt(&self, f: &mut Formatter) -> Result;
568 /// Format trait for an empty format, `{}`.
570 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
571 /// output, and so cannot be derived.
573 /// [debug]: trait.Debug.html
575 /// For more information on formatters, see [the module-level documentation][module].
577 /// [module]: ../../std/fmt/index.html
581 /// Implementing `Display` on a type:
591 /// impl fmt::Display for Point {
592 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
593 /// write!(f, "({}, {})", self.x, self.y)
597 /// let origin = Point { x: 0, y: 0 };
599 /// println!("The origin is: {}", origin);
601 #[rustc_on_unimplemented(
603 _Self="std::path::Path",
604 label="`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
605 note="call `.display()` or `.to_string_lossy()` to safely print paths, \
606 as they may contain non-Unicode data"
608 message="`{Self}` doesn't implement `{Display}`",
609 label="`{Self}` cannot be formatted with the default formatter",
610 note="in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead",
613 #[stable(feature = "rust1", since = "1.0.0")]
615 /// Formats the value using the given formatter.
622 /// struct Position {
627 /// impl fmt::Display for Position {
628 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
629 /// write!(f, "({}, {})", self.longitude, self.latitude)
633 /// assert_eq!("(1.987, 2.983)".to_owned(),
634 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
636 #[stable(feature = "rust1", since = "1.0.0")]
637 fn fmt(&self, f: &mut Formatter) -> Result;
642 /// The `Octal` trait should format its output as a number in base-8.
644 /// For primitive signed integers (`i8` to `i128`, and `isize`),
645 /// negative values are formatted as the two’s complement representation.
647 /// The alternate flag, `#`, adds a `0o` in front of the output.
649 /// For more information on formatters, see [the module-level documentation][module].
651 /// [module]: ../../std/fmt/index.html
655 /// Basic usage with `i32`:
658 /// let x = 42; // 42 is '52' in octal
660 /// assert_eq!(format!("{:o}", x), "52");
661 /// assert_eq!(format!("{:#o}", x), "0o52");
663 /// assert_eq!(format!("{:o}", -16), "37777777760");
666 /// Implementing `Octal` on a type:
671 /// struct Length(i32);
673 /// impl fmt::Octal for Length {
674 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
675 /// let val = self.0;
677 /// write!(f, "{:o}", val) // delegate to i32's implementation
681 /// let l = Length(9);
683 /// println!("l as octal is: {:o}", l);
685 #[stable(feature = "rust1", since = "1.0.0")]
687 /// Formats the value using the given formatter.
688 #[stable(feature = "rust1", since = "1.0.0")]
689 fn fmt(&self, f: &mut Formatter) -> Result;
694 /// The `Binary` trait should format its output as a number in binary.
696 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
697 /// negative values are formatted as the two’s complement representation.
699 /// The alternate flag, `#`, adds a `0b` in front of the output.
701 /// For more information on formatters, see [the module-level documentation][module].
705 /// Basic usage with [`i32`]:
708 /// let x = 42; // 42 is '101010' in binary
710 /// assert_eq!(format!("{:b}", x), "101010");
711 /// assert_eq!(format!("{:#b}", x), "0b101010");
713 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
716 /// Implementing `Binary` on a type:
721 /// struct Length(i32);
723 /// impl fmt::Binary for Length {
724 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
725 /// let val = self.0;
727 /// write!(f, "{:b}", val) // delegate to i32's implementation
731 /// let l = Length(107);
733 /// println!("l as binary is: {:b}", l);
736 /// [module]: ../../std/fmt/index.html
737 /// [`i8`]: ../../std/primitive.i8.html
738 /// [`i128`]: ../../std/primitive.i128.html
739 /// [`isize`]: ../../std/primitive.isize.html
740 /// [`i32`]: ../../std/primitive.i32.html
741 #[stable(feature = "rust1", since = "1.0.0")]
743 /// Formats the value using the given formatter.
744 #[stable(feature = "rust1", since = "1.0.0")]
745 fn fmt(&self, f: &mut Formatter) -> Result;
750 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
753 /// For primitive signed integers (`i8` to `i128`, and `isize`),
754 /// negative values are formatted as the two’s complement representation.
756 /// The alternate flag, `#`, adds a `0x` in front of the output.
758 /// For more information on formatters, see [the module-level documentation][module].
760 /// [module]: ../../std/fmt/index.html
764 /// Basic usage with `i32`:
767 /// let x = 42; // 42 is '2a' in hex
769 /// assert_eq!(format!("{:x}", x), "2a");
770 /// assert_eq!(format!("{:#x}", x), "0x2a");
772 /// assert_eq!(format!("{:x}", -16), "fffffff0");
775 /// Implementing `LowerHex` on a type:
780 /// struct Length(i32);
782 /// impl fmt::LowerHex for Length {
783 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
784 /// let val = self.0;
786 /// write!(f, "{:x}", val) // delegate to i32's implementation
790 /// let l = Length(9);
792 /// println!("l as hex is: {:x}", l);
794 #[stable(feature = "rust1", since = "1.0.0")]
796 /// Formats the value using the given formatter.
797 #[stable(feature = "rust1", since = "1.0.0")]
798 fn fmt(&self, f: &mut Formatter) -> Result;
803 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
806 /// For primitive signed integers (`i8` to `i128`, and `isize`),
807 /// negative values are formatted as the two’s complement representation.
809 /// The alternate flag, `#`, adds a `0x` in front of the output.
811 /// For more information on formatters, see [the module-level documentation][module].
813 /// [module]: ../../std/fmt/index.html
817 /// Basic usage with `i32`:
820 /// let x = 42; // 42 is '2A' in hex
822 /// assert_eq!(format!("{:X}", x), "2A");
823 /// assert_eq!(format!("{:#X}", x), "0x2A");
825 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
828 /// Implementing `UpperHex` on a type:
833 /// struct Length(i32);
835 /// impl fmt::UpperHex for Length {
836 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
837 /// let val = self.0;
839 /// write!(f, "{:X}", val) // delegate to i32's implementation
843 /// let l = Length(9);
845 /// println!("l as hex is: {:X}", l);
847 #[stable(feature = "rust1", since = "1.0.0")]
849 /// Formats the value using the given formatter.
850 #[stable(feature = "rust1", since = "1.0.0")]
851 fn fmt(&self, f: &mut Formatter) -> Result;
856 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
859 /// For more information on formatters, see [the module-level documentation][module].
861 /// [module]: ../../std/fmt/index.html
865 /// Basic usage with `&i32`:
870 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
873 /// Implementing `Pointer` on a type:
878 /// struct Length(i32);
880 /// impl fmt::Pointer for Length {
881 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
882 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
884 /// write!(f, "{:p}", self as *const Length)
888 /// let l = Length(42);
890 /// println!("l is in memory here: {:p}", l);
892 #[stable(feature = "rust1", since = "1.0.0")]
894 /// Formats the value using the given formatter.
895 #[stable(feature = "rust1", since = "1.0.0")]
896 fn fmt(&self, f: &mut Formatter) -> Result;
901 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
903 /// For more information on formatters, see [the module-level documentation][module].
905 /// [module]: ../../std/fmt/index.html
909 /// Basic usage with `i32`:
912 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
914 /// assert_eq!(format!("{:e}", x), "4.2e1");
917 /// Implementing `LowerExp` on a type:
922 /// struct Length(i32);
924 /// impl fmt::LowerExp for Length {
925 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
926 /// let val = self.0;
927 /// write!(f, "{}e1", val / 10)
931 /// let l = Length(100);
933 /// println!("l in scientific notation is: {:e}", l);
935 #[stable(feature = "rust1", since = "1.0.0")]
937 /// Formats the value using the given formatter.
938 #[stable(feature = "rust1", since = "1.0.0")]
939 fn fmt(&self, f: &mut Formatter) -> Result;
944 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
946 /// For more information on formatters, see [the module-level documentation][module].
948 /// [module]: ../../std/fmt/index.html
952 /// Basic usage with `f32`:
955 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
957 /// assert_eq!(format!("{:E}", x), "4.2E1");
960 /// Implementing `UpperExp` on a type:
965 /// struct Length(i32);
967 /// impl fmt::UpperExp for Length {
968 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
969 /// let val = self.0;
970 /// write!(f, "{}E1", val / 10)
974 /// let l = Length(100);
976 /// println!("l in scientific notation is: {:E}", l);
978 #[stable(feature = "rust1", since = "1.0.0")]
980 /// Formats the value using the given formatter.
981 #[stable(feature = "rust1", since = "1.0.0")]
982 fn fmt(&self, f: &mut Formatter) -> Result;
985 /// The `write` function takes an output stream, and an `Arguments` struct
986 /// that can be precompiled with the `format_args!` macro.
988 /// The arguments will be formatted according to the specified format string
989 /// into the output stream provided.
998 /// let mut output = String::new();
999 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1000 /// .expect("Error occurred while trying to write in String");
1001 /// assert_eq!(output, "Hello world!");
1004 /// Please note that using [`write!`] might be preferable. Example:
1007 /// use std::fmt::Write;
1009 /// let mut output = String::new();
1010 /// write!(&mut output, "Hello {}!", "world")
1011 /// .expect("Error occurred while trying to write in String");
1012 /// assert_eq!(output, "Hello world!");
1015 /// [`write!`]: ../../std/macro.write.html
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 pub fn write(output: &mut dyn Write, args: Arguments) -> Result {
1018 let mut formatter = Formatter {
1023 align: rt::v1::Alignment::Unknown,
1026 curarg: args.args.iter(),
1033 // We can use default formatting parameters for all arguments.
1034 for (arg, piece) in args.args.iter().zip(args.pieces.iter()) {
1035 formatter.buf.write_str(*piece)?;
1036 (arg.formatter)(arg.value, &mut formatter)?;
1041 // Every spec has a corresponding argument that is preceded by
1043 for (arg, piece) in fmt.iter().zip(args.pieces.iter()) {
1044 formatter.buf.write_str(*piece)?;
1045 formatter.run(arg)?;
1051 // There can be only one trailing string piece left.
1052 if let Some(piece) = args.pieces.get(idx) {
1053 formatter.buf.write_str(*piece)?;
1059 impl<'a> Formatter<'a> {
1060 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1061 where 'b: 'c, F: FnOnce(&'b mut (dyn Write+'b)) -> &'c mut (dyn Write+'c)
1064 // We want to change this
1065 buf: wrap(self.buf),
1067 // And preserve these
1072 precision: self.precision,
1074 // These only exist in the struct for the `run` method,
1075 // which won’t be used together with this method.
1076 curarg: self.curarg.clone(),
1081 // First up is the collection of functions used to execute a format string
1082 // at runtime. This consumes all of the compile-time statics generated by
1083 // the format! syntax extension.
1084 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1085 // Fill in the format parameters into the formatter
1086 self.fill = arg.format.fill;
1087 self.align = arg.format.align;
1088 self.flags = arg.format.flags;
1089 self.width = self.getcount(&arg.format.width);
1090 self.precision = self.getcount(&arg.format.precision);
1092 // Extract the correct argument
1093 let value = match arg.position {
1094 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1095 rt::v1::Position::At(i) => self.args[i],
1098 // Then actually do some printing
1099 (value.formatter)(value.value, self)
1102 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1104 rt::v1::Count::Is(n) => Some(n),
1105 rt::v1::Count::Implied => None,
1106 rt::v1::Count::Param(i) => {
1107 self.args[i].as_usize()
1109 rt::v1::Count::NextParam => {
1110 self.curarg.next().and_then(|arg| arg.as_usize())
1115 // Helper methods used for padding and processing formatting arguments that
1116 // all formatting traits can use.
1118 /// Performs the correct padding for an integer which has already been
1119 /// emitted into a str. The str should *not* contain the sign for the
1120 /// integer, that will be added by this method.
1124 /// * is_nonnegative - whether the original integer was either positive or zero.
1125 /// * prefix - if the '#' character (Alternate) is provided, this
1126 /// is the prefix to put in front of the number.
1127 /// * buf - the byte array that the number has been formatted into
1129 /// This function will correctly account for the flags provided as well as
1130 /// the minimum width. It will not take precision into account.
1137 /// struct Foo { nb: i32 };
1140 /// fn new(nb: i32) -> Foo {
1147 /// impl fmt::Display for Foo {
1148 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1149 /// // We need to remove "-" from the number output.
1150 /// let tmp = self.nb.abs().to_string();
1152 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1156 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1157 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1158 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1159 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1161 #[stable(feature = "rust1", since = "1.0.0")]
1162 pub fn pad_integral(&mut self,
1163 is_nonnegative: bool,
1167 let mut width = buf.len();
1169 let mut sign = None;
1170 if !is_nonnegative {
1171 sign = Some('-'); width += 1;
1172 } else if self.sign_plus() {
1173 sign = Some('+'); width += 1;
1176 let mut prefixed = false;
1177 if self.alternate() {
1178 prefixed = true; width += prefix.chars().count();
1181 // Writes the sign if it exists, and then the prefix if it was requested
1182 let write_prefix = |f: &mut Formatter| {
1183 if let Some(c) = sign {
1184 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
1186 if prefixed { f.buf.write_str(prefix) }
1190 // The `width` field is more of a `min-width` parameter at this point.
1192 // If there's no minimum length requirements then we can just
1195 write_prefix(self)?; self.buf.write_str(buf)
1197 // Check if we're over the minimum width, if so then we can also
1198 // just write the bytes.
1199 Some(min) if width >= min => {
1200 write_prefix(self)?; self.buf.write_str(buf)
1202 // The sign and prefix goes before the padding if the fill character
1204 Some(min) if self.sign_aware_zero_pad() => {
1206 self.align = rt::v1::Alignment::Right;
1207 write_prefix(self)?;
1208 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1209 f.buf.write_str(buf)
1212 // Otherwise, the sign and prefix goes after the padding
1214 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1215 write_prefix(f)?; f.buf.write_str(buf)
1221 /// This function takes a string slice and emits it to the internal buffer
1222 /// after applying the relevant formatting flags specified. The flags
1223 /// recognized for generic strings are:
1225 /// * width - the minimum width of what to emit
1226 /// * fill/align - what to emit and where to emit it if the string
1227 /// provided needs to be padded
1228 /// * precision - the maximum length to emit, the string is truncated if it
1229 /// is longer than this length
1231 /// Notably this function ignores the `flag` parameters.
1240 /// impl fmt::Display for Foo {
1241 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1242 /// formatter.pad("Foo")
1246 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1247 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 pub fn pad(&mut self, s: &str) -> Result {
1251 // Make sure there's a fast path up front
1252 if self.width.is_none() && self.precision.is_none() {
1253 return self.buf.write_str(s);
1255 // The `precision` field can be interpreted as a `max-width` for the
1256 // string being formatted.
1257 let s = if let Some(max) = self.precision {
1258 // If our string is longer that the precision, then we must have
1259 // truncation. However other flags like `fill`, `width` and `align`
1260 // must act as always.
1261 if let Some((i, _)) = s.char_indices().nth(max) {
1262 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1263 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1264 // `unsafe` and otherwise don't emit any panic-related code
1266 s.get(..i).unwrap_or(&s)
1273 // The `width` field is more of a `min-width` parameter at this point.
1275 // If we're under the maximum length, and there's no minimum length
1276 // requirements, then we can just emit the string
1277 None => self.buf.write_str(s),
1278 // If we're under the maximum width, check if we're over the minimum
1279 // width, if so it's as easy as just emitting the string.
1280 Some(width) if s.chars().count() >= width => {
1281 self.buf.write_str(s)
1283 // If we're under both the maximum and the minimum width, then fill
1284 // up the minimum width with the specified string + some alignment.
1286 let align = rt::v1::Alignment::Left;
1287 self.with_padding(width - s.chars().count(), align, |me| {
1294 /// Runs a callback, emitting the correct padding either before or
1295 /// afterwards depending on whether right or left alignment is requested.
1296 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1298 where F: FnOnce(&mut Formatter) -> Result,
1300 let align = match self.align {
1301 rt::v1::Alignment::Unknown => default,
1305 let (pre_pad, post_pad) = match align {
1306 rt::v1::Alignment::Left => (0, padding),
1307 rt::v1::Alignment::Right |
1308 rt::v1::Alignment::Unknown => (padding, 0),
1309 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1312 let mut fill = [0; 4];
1313 let fill = self.fill.encode_utf8(&mut fill);
1315 for _ in 0..pre_pad {
1316 self.buf.write_str(fill)?;
1321 for _ in 0..post_pad {
1322 self.buf.write_str(fill)?;
1328 /// Takes the formatted parts and applies the padding.
1329 /// Assumes that the caller already has rendered the parts with required precision,
1330 /// so that `self.precision` can be ignored.
1331 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1332 if let Some(mut width) = self.width {
1333 // for the sign-aware zero padding, we render the sign first and
1334 // behave as if we had no sign from the beginning.
1335 let mut formatted = formatted.clone();
1336 let old_fill = self.fill;
1337 let old_align = self.align;
1338 let mut align = old_align;
1339 if self.sign_aware_zero_pad() {
1340 // a sign always goes first
1341 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1342 self.buf.write_str(sign)?;
1344 // remove the sign from the formatted parts
1345 formatted.sign = b"";
1346 width = if width < sign.len() { 0 } else { width - sign.len() };
1347 align = rt::v1::Alignment::Right;
1349 self.align = rt::v1::Alignment::Right;
1352 // remaining parts go through the ordinary padding process.
1353 let len = formatted.len();
1354 let ret = if width <= len { // no padding
1355 self.write_formatted_parts(&formatted)
1357 self.with_padding(width - len, align, |f| {
1358 f.write_formatted_parts(&formatted)
1361 self.fill = old_fill;
1362 self.align = old_align;
1365 // this is the common case and we take a shortcut
1366 self.write_formatted_parts(formatted)
1370 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1371 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1372 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1375 if !formatted.sign.is_empty() {
1376 write_bytes(self.buf, formatted.sign)?;
1378 for part in formatted.parts {
1380 flt2dec::Part::Zero(mut nzeroes) => {
1381 const ZEROES: &str = // 64 zeroes
1382 "0000000000000000000000000000000000000000000000000000000000000000";
1383 while nzeroes > ZEROES.len() {
1384 self.buf.write_str(ZEROES)?;
1385 nzeroes -= ZEROES.len();
1388 self.buf.write_str(&ZEROES[..nzeroes])?;
1391 flt2dec::Part::Num(mut v) => {
1393 let len = part.len();
1394 for c in s[..len].iter_mut().rev() {
1395 *c = b'0' + (v % 10) as u8;
1398 write_bytes(self.buf, &s[..len])?;
1400 flt2dec::Part::Copy(buf) => {
1401 write_bytes(self.buf, buf)?;
1408 /// Writes some data to the underlying buffer contained within this
1418 /// impl fmt::Display for Foo {
1419 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1420 /// formatter.write_str("Foo")
1421 /// // This is equivalent to:
1422 /// // write!(formatter, "Foo")
1426 /// assert_eq!(&format!("{}", Foo), "Foo");
1427 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1429 #[stable(feature = "rust1", since = "1.0.0")]
1430 pub fn write_str(&mut self, data: &str) -> Result {
1431 self.buf.write_str(data)
1434 /// Writes some formatted information into this instance.
1441 /// struct Foo(i32);
1443 /// impl fmt::Display for Foo {
1444 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1445 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1449 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1450 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1454 write(self.buf, fmt)
1457 /// Flags for formatting
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 #[rustc_deprecated(since = "1.24.0",
1460 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1461 or `sign_aware_zero_pad` methods instead")]
1462 pub fn flags(&self) -> u32 { self.flags }
1464 /// Character used as 'fill' whenever there is alignment.
1473 /// impl fmt::Display for Foo {
1474 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1475 /// let c = formatter.fill();
1476 /// if let Some(width) = formatter.width() {
1477 /// for _ in 0..width {
1478 /// write!(formatter, "{}", c)?;
1482 /// write!(formatter, "{}", c)
1487 /// // We set alignment to the left with ">".
1488 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1489 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1491 #[stable(feature = "fmt_flags", since = "1.5.0")]
1492 pub fn fill(&self) -> char { self.fill }
1494 /// Flag indicating what form of alignment was requested.
1499 /// extern crate core;
1501 /// use std::fmt::{self, Alignment};
1505 /// impl fmt::Display for Foo {
1506 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1507 /// let s = if let Some(s) = formatter.align() {
1509 /// Alignment::Left => "left",
1510 /// Alignment::Right => "right",
1511 /// Alignment::Center => "center",
1516 /// write!(formatter, "{}", s)
1521 /// assert_eq!(&format!("{:<}", Foo), "left");
1522 /// assert_eq!(&format!("{:>}", Foo), "right");
1523 /// assert_eq!(&format!("{:^}", Foo), "center");
1524 /// assert_eq!(&format!("{}", Foo), "into the void");
1527 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1528 pub fn align(&self) -> Option<Alignment> {
1530 rt::v1::Alignment::Left => Some(Alignment::Left),
1531 rt::v1::Alignment::Right => Some(Alignment::Right),
1532 rt::v1::Alignment::Center => Some(Alignment::Center),
1533 rt::v1::Alignment::Unknown => None,
1537 /// Optionally specified integer width that the output should be.
1544 /// struct Foo(i32);
1546 /// impl fmt::Display for Foo {
1547 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1548 /// if let Some(width) = formatter.width() {
1549 /// // If we received a width, we use it
1550 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1552 /// // Otherwise we do nothing special
1553 /// write!(formatter, "Foo({})", self.0)
1558 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1559 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1561 #[stable(feature = "fmt_flags", since = "1.5.0")]
1562 pub fn width(&self) -> Option<usize> { self.width }
1564 /// Optionally specified precision for numeric types.
1571 /// struct Foo(f32);
1573 /// impl fmt::Display for Foo {
1574 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1575 /// if let Some(precision) = formatter.precision() {
1576 /// // If we received a precision, we use it.
1577 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1579 /// // Otherwise we default to 2.
1580 /// write!(formatter, "Foo({:.2})", self.0)
1585 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1586 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1588 #[stable(feature = "fmt_flags", since = "1.5.0")]
1589 pub fn precision(&self) -> Option<usize> { self.precision }
1591 /// Determines if the `+` flag was specified.
1598 /// struct Foo(i32);
1600 /// impl fmt::Display for Foo {
1601 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1602 /// if formatter.sign_plus() {
1603 /// write!(formatter,
1605 /// if self.0 < 0 { '-' } else { '+' },
1608 /// write!(formatter, "Foo({})", self.0)
1613 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1614 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1616 #[stable(feature = "fmt_flags", since = "1.5.0")]
1617 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1619 /// Determines if the `-` flag was specified.
1626 /// struct Foo(i32);
1628 /// impl fmt::Display for Foo {
1629 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1630 /// if formatter.sign_minus() {
1631 /// // You want a minus sign? Have one!
1632 /// write!(formatter, "-Foo({})", self.0)
1634 /// write!(formatter, "Foo({})", self.0)
1639 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1640 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1642 #[stable(feature = "fmt_flags", since = "1.5.0")]
1643 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1645 /// Determines if the `#` flag was specified.
1652 /// struct Foo(i32);
1654 /// impl fmt::Display for Foo {
1655 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1656 /// if formatter.alternate() {
1657 /// write!(formatter, "Foo({})", self.0)
1659 /// write!(formatter, "{}", self.0)
1664 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1665 /// assert_eq!(&format!("{}", Foo(23)), "23");
1667 #[stable(feature = "fmt_flags", since = "1.5.0")]
1668 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1670 /// Determines if the `0` flag was specified.
1677 /// struct Foo(i32);
1679 /// impl fmt::Display for Foo {
1680 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1681 /// assert!(formatter.sign_aware_zero_pad());
1682 /// assert_eq!(formatter.width(), Some(4));
1683 /// // We ignore the formatter's options.
1684 /// write!(formatter, "{}", self.0)
1688 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1690 #[stable(feature = "fmt_flags", since = "1.5.0")]
1691 pub fn sign_aware_zero_pad(&self) -> bool {
1692 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1695 // FIXME: Decide what public API we want for these two flags.
1696 // https://github.com/rust-lang/rust/issues/48584
1697 fn debug_lower_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0 }
1699 fn debug_upper_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0 }
1701 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1702 /// [`fmt::Debug`] implementations for structs.
1704 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1705 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1711 /// use std::net::Ipv4Addr;
1719 /// impl fmt::Debug for Foo {
1720 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1721 /// fmt.debug_struct("Foo")
1722 /// .field("bar", &self.bar)
1723 /// .field("baz", &self.baz)
1724 /// .field("addr", &format_args!("{}", self.addr))
1730 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1731 /// format!("{:?}", Foo {
1733 /// baz: "Hello World".to_string(),
1734 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1738 #[stable(feature = "debug_builders", since = "1.2.0")]
1739 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1740 builders::debug_struct_new(self, name)
1743 /// Creates a `DebugTuple` builder designed to assist with creation of
1744 /// `fmt::Debug` implementations for tuple structs.
1750 /// use std::marker::PhantomData;
1752 /// struct Foo<T>(i32, String, PhantomData<T>);
1754 /// impl<T> fmt::Debug for Foo<T> {
1755 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1756 /// fmt.debug_tuple("Foo")
1759 /// .field(&format_args!("_"))
1765 /// "Foo(10, \"Hello\", _)",
1766 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1769 #[stable(feature = "debug_builders", since = "1.2.0")]
1770 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1771 builders::debug_tuple_new(self, name)
1774 /// Creates a `DebugList` builder designed to assist with creation of
1775 /// `fmt::Debug` implementations for list-like structures.
1782 /// struct Foo(Vec<i32>);
1784 /// impl fmt::Debug for Foo {
1785 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1786 /// fmt.debug_list().entries(self.0.iter()).finish()
1790 /// // prints "[10, 11]"
1791 /// println!("{:?}", Foo(vec![10, 11]));
1793 #[stable(feature = "debug_builders", since = "1.2.0")]
1794 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1795 builders::debug_list_new(self)
1798 /// Creates a `DebugSet` builder designed to assist with creation of
1799 /// `fmt::Debug` implementations for set-like structures.
1806 /// struct Foo(Vec<i32>);
1808 /// impl fmt::Debug for Foo {
1809 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1810 /// fmt.debug_set().entries(self.0.iter()).finish()
1814 /// // prints "{10, 11}"
1815 /// println!("{:?}", Foo(vec![10, 11]));
1818 /// [`format_args!`]: ../../std/macro.format_args.html
1820 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1821 /// to build a list of match arms:
1826 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1827 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1829 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1831 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1833 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1834 /// L::fmt(&(self.0).0, fmt)?;
1835 /// fmt.write_str(" => ")?;
1836 /// R::fmt(&(self.0).1, fmt)
1840 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1842 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1844 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1846 /// .entries(self.0.iter().map(Arm))
1847 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1852 #[stable(feature = "debug_builders", since = "1.2.0")]
1853 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1854 builders::debug_set_new(self)
1857 /// Creates a `DebugMap` builder designed to assist with creation of
1858 /// `fmt::Debug` implementations for map-like structures.
1865 /// struct Foo(Vec<(String, i32)>);
1867 /// impl fmt::Debug for Foo {
1868 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1869 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1873 /// // prints "{"A": 10, "B": 11}"
1874 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1876 #[stable(feature = "debug_builders", since = "1.2.0")]
1877 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1878 builders::debug_map_new(self)
1882 #[stable(since = "1.2.0", feature = "formatter_write")]
1883 impl Write for Formatter<'_> {
1884 fn write_str(&mut self, s: &str) -> Result {
1885 self.buf.write_str(s)
1888 fn write_char(&mut self, c: char) -> Result {
1889 self.buf.write_char(c)
1892 fn write_fmt(&mut self, args: Arguments) -> Result {
1893 write(self.buf, args)
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 impl Display for Error {
1899 fn fmt(&self, f: &mut Formatter) -> Result {
1900 Display::fmt("an error occurred when formatting an argument", f)
1904 // Implementations of the core formatting traits
1906 macro_rules! fmt_refs {
1907 ($($tr:ident),*) => {
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 impl<T: ?Sized + $tr> $tr for &T {
1911 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 impl<T: ?Sized + $tr> $tr for &mut T {
1915 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1921 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1923 #[unstable(feature = "never_type", issue = "35121")]
1925 fn fmt(&self, _: &mut Formatter) -> Result {
1930 #[unstable(feature = "never_type", issue = "35121")]
1931 impl Display for ! {
1932 fn fmt(&self, _: &mut Formatter) -> Result {
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 impl Debug for bool {
1940 fn fmt(&self, f: &mut Formatter) -> Result {
1941 Display::fmt(self, f)
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 impl Display for bool {
1947 fn fmt(&self, f: &mut Formatter) -> Result {
1948 Display::fmt(if *self { "true" } else { "false" }, f)
1952 #[stable(feature = "rust1", since = "1.0.0")]
1953 impl Debug for str {
1954 fn fmt(&self, f: &mut Formatter) -> Result {
1957 for (i, c) in self.char_indices() {
1958 let esc = c.escape_debug();
1959 // If char needs escaping, flush backlog so far and write, else skip
1961 f.write_str(&self[from..i])?;
1965 from = i + c.len_utf8();
1968 f.write_str(&self[from..])?;
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 impl Display for str {
1975 fn fmt(&self, f: &mut Formatter) -> Result {
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 impl Debug for char {
1982 fn fmt(&self, f: &mut Formatter) -> Result {
1983 f.write_char('\'')?;
1984 for c in self.escape_debug() {
1991 #[stable(feature = "rust1", since = "1.0.0")]
1992 impl Display for char {
1993 fn fmt(&self, f: &mut Formatter) -> Result {
1994 if f.width.is_none() && f.precision.is_none() {
1997 f.pad(self.encode_utf8(&mut [0; 4]))
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 impl<T: ?Sized> Pointer for *const T {
2004 fn fmt(&self, f: &mut Formatter) -> Result {
2005 let old_width = f.width;
2006 let old_flags = f.flags;
2008 // The alternate flag is already treated by LowerHex as being special-
2009 // it denotes whether to prefix with 0x. We use it to work out whether
2010 // or not to zero extend, and then unconditionally set it to get the
2013 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2015 if let None = f.width {
2016 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2019 f.flags |= 1 << (FlagV1::Alternate as u32);
2021 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2023 f.width = old_width;
2024 f.flags = old_flags;
2030 #[stable(feature = "rust1", since = "1.0.0")]
2031 impl<T: ?Sized> Pointer for *mut T {
2032 fn fmt(&self, f: &mut Formatter) -> Result {
2033 Pointer::fmt(&(*self as *const T), f)
2037 #[stable(feature = "rust1", since = "1.0.0")]
2038 impl<T: ?Sized> Pointer for &T {
2039 fn fmt(&self, f: &mut Formatter) -> Result {
2040 Pointer::fmt(&(*self as *const T), f)
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 impl<T: ?Sized> Pointer for &mut T {
2046 fn fmt(&self, f: &mut Formatter) -> Result {
2047 Pointer::fmt(&(&**self as *const T), f)
2051 // Implementation of Display/Debug for various core types
2053 #[stable(feature = "rust1", since = "1.0.0")]
2054 impl<T: ?Sized> Debug for *const T {
2055 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2057 #[stable(feature = "rust1", since = "1.0.0")]
2058 impl<T: ?Sized> Debug for *mut T {
2059 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2063 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2066 macro_rules! tuple {
2068 ( $($name:ident,)+ ) => (
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
2071 #[allow(non_snake_case, unused_assignments, deprecated)]
2072 fn fmt(&self, f: &mut Formatter) -> Result {
2073 let mut builder = f.debug_tuple("");
2074 let ($(ref $name,)*) = *self;
2076 builder.field(&$name);
2082 peel! { $($name,)* }
2086 macro_rules! last_type {
2087 ($a:ident,) => { $a };
2088 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2091 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 impl<T: Debug> Debug for [T] {
2095 fn fmt(&self, f: &mut Formatter) -> Result {
2096 f.debug_list().entries(self.iter()).finish()
2100 #[stable(feature = "rust1", since = "1.0.0")]
2103 fn fmt(&self, f: &mut Formatter) -> Result {
2107 #[stable(feature = "rust1", since = "1.0.0")]
2108 impl<T: ?Sized> Debug for PhantomData<T> {
2109 fn fmt(&self, f: &mut Formatter) -> Result {
2110 f.pad("PhantomData")
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl<T: Copy + Debug> Debug for Cell<T> {
2116 fn fmt(&self, f: &mut Formatter) -> Result {
2117 f.debug_struct("Cell")
2118 .field("value", &self.get())
2123 #[stable(feature = "rust1", since = "1.0.0")]
2124 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2125 fn fmt(&self, f: &mut Formatter) -> Result {
2126 match self.try_borrow() {
2128 f.debug_struct("RefCell")
2129 .field("value", &borrow)
2133 // The RefCell is mutably borrowed so we can't look at its value
2134 // here. Show a placeholder instead.
2135 struct BorrowedPlaceholder;
2137 impl Debug for BorrowedPlaceholder {
2138 fn fmt(&self, f: &mut Formatter) -> Result {
2139 f.write_str("<borrowed>")
2143 f.debug_struct("RefCell")
2144 .field("value", &BorrowedPlaceholder)
2151 #[stable(feature = "rust1", since = "1.0.0")]
2152 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2153 fn fmt(&self, f: &mut Formatter) -> Result {
2154 Debug::fmt(&**self, f)
2158 #[stable(feature = "rust1", since = "1.0.0")]
2159 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2160 fn fmt(&self, f: &mut Formatter) -> Result {
2161 Debug::fmt(&*(self.deref()), f)
2165 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2166 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2167 fn fmt(&self, f: &mut Formatter) -> Result {
2172 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
2173 // it's a lot easier than creating all of the rt::Piece structures here.