1 //! Utilities for formatting and printing strings.
3 // ignore-tidy-undocumented-unsafe
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use crate::cell::{Cell, Ref, RefCell, RefMut, UnsafeCell};
8 use crate::marker::PhantomData;
10 use crate::num::flt2dec;
11 use crate::ops::Deref;
19 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
20 /// Possible alignments returned by `Formatter::align`
23 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
24 /// Indication that contents should be left-aligned.
26 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
27 /// Indication that contents should be right-aligned.
29 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
30 /// Indication that contents should be center-aligned.
34 #[stable(feature = "debug_builders", since = "1.2.0")]
35 pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
37 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
43 /// The type returned by formatter methods.
57 /// impl fmt::Display for Triangle {
58 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
63 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
65 /// assert_eq!(format!("{}", pythagorean_triple), "(3, 4, 5)");
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub type Result = result::Result<(), Error>;
70 /// The error type which is returned from formatting a message into a stream.
72 /// This type does not support transmission of an error other than that an error
73 /// occurred. Any extra information must be arranged to be transmitted through
76 /// An important thing to remember is that the type `fmt::Error` should not be
77 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
80 /// [`std::io::Error`]: ../../std/io/struct.Error.html
81 /// [`std::error::Error`]: ../../std/error/trait.Error.html
86 /// use std::fmt::{self, write};
88 /// let mut output = String::new();
89 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
90 /// panic!("An error occurred");
93 #[stable(feature = "rust1", since = "1.0.0")]
94 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
97 /// A collection of methods that are required to format a message into a stream.
99 /// This trait is the type which this modules requires when formatting
100 /// information. This is similar to the standard library's [`io::Write`] trait,
101 /// but it is only intended for use in libcore.
103 /// This trait should generally not be implemented by consumers of the standard
104 /// library. The [`write!`] macro accepts an instance of [`io::Write`], and the
105 /// [`io::Write`] trait is favored over implementing this trait.
107 /// [`write!`]: ../../std/macro.write.html
108 /// [`io::Write`]: ../../std/io/trait.Write.html
109 #[stable(feature = "rust1", since = "1.0.0")]
111 /// Writes a string slice into this writer, returning whether the write
114 /// This method can only succeed if the entire string slice was successfully
115 /// written, and this method will not return until all data has been
116 /// written or an error occurs.
120 /// This function will return an instance of [`Error`] on error.
122 /// [`Error`]: struct.Error.html
127 /// use std::fmt::{Error, Write};
129 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
133 /// let mut buf = String::new();
134 /// writer(&mut buf, "hola").unwrap();
135 /// assert_eq!(&buf, "hola");
137 #[stable(feature = "rust1", since = "1.0.0")]
138 fn write_str(&mut self, s: &str) -> Result;
140 /// Writes a [`char`] into this writer, returning whether the write succeeded.
142 /// A single [`char`] may be encoded as more than one byte.
143 /// This method can only succeed if the entire byte sequence was successfully
144 /// written, and this method will not return until all data has been
145 /// written or an error occurs.
149 /// This function will return an instance of [`Error`] on error.
151 /// [`char`]: ../../std/primitive.char.html
152 /// [`Error`]: struct.Error.html
157 /// use std::fmt::{Error, Write};
159 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
163 /// let mut buf = String::new();
164 /// writer(&mut buf, 'a').unwrap();
165 /// writer(&mut buf, 'b').unwrap();
166 /// assert_eq!(&buf, "ab");
168 #[stable(feature = "fmt_write_char", since = "1.1.0")]
169 fn write_char(&mut self, c: char) -> Result {
170 self.write_str(c.encode_utf8(&mut [0; 4]))
173 /// Glue for usage of the [`write!`] macro with implementors of this trait.
175 /// This method should generally not be invoked manually, but rather through
176 /// the [`write!`] macro itself.
178 /// [`write!`]: ../../std/macro.write.html
183 /// use std::fmt::{Error, Write};
185 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
186 /// f.write_fmt(format_args!("{}", s))
189 /// let mut buf = String::new();
190 /// writer(&mut buf, "world").unwrap();
191 /// assert_eq!(&buf, "world");
193 #[stable(feature = "rust1", since = "1.0.0")]
194 fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
195 write(&mut self, args)
199 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
200 impl<W: Write + ?Sized> Write for &mut W {
201 fn write_str(&mut self, s: &str) -> Result {
202 (**self).write_str(s)
205 fn write_char(&mut self, c: char) -> Result {
206 (**self).write_char(c)
209 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
210 (**self).write_fmt(args)
214 /// Configuration for formatting.
216 /// A `Formatter` represents various options related to formatting. Users do not
217 /// construct `Formatter`s directly; a mutable reference to one is passed to
218 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
220 /// To interact with a `Formatter`, you'll call various methods to change the
221 /// various options related to formatting. For examples, please see the
222 /// documentation of the methods defined on `Formatter` below.
224 /// [`Debug`]: trait.Debug.html
225 /// [`Display`]: trait.Display.html
226 #[allow(missing_debug_implementations)]
227 #[stable(feature = "rust1", since = "1.0.0")]
228 pub struct Formatter<'a> {
231 align: rt::v1::Alignment,
232 width: Option<usize>,
233 precision: Option<usize>,
235 buf: &'a mut (dyn Write + 'a),
238 // NB. Argument is essentially an optimized partially applied formatting function,
239 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
245 /// This struct represents the generic "argument" which is taken by the Xprintf
246 /// family of functions. It contains a function to format the given value. At
247 /// compile time it is ensured that the function and the value have the correct
248 /// types, and then this struct is used to canonicalize arguments to one type.
249 #[derive(Copy, Clone)]
250 #[allow(missing_debug_implementations)]
251 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
253 pub struct ArgumentV1<'a> {
255 formatter: fn(&Opaque, &mut Formatter<'_>) -> Result,
258 // This gurantees a single stable value for the function pointer associated with
259 // indices/counts in the formatting infrastructure.
261 // Note that a function defined as such would not be correct as functions are
262 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
263 // address is not considered important to LLVM and as such the as_usize cast
264 // could have been miscompiled. In practice, we never call as_usize on non-usize
265 // containing data (as a matter of static generation of the formatting
266 // arguments), so this is merely an additional check.
267 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
268 static USIZE_MARKER: fn(&usize, &mut Formatter<'_>) -> Result = |_, _| loop {};
270 impl<'a> ArgumentV1<'a> {
272 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
273 pub fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
274 unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) } }
278 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
279 pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
280 ArgumentV1::new(x, USIZE_MARKER)
283 fn as_usize(&self) -> Option<usize> {
284 if self.formatter as usize == USIZE_MARKER as usize {
285 // SAFETY: The `formatter` field is only set to USIZE_MARKER if
286 // the value is a usize, so this is safe
287 Some(unsafe { *(self.value as *const _ as *const usize) })
294 // flags available in the v1 format of format_args
295 #[derive(Copy, Clone)]
305 impl<'a> Arguments<'a> {
306 /// When using the format_args!() macro, this function is used to generate the
307 /// Arguments structure.
310 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
311 pub fn new_v1(pieces: &'a [&'a str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
312 Arguments { pieces, fmt: None, args }
315 /// This function is used to specify nonstandard formatting parameters.
316 /// The `pieces` array must be at least as long as `fmt` to construct
317 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
318 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
319 /// created with `argumentusize`. However, failing to do so doesn't cause
320 /// unsafety, but will ignore invalid .
323 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
324 pub fn new_v1_formatted(
325 pieces: &'a [&'a str],
326 args: &'a [ArgumentV1<'a>],
327 fmt: &'a [rt::v1::Argument],
329 Arguments { pieces, fmt: Some(fmt), args }
332 /// Estimates the length of the formatted text.
334 /// This is intended to be used for setting initial `String` capacity
335 /// when using `format!`. Note: this is neither the lower nor upper bound.
338 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
339 pub fn estimated_capacity(&self) -> usize {
340 let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
342 if self.args.is_empty() {
344 } else if self.pieces[0] == "" && pieces_length < 16 {
345 // If the format string starts with an argument,
346 // don't preallocate anything, unless length
347 // of pieces is significant.
350 // There are some arguments, so any additional push
351 // will reallocate the string. To avoid that,
352 // we're "pre-doubling" the capacity here.
353 pieces_length.checked_mul(2).unwrap_or(0)
358 /// This structure represents a safely precompiled version of a format string
359 /// and its arguments. This cannot be generated at runtime because it cannot
360 /// safely be done, so no constructors are given and the fields are private
361 /// to prevent modification.
363 /// The [`format_args!`] macro will safely create an instance of this structure.
364 /// The macro validates the format string at compile-time so usage of the
365 /// [`write`] and [`format`] functions can be safely performed.
367 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
368 /// and `Display` contexts as seen below. The example also shows that `Debug`
369 /// and `Display` format to the same thing: the interpolated format string
370 /// in `format_args!`.
373 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
374 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
375 /// assert_eq!("1 foo 2", display);
376 /// assert_eq!(display, debug);
379 /// [`format_args!`]: ../../std/macro.format_args.html
380 /// [`format`]: ../../std/fmt/fn.format.html
381 /// [`write`]: ../../std/fmt/fn.write.html
382 #[stable(feature = "rust1", since = "1.0.0")]
383 #[derive(Copy, Clone)]
384 pub struct Arguments<'a> {
385 // Format string pieces to print.
386 pieces: &'a [&'a str],
388 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
389 fmt: Option<&'a [rt::v1::Argument]>,
391 // Dynamic arguments for interpolation, to be interleaved with string
392 // pieces. (Every argument is preceded by a string piece.)
393 args: &'a [ArgumentV1<'a>],
396 #[stable(feature = "rust1", since = "1.0.0")]
397 impl Debug for Arguments<'_> {
398 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
399 Display::fmt(self, fmt)
403 #[stable(feature = "rust1", since = "1.0.0")]
404 impl Display for Arguments<'_> {
405 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
406 write(fmt.buf, *self)
412 /// `Debug` should format the output in a programmer-facing, debugging context.
414 /// Generally speaking, you should just `derive` a `Debug` implementation.
416 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
418 /// For more information on formatters, see [the module-level documentation][module].
420 /// [module]: ../../std/fmt/index.html
422 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
423 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
424 /// comma-separated list of each field's name and `Debug` value, then `}`. For
425 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
426 /// `Debug` values of the fields, then `)`.
430 /// Deriving an implementation:
439 /// let origin = Point { x: 0, y: 0 };
441 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
444 /// Manually implementing:
454 /// impl fmt::Debug for Point {
455 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456 /// f.debug_struct("Point")
457 /// .field("x", &self.x)
458 /// .field("y", &self.y)
463 /// let origin = Point { x: 0, y: 0 };
465 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
468 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
469 /// implementations, such as [`debug_struct`].
471 /// `Debug` implementations using either `derive` or the debug builder API
472 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
474 /// [`debug_struct`]: ../../std/fmt/struct.Formatter.html#method.debug_struct
475 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
477 /// Pretty-printing with `#?`:
486 /// let origin = Point { x: 0, y: 0 };
488 /// assert_eq!(format!("The origin is: {:#?}", origin),
489 /// "The origin is: Point {
495 #[stable(feature = "rust1", since = "1.0.0")]
496 #[rustc_on_unimplemented(
499 label = "`{Self}` cannot be formatted using `{{:?}}`",
500 note = "add `#[derive(Debug)]` or manually implement `{Debug}`"
502 message = "`{Self}` doesn't implement `{Debug}`",
503 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
505 #[doc(alias = "{:?}")]
506 #[rustc_diagnostic_item = "debug_trait"]
508 /// Formats the value using the given formatter.
515 /// struct Position {
520 /// impl fmt::Debug for Position {
521 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522 /// f.debug_tuple("")
523 /// .field(&self.longitude)
524 /// .field(&self.latitude)
529 /// let position = Position { longitude: 1.987, latitude: 2.983 };
530 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
532 /// assert_eq!(format!("{:#?}", position), "(
537 #[stable(feature = "rust1", since = "1.0.0")]
538 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
541 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
542 pub(crate) mod macros {
543 /// Derive macro generating an impl of the trait `Debug`.
544 #[rustc_builtin_macro]
545 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
546 #[allow_internal_unstable(core_intrinsics)]
547 pub macro Debug($item:item) {
548 /* compiler built-in */
551 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
553 pub use macros::Debug;
555 /// Format trait for an empty format, `{}`.
557 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
558 /// output, and so cannot be derived.
560 /// [debug]: trait.Debug.html
562 /// For more information on formatters, see [the module-level documentation][module].
564 /// [module]: ../../std/fmt/index.html
568 /// Implementing `Display` on a type:
578 /// impl fmt::Display for Point {
579 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
580 /// write!(f, "({}, {})", self.x, self.y)
584 /// let origin = Point { x: 0, y: 0 };
586 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
588 #[rustc_on_unimplemented(
590 _Self = "std::path::Path",
591 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
592 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
593 as they may contain non-Unicode data"
595 message = "`{Self}` doesn't implement `{Display}`",
596 label = "`{Self}` cannot be formatted with the default formatter",
597 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
600 #[stable(feature = "rust1", since = "1.0.0")]
602 /// Formats the value using the given formatter.
609 /// struct Position {
614 /// impl fmt::Display for Position {
615 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616 /// write!(f, "({}, {})", self.longitude, self.latitude)
620 /// assert_eq!("(1.987, 2.983)",
621 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
623 #[stable(feature = "rust1", since = "1.0.0")]
624 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
629 /// The `Octal` trait should format its output as a number in base-8.
631 /// For primitive signed integers (`i8` to `i128`, and `isize`),
632 /// negative values are formatted as the two’s complement representation.
634 /// The alternate flag, `#`, adds a `0o` in front of the output.
636 /// For more information on formatters, see [the module-level documentation][module].
638 /// [module]: ../../std/fmt/index.html
642 /// Basic usage with `i32`:
645 /// let x = 42; // 42 is '52' in octal
647 /// assert_eq!(format!("{:o}", x), "52");
648 /// assert_eq!(format!("{:#o}", x), "0o52");
650 /// assert_eq!(format!("{:o}", -16), "37777777760");
653 /// Implementing `Octal` on a type:
658 /// struct Length(i32);
660 /// impl fmt::Octal for Length {
661 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
662 /// let val = self.0;
664 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
668 /// let l = Length(9);
670 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
672 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
674 #[stable(feature = "rust1", since = "1.0.0")]
676 /// Formats the value using the given formatter.
677 #[stable(feature = "rust1", since = "1.0.0")]
678 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
683 /// The `Binary` trait should format its output as a number in binary.
685 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
686 /// negative values are formatted as the two’s complement representation.
688 /// The alternate flag, `#`, adds a `0b` in front of the output.
690 /// For more information on formatters, see [the module-level documentation][module].
694 /// Basic usage with [`i32`]:
697 /// let x = 42; // 42 is '101010' in binary
699 /// assert_eq!(format!("{:b}", x), "101010");
700 /// assert_eq!(format!("{:#b}", x), "0b101010");
702 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
705 /// Implementing `Binary` on a type:
710 /// struct Length(i32);
712 /// impl fmt::Binary for Length {
713 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
714 /// let val = self.0;
716 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
720 /// let l = Length(107);
722 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
725 /// format!("l as binary is: {:#032b}", l),
726 /// "l as binary is: 0b000000000000000000000001101011"
730 /// [module]: ../../std/fmt/index.html
731 /// [`i8`]: ../../std/primitive.i8.html
732 /// [`i128`]: ../../std/primitive.i128.html
733 /// [`isize`]: ../../std/primitive.isize.html
734 /// [`i32`]: ../../std/primitive.i32.html
735 #[stable(feature = "rust1", since = "1.0.0")]
737 /// Formats the value using the given formatter.
738 #[stable(feature = "rust1", since = "1.0.0")]
739 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
744 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
747 /// For primitive signed integers (`i8` to `i128`, and `isize`),
748 /// negative values are formatted as the two’s complement representation.
750 /// The alternate flag, `#`, adds a `0x` in front of the output.
752 /// For more information on formatters, see [the module-level documentation][module].
754 /// [module]: ../../std/fmt/index.html
758 /// Basic usage with `i32`:
761 /// let x = 42; // 42 is '2a' in hex
763 /// assert_eq!(format!("{:x}", x), "2a");
764 /// assert_eq!(format!("{:#x}", x), "0x2a");
766 /// assert_eq!(format!("{:x}", -16), "fffffff0");
769 /// Implementing `LowerHex` on a type:
774 /// struct Length(i32);
776 /// impl fmt::LowerHex for Length {
777 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778 /// let val = self.0;
780 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
784 /// let l = Length(9);
786 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
788 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
790 #[stable(feature = "rust1", since = "1.0.0")]
792 /// Formats the value using the given formatter.
793 #[stable(feature = "rust1", since = "1.0.0")]
794 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
799 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
802 /// For primitive signed integers (`i8` to `i128`, and `isize`),
803 /// negative values are formatted as the two’s complement representation.
805 /// The alternate flag, `#`, adds a `0x` in front of the output.
807 /// For more information on formatters, see [the module-level documentation][module].
809 /// [module]: ../../std/fmt/index.html
813 /// Basic usage with `i32`:
816 /// let x = 42; // 42 is '2A' in hex
818 /// assert_eq!(format!("{:X}", x), "2A");
819 /// assert_eq!(format!("{:#X}", x), "0x2A");
821 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
824 /// Implementing `UpperHex` on a type:
829 /// struct Length(i32);
831 /// impl fmt::UpperHex for Length {
832 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
833 /// let val = self.0;
835 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
839 /// let l = Length(i32::max_value());
841 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
843 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
845 #[stable(feature = "rust1", since = "1.0.0")]
847 /// Formats the value using the given formatter.
848 #[stable(feature = "rust1", since = "1.0.0")]
849 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
854 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
857 /// For more information on formatters, see [the module-level documentation][module].
859 /// [module]: ../../std/fmt/index.html
863 /// Basic usage with `&i32`:
868 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
871 /// Implementing `Pointer` on a type:
876 /// struct Length(i32);
878 /// impl fmt::Pointer for Length {
879 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
882 /// let ptr = self as *const Self;
883 /// fmt::Pointer::fmt(&ptr, f)
887 /// let l = Length(42);
889 /// println!("l is in memory here: {:p}", l);
891 /// let l_ptr = format!("{:018p}", l);
892 /// assert_eq!(l_ptr.len(), 18);
893 /// assert_eq!(&l_ptr[..2], "0x");
895 #[stable(feature = "rust1", since = "1.0.0")]
897 /// Formats the value using the given formatter.
898 #[stable(feature = "rust1", since = "1.0.0")]
899 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
904 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
906 /// For more information on formatters, see [the module-level documentation][module].
908 /// [module]: ../../std/fmt/index.html
912 /// Basic usage with `f64`:
915 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
917 /// assert_eq!(format!("{:e}", x), "4.2e1");
920 /// Implementing `LowerExp` on a type:
925 /// struct Length(i32);
927 /// impl fmt::LowerExp for Length {
928 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
929 /// let val = f64::from(self.0);
930 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
934 /// let l = Length(100);
937 /// format!("l in scientific notation is: {:e}", l),
938 /// "l in scientific notation is: 1e2"
942 /// format!("l in scientific notation is: {:05e}", l),
943 /// "l in scientific notation is: 001e2"
946 #[stable(feature = "rust1", since = "1.0.0")]
948 /// Formats the value using the given formatter.
949 #[stable(feature = "rust1", since = "1.0.0")]
950 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
955 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
957 /// For more information on formatters, see [the module-level documentation][module].
959 /// [module]: ../../std/fmt/index.html
963 /// Basic usage with `f64`:
966 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
968 /// assert_eq!(format!("{:E}", x), "4.2E1");
971 /// Implementing `UpperExp` on a type:
976 /// struct Length(i32);
978 /// impl fmt::UpperExp for Length {
979 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
980 /// let val = f64::from(self.0);
981 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
985 /// let l = Length(100);
988 /// format!("l in scientific notation is: {:E}", l),
989 /// "l in scientific notation is: 1E2"
993 /// format!("l in scientific notation is: {:05E}", l),
994 /// "l in scientific notation is: 001E2"
997 #[stable(feature = "rust1", since = "1.0.0")]
999 /// Formats the value using the given formatter.
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1004 /// The `write` function takes an output stream, and an `Arguments` struct
1005 /// that can be precompiled with the `format_args!` macro.
1007 /// The arguments will be formatted according to the specified format string
1008 /// into the output stream provided.
1017 /// let mut output = String::new();
1018 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1019 /// .expect("Error occurred while trying to write in String");
1020 /// assert_eq!(output, "Hello world!");
1023 /// Please note that using [`write!`] might be preferable. Example:
1026 /// use std::fmt::Write;
1028 /// let mut output = String::new();
1029 /// write!(&mut output, "Hello {}!", "world")
1030 /// .expect("Error occurred while trying to write in String");
1031 /// assert_eq!(output, "Hello world!");
1034 /// [`write!`]: ../../std/macro.write.html
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1037 let mut formatter = Formatter {
1042 align: rt::v1::Alignment::Unknown,
1050 // We can use default formatting parameters for all arguments.
1051 for (arg, piece) in args.args.iter().zip(args.pieces.iter()) {
1052 formatter.buf.write_str(*piece)?;
1053 (arg.formatter)(arg.value, &mut formatter)?;
1058 // Every spec has a corresponding argument that is preceded by
1060 for (arg, piece) in fmt.iter().zip(args.pieces.iter()) {
1061 formatter.buf.write_str(*piece)?;
1062 run(&mut formatter, arg, &args.args)?;
1068 // There can be only one trailing string piece left.
1069 if let Some(piece) = args.pieces.get(idx) {
1070 formatter.buf.write_str(*piece)?;
1076 fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1077 fmt.fill = arg.format.fill;
1078 fmt.align = arg.format.align;
1079 fmt.flags = arg.format.flags;
1080 fmt.width = getcount(args, &arg.format.width);
1081 fmt.precision = getcount(args, &arg.format.precision);
1083 // Extract the correct argument
1084 let value = args[arg.position];
1086 // Then actually do some printing
1087 (value.formatter)(value.value, fmt)
1090 fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1092 rt::v1::Count::Is(n) => Some(n),
1093 rt::v1::Count::Implied => None,
1094 rt::v1::Count::Param(i) => args[i].as_usize(),
1098 /// Padding after the end of something. Returned by `Formatter::padding`.
1099 #[must_use = "don't forget to write the post padding"]
1100 struct PostPadding {
1106 fn new(fill: char, padding: usize) -> PostPadding {
1107 PostPadding { fill, padding }
1110 /// Write this post padding.
1111 fn write(self, buf: &mut dyn Write) -> Result {
1112 for _ in 0..self.padding {
1113 buf.write_char(self.fill)?;
1119 impl<'a> Formatter<'a> {
1120 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1123 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1126 // We want to change this
1127 buf: wrap(self.buf),
1129 // And preserve these
1134 precision: self.precision,
1138 // Helper methods used for padding and processing formatting arguments that
1139 // all formatting traits can use.
1141 /// Performs the correct padding for an integer which has already been
1142 /// emitted into a str. The str should *not* contain the sign for the
1143 /// integer, that will be added by this method.
1147 /// * is_nonnegative - whether the original integer was either positive or zero.
1148 /// * prefix - if the '#' character (Alternate) is provided, this
1149 /// is the prefix to put in front of the number.
1150 /// * buf - the byte array that the number has been formatted into
1152 /// This function will correctly account for the flags provided as well as
1153 /// the minimum width. It will not take precision into account.
1160 /// struct Foo { nb: i32 };
1163 /// fn new(nb: i32) -> Foo {
1170 /// impl fmt::Display for Foo {
1171 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1172 /// // We need to remove "-" from the number output.
1173 /// let tmp = self.nb.abs().to_string();
1175 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1179 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1180 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1181 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1182 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1186 let mut width = buf.len();
1188 let mut sign = None;
1189 if !is_nonnegative {
1192 } else if self.sign_plus() {
1197 let prefix = if self.alternate() {
1198 width += prefix.chars().count();
1204 // Writes the sign if it exists, and then the prefix if it was requested
1206 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1207 if let Some(c) = sign {
1208 f.buf.write_char(c)?;
1210 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1213 // The `width` field is more of a `min-width` parameter at this point.
1215 // If there's no minimum length requirements then we can just
1218 write_prefix(self, sign, prefix)?;
1219 self.buf.write_str(buf)
1221 // Check if we're over the minimum width, if so then we can also
1222 // just write the bytes.
1223 Some(min) if width >= min => {
1224 write_prefix(self, sign, prefix)?;
1225 self.buf.write_str(buf)
1227 // The sign and prefix goes before the padding if the fill character
1229 Some(min) if self.sign_aware_zero_pad() => {
1230 let old_fill = crate::mem::replace(&mut self.fill, '0');
1231 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1232 write_prefix(self, sign, prefix)?;
1233 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1234 self.buf.write_str(buf)?;
1235 post_padding.write(self.buf)?;
1236 self.fill = old_fill;
1237 self.align = old_align;
1240 // Otherwise, the sign and prefix goes after the padding
1242 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1243 write_prefix(self, sign, prefix)?;
1244 self.buf.write_str(buf)?;
1245 post_padding.write(self.buf)
1250 /// This function takes a string slice and emits it to the internal buffer
1251 /// after applying the relevant formatting flags specified. The flags
1252 /// recognized for generic strings are:
1254 /// * width - the minimum width of what to emit
1255 /// * fill/align - what to emit and where to emit it if the string
1256 /// provided needs to be padded
1257 /// * precision - the maximum length to emit, the string is truncated if it
1258 /// is longer than this length
1260 /// Notably this function ignores the `flag` parameters.
1269 /// impl fmt::Display for Foo {
1270 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1271 /// formatter.pad("Foo")
1275 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1276 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 pub fn pad(&mut self, s: &str) -> Result {
1280 // Make sure there's a fast path up front
1281 if self.width.is_none() && self.precision.is_none() {
1282 return self.buf.write_str(s);
1284 // The `precision` field can be interpreted as a `max-width` for the
1285 // string being formatted.
1286 let s = if let Some(max) = self.precision {
1287 // If our string is longer that the precision, then we must have
1288 // truncation. However other flags like `fill`, `width` and `align`
1289 // must act as always.
1290 if let Some((i, _)) = s.char_indices().nth(max) {
1291 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1292 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1293 // `unsafe` and otherwise don't emit any panic-related code
1295 s.get(..i).unwrap_or(&s)
1302 // The `width` field is more of a `min-width` parameter at this point.
1304 // If we're under the maximum length, and there's no minimum length
1305 // requirements, then we can just emit the string
1306 None => self.buf.write_str(s),
1307 // If we're under the maximum width, check if we're over the minimum
1308 // width, if so it's as easy as just emitting the string.
1309 Some(width) if s.chars().count() >= width => self.buf.write_str(s),
1310 // If we're under both the maximum and the minimum width, then fill
1311 // up the minimum width with the specified string + some alignment.
1313 let align = rt::v1::Alignment::Left;
1314 let post_padding = self.padding(width - s.chars().count(), align)?;
1315 self.buf.write_str(s)?;
1316 post_padding.write(self.buf)
1321 /// Write the pre-padding and return the unwritten post-padding. Callers are
1322 /// responsible for ensuring post-padding is written after the thing that is
1327 default: rt::v1::Alignment,
1328 ) -> result::Result<PostPadding, Error> {
1329 let align = match self.align {
1330 rt::v1::Alignment::Unknown => default,
1334 let (pre_pad, post_pad) = match align {
1335 rt::v1::Alignment::Left => (0, padding),
1336 rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1337 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1340 for _ in 0..pre_pad {
1341 self.buf.write_char(self.fill)?;
1344 Ok(PostPadding::new(self.fill, post_pad))
1347 /// Takes the formatted parts and applies the padding.
1348 /// Assumes that the caller already has rendered the parts with required precision,
1349 /// so that `self.precision` can be ignored.
1350 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted<'_>) -> Result {
1351 if let Some(mut width) = self.width {
1352 // for the sign-aware zero padding, we render the sign first and
1353 // behave as if we had no sign from the beginning.
1354 let mut formatted = formatted.clone();
1355 let old_fill = self.fill;
1356 let old_align = self.align;
1357 let mut align = old_align;
1358 if self.sign_aware_zero_pad() {
1359 // a sign always goes first
1360 let sign = formatted.sign;
1361 self.buf.write_str(sign)?;
1363 // remove the sign from the formatted parts
1364 formatted.sign = "";
1365 width = width.saturating_sub(sign.len());
1366 align = rt::v1::Alignment::Right;
1368 self.align = rt::v1::Alignment::Right;
1371 // remaining parts go through the ordinary padding process.
1372 let len = formatted.len();
1373 let ret = if width <= len {
1375 self.write_formatted_parts(&formatted)
1377 let post_padding = self.padding(width - len, align)?;
1378 self.write_formatted_parts(&formatted)?;
1379 post_padding.write(self.buf)
1381 self.fill = old_fill;
1382 self.align = old_align;
1385 // this is the common case and we take a shortcut
1386 self.write_formatted_parts(formatted)
1390 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted<'_>) -> Result {
1391 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1392 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1395 if !formatted.sign.is_empty() {
1396 self.buf.write_str(formatted.sign)?;
1398 for part in formatted.parts {
1400 flt2dec::Part::Zero(mut nzeroes) => {
1401 const ZEROES: &str = // 64 zeroes
1402 "0000000000000000000000000000000000000000000000000000000000000000";
1403 while nzeroes > ZEROES.len() {
1404 self.buf.write_str(ZEROES)?;
1405 nzeroes -= ZEROES.len();
1408 self.buf.write_str(&ZEROES[..nzeroes])?;
1411 flt2dec::Part::Num(mut v) => {
1413 let len = part.len();
1414 for c in s[..len].iter_mut().rev() {
1415 *c = b'0' + (v % 10) as u8;
1418 write_bytes(self.buf, &s[..len])?;
1420 flt2dec::Part::Copy(buf) => {
1421 write_bytes(self.buf, buf)?;
1428 /// Writes some data to the underlying buffer contained within this
1438 /// impl fmt::Display for Foo {
1439 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1440 /// formatter.write_str("Foo")
1441 /// // This is equivalent to:
1442 /// // write!(formatter, "Foo")
1446 /// assert_eq!(&format!("{}", Foo), "Foo");
1447 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1449 #[stable(feature = "rust1", since = "1.0.0")]
1450 pub fn write_str(&mut self, data: &str) -> Result {
1451 self.buf.write_str(data)
1454 /// Writes some formatted information into this instance.
1461 /// struct Foo(i32);
1463 /// impl fmt::Display for Foo {
1464 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1465 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1469 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1470 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1474 write(self.buf, fmt)
1477 /// Flags for formatting
1478 #[stable(feature = "rust1", since = "1.0.0")]
1481 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1482 or `sign_aware_zero_pad` methods instead"
1484 pub fn flags(&self) -> u32 {
1488 /// Character used as 'fill' whenever there is alignment.
1497 /// impl fmt::Display for Foo {
1498 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1499 /// let c = formatter.fill();
1500 /// if let Some(width) = formatter.width() {
1501 /// for _ in 0..width {
1502 /// write!(formatter, "{}", c)?;
1506 /// write!(formatter, "{}", c)
1511 /// // We set alignment to the left with ">".
1512 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1513 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1515 #[stable(feature = "fmt_flags", since = "1.5.0")]
1516 pub fn fill(&self) -> char {
1520 /// Flag indicating what form of alignment was requested.
1525 /// extern crate core;
1527 /// use std::fmt::{self, Alignment};
1531 /// impl fmt::Display for Foo {
1532 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1533 /// let s = if let Some(s) = formatter.align() {
1535 /// Alignment::Left => "left",
1536 /// Alignment::Right => "right",
1537 /// Alignment::Center => "center",
1542 /// write!(formatter, "{}", s)
1546 /// assert_eq!(&format!("{:<}", Foo), "left");
1547 /// assert_eq!(&format!("{:>}", Foo), "right");
1548 /// assert_eq!(&format!("{:^}", Foo), "center");
1549 /// assert_eq!(&format!("{}", Foo), "into the void");
1551 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1552 pub fn align(&self) -> Option<Alignment> {
1554 rt::v1::Alignment::Left => Some(Alignment::Left),
1555 rt::v1::Alignment::Right => Some(Alignment::Right),
1556 rt::v1::Alignment::Center => Some(Alignment::Center),
1557 rt::v1::Alignment::Unknown => None,
1561 /// Optionally specified integer width that the output should be.
1568 /// struct Foo(i32);
1570 /// impl fmt::Display for Foo {
1571 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1572 /// if let Some(width) = formatter.width() {
1573 /// // If we received a width, we use it
1574 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1576 /// // Otherwise we do nothing special
1577 /// write!(formatter, "Foo({})", self.0)
1582 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1583 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1585 #[stable(feature = "fmt_flags", since = "1.5.0")]
1586 pub fn width(&self) -> Option<usize> {
1590 /// Optionally specified precision for numeric types.
1597 /// struct Foo(f32);
1599 /// impl fmt::Display for Foo {
1600 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1601 /// if let Some(precision) = formatter.precision() {
1602 /// // If we received a precision, we use it.
1603 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1605 /// // Otherwise we default to 2.
1606 /// write!(formatter, "Foo({:.2})", self.0)
1611 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1612 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1614 #[stable(feature = "fmt_flags", since = "1.5.0")]
1615 pub fn precision(&self) -> Option<usize> {
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_plus() {
1631 /// write!(formatter,
1633 /// if self.0 < 0 { '-' } else { '+' },
1636 /// write!(formatter, "Foo({})", self.0)
1641 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1642 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1644 #[stable(feature = "fmt_flags", since = "1.5.0")]
1645 pub fn sign_plus(&self) -> bool {
1646 self.flags & (1 << FlagV1::SignPlus as u32) != 0
1649 /// Determines if the `-` flag was specified.
1656 /// struct Foo(i32);
1658 /// impl fmt::Display for Foo {
1659 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1660 /// if formatter.sign_minus() {
1661 /// // You want a minus sign? Have one!
1662 /// write!(formatter, "-Foo({})", self.0)
1664 /// write!(formatter, "Foo({})", self.0)
1669 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1670 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1672 #[stable(feature = "fmt_flags", since = "1.5.0")]
1673 pub fn sign_minus(&self) -> bool {
1674 self.flags & (1 << FlagV1::SignMinus as u32) != 0
1677 /// Determines if the `#` flag was specified.
1684 /// struct Foo(i32);
1686 /// impl fmt::Display for Foo {
1687 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1688 /// if formatter.alternate() {
1689 /// write!(formatter, "Foo({})", self.0)
1691 /// write!(formatter, "{}", self.0)
1696 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1697 /// assert_eq!(&format!("{}", Foo(23)), "23");
1699 #[stable(feature = "fmt_flags", since = "1.5.0")]
1700 pub fn alternate(&self) -> bool {
1701 self.flags & (1 << FlagV1::Alternate as u32) != 0
1704 /// Determines if the `0` flag was specified.
1711 /// struct Foo(i32);
1713 /// impl fmt::Display for Foo {
1714 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1715 /// assert!(formatter.sign_aware_zero_pad());
1716 /// assert_eq!(formatter.width(), Some(4));
1717 /// // We ignore the formatter's options.
1718 /// write!(formatter, "{}", self.0)
1722 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1724 #[stable(feature = "fmt_flags", since = "1.5.0")]
1725 pub fn sign_aware_zero_pad(&self) -> bool {
1726 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1729 // FIXME: Decide what public API we want for these two flags.
1730 // https://github.com/rust-lang/rust/issues/48584
1731 fn debug_lower_hex(&self) -> bool {
1732 self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1735 fn debug_upper_hex(&self) -> bool {
1736 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1739 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1740 /// [`fmt::Debug`] implementations for structs.
1742 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1743 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1749 /// use std::net::Ipv4Addr;
1757 /// impl fmt::Debug for Foo {
1758 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1759 /// fmt.debug_struct("Foo")
1760 /// .field("bar", &self.bar)
1761 /// .field("baz", &self.baz)
1762 /// .field("addr", &format_args!("{}", self.addr))
1768 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1769 /// format!("{:?}", Foo {
1771 /// baz: "Hello World".to_string(),
1772 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1776 #[stable(feature = "debug_builders", since = "1.2.0")]
1777 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1778 builders::debug_struct_new(self, name)
1781 /// Creates a `DebugTuple` builder designed to assist with creation of
1782 /// `fmt::Debug` implementations for tuple structs.
1788 /// use std::marker::PhantomData;
1790 /// struct Foo<T>(i32, String, PhantomData<T>);
1792 /// impl<T> fmt::Debug for Foo<T> {
1793 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1794 /// fmt.debug_tuple("Foo")
1797 /// .field(&format_args!("_"))
1803 /// "Foo(10, \"Hello\", _)",
1804 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1807 #[stable(feature = "debug_builders", since = "1.2.0")]
1808 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1809 builders::debug_tuple_new(self, name)
1812 /// Creates a `DebugList` builder designed to assist with creation of
1813 /// `fmt::Debug` implementations for list-like structures.
1820 /// struct Foo(Vec<i32>);
1822 /// impl fmt::Debug for Foo {
1823 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1824 /// fmt.debug_list().entries(self.0.iter()).finish()
1828 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
1830 #[stable(feature = "debug_builders", since = "1.2.0")]
1831 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1832 builders::debug_list_new(self)
1835 /// Creates a `DebugSet` builder designed to assist with creation of
1836 /// `fmt::Debug` implementations for set-like structures.
1843 /// struct Foo(Vec<i32>);
1845 /// impl fmt::Debug for Foo {
1846 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1847 /// fmt.debug_set().entries(self.0.iter()).finish()
1851 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
1854 /// [`format_args!`]: ../../std/macro.format_args.html
1856 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1857 /// to build a list of match arms:
1862 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1863 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1865 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1867 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1869 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1870 /// L::fmt(&(self.0).0, fmt)?;
1871 /// fmt.write_str(" => ")?;
1872 /// R::fmt(&(self.0).1, fmt)
1876 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1878 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1880 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1882 /// .entries(self.0.iter().map(Arm))
1883 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1888 #[stable(feature = "debug_builders", since = "1.2.0")]
1889 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1890 builders::debug_set_new(self)
1893 /// Creates a `DebugMap` builder designed to assist with creation of
1894 /// `fmt::Debug` implementations for map-like structures.
1901 /// struct Foo(Vec<(String, i32)>);
1903 /// impl fmt::Debug for Foo {
1904 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1905 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1910 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1911 /// r#"{"A": 10, "B": 11}"#
1914 #[stable(feature = "debug_builders", since = "1.2.0")]
1915 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1916 builders::debug_map_new(self)
1920 #[stable(since = "1.2.0", feature = "formatter_write")]
1921 impl Write for Formatter<'_> {
1922 fn write_str(&mut self, s: &str) -> Result {
1923 self.buf.write_str(s)
1926 fn write_char(&mut self, c: char) -> Result {
1927 self.buf.write_char(c)
1930 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
1931 write(self.buf, args)
1935 #[stable(feature = "rust1", since = "1.0.0")]
1936 impl Display for Error {
1937 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1938 Display::fmt("an error occurred when formatting an argument", f)
1942 // Implementations of the core formatting traits
1944 macro_rules! fmt_refs {
1945 ($($tr:ident),*) => {
1947 #[stable(feature = "rust1", since = "1.0.0")]
1948 impl<T: ?Sized + $tr> $tr for &T {
1949 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 impl<T: ?Sized + $tr> $tr for &mut T {
1953 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
1959 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1961 #[unstable(feature = "never_type", issue = "35121")]
1963 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
1968 #[unstable(feature = "never_type", issue = "35121")]
1969 impl Display for ! {
1970 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 impl Debug for bool {
1978 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1979 Display::fmt(self, f)
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl Display for bool {
1985 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1986 Display::fmt(if *self { "true" } else { "false" }, f)
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 impl Debug for str {
1992 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1995 for (i, c) in self.char_indices() {
1996 let esc = c.escape_debug();
1997 // If char needs escaping, flush backlog so far and write, else skip
1999 f.write_str(&self[from..i])?;
2003 from = i + c.len_utf8();
2006 f.write_str(&self[from..])?;
2011 #[stable(feature = "rust1", since = "1.0.0")]
2012 impl Display for str {
2013 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2018 #[stable(feature = "rust1", since = "1.0.0")]
2019 impl Debug for char {
2020 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2021 f.write_char('\'')?;
2022 for c in self.escape_debug() {
2029 #[stable(feature = "rust1", since = "1.0.0")]
2030 impl Display for char {
2031 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2032 if f.width.is_none() && f.precision.is_none() {
2035 f.pad(self.encode_utf8(&mut [0; 4]))
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 impl<T: ?Sized> Pointer for *const T {
2042 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2043 let old_width = f.width;
2044 let old_flags = f.flags;
2046 // The alternate flag is already treated by LowerHex as being special-
2047 // it denotes whether to prefix with 0x. We use it to work out whether
2048 // or not to zero extend, and then unconditionally set it to get the
2051 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2053 if f.width.is_none() {
2054 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2057 f.flags |= 1 << (FlagV1::Alternate as u32);
2059 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2061 f.width = old_width;
2062 f.flags = old_flags;
2068 #[stable(feature = "rust1", since = "1.0.0")]
2069 impl<T: ?Sized> Pointer for *mut T {
2070 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2071 Pointer::fmt(&(*self as *const T), f)
2075 #[stable(feature = "rust1", since = "1.0.0")]
2076 impl<T: ?Sized> Pointer for &T {
2077 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2078 Pointer::fmt(&(*self as *const T), f)
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 impl<T: ?Sized> Pointer for &mut T {
2084 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2085 Pointer::fmt(&(&**self as *const T), f)
2089 // Implementation of Display/Debug for various core types
2091 #[stable(feature = "rust1", since = "1.0.0")]
2092 impl<T: ?Sized> Debug for *const T {
2093 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2094 Pointer::fmt(self, f)
2097 #[stable(feature = "rust1", since = "1.0.0")]
2098 impl<T: ?Sized> Debug for *mut T {
2099 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2100 Pointer::fmt(self, f)
2105 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2108 macro_rules! tuple {
2110 ( $($name:ident,)+ ) => (
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2113 #[allow(non_snake_case, unused_assignments)]
2114 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2115 let mut builder = f.debug_tuple("");
2116 let ($(ref $name,)+) = *self;
2118 builder.field(&$name);
2124 peel! { $($name,)+ }
2128 macro_rules! last_type {
2129 ($a:ident,) => { $a };
2130 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2133 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 impl<T: Debug> Debug for [T] {
2137 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2138 f.debug_list().entries(self.iter()).finish()
2142 #[stable(feature = "rust1", since = "1.0.0")]
2145 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2149 #[stable(feature = "rust1", since = "1.0.0")]
2150 impl<T: ?Sized> Debug for PhantomData<T> {
2151 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2152 f.pad("PhantomData")
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 impl<T: Copy + Debug> Debug for Cell<T> {
2158 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2159 f.debug_struct("Cell").field("value", &self.get()).finish()
2163 #[stable(feature = "rust1", since = "1.0.0")]
2164 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2165 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2166 match self.try_borrow() {
2167 Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2169 // The RefCell is mutably borrowed so we can't look at its value
2170 // here. Show a placeholder instead.
2171 struct BorrowedPlaceholder;
2173 impl Debug for BorrowedPlaceholder {
2174 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2175 f.write_str("<borrowed>")
2179 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2185 #[stable(feature = "rust1", since = "1.0.0")]
2186 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2187 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2188 Debug::fmt(&**self, f)
2192 #[stable(feature = "rust1", since = "1.0.0")]
2193 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2194 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2195 Debug::fmt(&*(self.deref()), f)
2199 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2200 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2201 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2206 // If you expected tests to be here, look instead at the ui/ifmt.rs test,
2207 // it's a lot easier than creating all of the rt::Piece structures here.