1 //! Utilities for formatting and printing strings.
3 #![stable(feature = "rust1", since = "1.0.0")]
5 use crate::cell::{Cell, Ref, RefCell, RefMut, UnsafeCell};
6 use crate::marker::PhantomData;
8 use crate::num::flt2dec;
17 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
18 /// Possible alignments returned by `Formatter::align`
21 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
22 /// Indication that contents should be left-aligned.
24 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
25 /// Indication that contents should be right-aligned.
27 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
28 /// Indication that contents should be center-aligned.
32 #[stable(feature = "debug_builders", since = "1.2.0")]
33 pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
35 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
41 /// The type returned by formatter methods.
55 /// impl fmt::Display for Triangle {
56 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
61 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
63 /// assert_eq!(format!("{}", pythagorean_triple), "(3, 4, 5)");
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub type Result = result::Result<(), Error>;
68 /// The error type which is returned from formatting a message into a stream.
70 /// This type does not support transmission of an error other than that an error
71 /// occurred. Any extra information must be arranged to be transmitted through
74 /// An important thing to remember is that the type `fmt::Error` should not be
75 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
78 /// [`std::io::Error`]: ../../std/io/struct.Error.html
79 /// [`std::error::Error`]: ../../std/error/trait.Error.html
84 /// use std::fmt::{self, write};
86 /// let mut output = String::new();
87 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
88 /// panic!("An error occurred");
91 #[stable(feature = "rust1", since = "1.0.0")]
92 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
95 /// A collection of methods that are required to format a message into a stream.
97 /// This trait is the type which this modules requires when formatting
98 /// information. This is similar to the standard library's [`io::Write`] trait,
99 /// but it is only intended for use in libcore.
101 /// This trait should generally not be implemented by consumers of the standard
102 /// library. The [`write!`] macro accepts an instance of [`io::Write`], and the
103 /// [`io::Write`] trait is favored over implementing this trait.
105 /// [`write!`]: ../../std/macro.write.html
106 /// [`io::Write`]: ../../std/io/trait.Write.html
107 #[stable(feature = "rust1", since = "1.0.0")]
109 /// Writes a string slice into this writer, returning whether the write
112 /// This method can only succeed if the entire string slice was successfully
113 /// written, and this method will not return until all data has been
114 /// written or an error occurs.
118 /// This function will return an instance of [`Error`] on error.
123 /// use std::fmt::{Error, Write};
125 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
129 /// let mut buf = String::new();
130 /// writer(&mut buf, "hola").unwrap();
131 /// assert_eq!(&buf, "hola");
133 #[stable(feature = "rust1", since = "1.0.0")]
134 fn write_str(&mut self, s: &str) -> Result;
136 /// Writes a [`char`] into this writer, returning whether the write succeeded.
138 /// A single [`char`] may be encoded as more than one byte.
139 /// This method can only succeed if the entire byte sequence was successfully
140 /// written, and this method will not return until all data has been
141 /// written or an error occurs.
145 /// This function will return an instance of [`Error`] on error.
150 /// use std::fmt::{Error, Write};
152 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
156 /// let mut buf = String::new();
157 /// writer(&mut buf, 'a').unwrap();
158 /// writer(&mut buf, 'b').unwrap();
159 /// assert_eq!(&buf, "ab");
161 #[stable(feature = "fmt_write_char", since = "1.1.0")]
162 fn write_char(&mut self, c: char) -> Result {
163 self.write_str(c.encode_utf8(&mut [0; 4]))
166 /// Glue for usage of the [`write!`] macro with implementors of this trait.
168 /// This method should generally not be invoked manually, but rather through
169 /// the [`write!`] macro itself.
171 /// [`write!`]: ../../std/macro.write.html
176 /// use std::fmt::{Error, Write};
178 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
179 /// f.write_fmt(format_args!("{}", s))
182 /// let mut buf = String::new();
183 /// writer(&mut buf, "world").unwrap();
184 /// assert_eq!(&buf, "world");
186 #[stable(feature = "rust1", since = "1.0.0")]
187 fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
188 write(&mut self, args)
192 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
193 impl<W: Write + ?Sized> Write for &mut W {
194 fn write_str(&mut self, s: &str) -> Result {
195 (**self).write_str(s)
198 fn write_char(&mut self, c: char) -> Result {
199 (**self).write_char(c)
202 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
203 (**self).write_fmt(args)
207 /// Configuration for formatting.
209 /// A `Formatter` represents various options related to formatting. Users do not
210 /// construct `Formatter`s directly; a mutable reference to one is passed to
211 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
213 /// To interact with a `Formatter`, you'll call various methods to change the
214 /// various options related to formatting. For examples, please see the
215 /// documentation of the methods defined on `Formatter` below.
216 #[allow(missing_debug_implementations)]
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub struct Formatter<'a> {
221 align: rt::v1::Alignment,
222 width: Option<usize>,
223 precision: Option<usize>,
225 buf: &'a mut (dyn Write + 'a),
228 // NB. Argument is essentially an optimized partially applied formatting function,
229 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
235 /// This struct represents the generic "argument" which is taken by the Xprintf
236 /// family of functions. It contains a function to format the given value. At
237 /// compile time it is ensured that the function and the value have the correct
238 /// types, and then this struct is used to canonicalize arguments to one type.
239 #[derive(Copy, Clone)]
240 #[allow(missing_debug_implementations)]
241 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
243 pub struct ArgumentV1<'a> {
245 formatter: fn(&Opaque, &mut Formatter<'_>) -> Result,
248 // This guarantees a single stable value for the function pointer associated with
249 // indices/counts in the formatting infrastructure.
251 // Note that a function defined as such would not be correct as functions are
252 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
253 // address is not considered important to LLVM and as such the as_usize cast
254 // could have been miscompiled. In practice, we never call as_usize on non-usize
255 // containing data (as a matter of static generation of the formatting
256 // arguments), so this is merely an additional check.
258 // We primarily want to ensure that the function pointer at `USIZE_MARKER` has
259 // an address corresponding *only* to functions that also take `&usize` as their
260 // first argument. The read_volatile here ensures that we can safely ready out a
261 // usize from the passed reference and that this address does not point at a
262 // non-usize taking function.
263 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
264 static USIZE_MARKER: fn(&usize, &mut Formatter<'_>) -> Result = |ptr, _| {
265 // SAFETY: ptr is a reference
266 let _v: usize = unsafe { crate::ptr::read_volatile(ptr) };
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 // SAFETY: `mem::transmute(x)` is safe because
275 // 1. `&'b T` keeps the lifetime it originated with `'b`
276 // (so as to not have an unbounded lifetime)
277 // 2. `&'b T` and `&'b Opaque` have the same memory layout
278 // (when `T` is `Sized`, as it is here)
279 // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
280 // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
281 // (as long as `T` is `Sized`)
282 unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) } }
286 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
287 pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
288 ArgumentV1::new(x, USIZE_MARKER)
291 fn as_usize(&self) -> Option<usize> {
292 if self.formatter as usize == USIZE_MARKER as usize {
293 // SAFETY: The `formatter` field is only set to USIZE_MARKER if
294 // the value is a usize, so this is safe
295 Some(unsafe { *(self.value as *const _ as *const usize) })
302 // flags available in the v1 format of format_args
303 #[derive(Copy, Clone)]
313 impl<'a> Arguments<'a> {
314 /// When using the format_args!() macro, this function is used to generate the
315 /// Arguments structure.
318 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
319 pub fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
320 Arguments { pieces, fmt: None, args }
323 /// This function is used to specify nonstandard formatting parameters.
324 /// The `pieces` array must be at least as long as `fmt` to construct
325 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
326 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
327 /// created with `argumentusize`. However, failing to do so doesn't cause
328 /// unsafety, but will ignore invalid .
331 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
332 pub fn new_v1_formatted(
333 pieces: &'a [&'static str],
334 args: &'a [ArgumentV1<'a>],
335 fmt: &'a [rt::v1::Argument],
337 Arguments { pieces, fmt: Some(fmt), args }
340 /// Estimates the length of the formatted text.
342 /// This is intended to be used for setting initial `String` capacity
343 /// when using `format!`. Note: this is neither the lower nor upper bound.
346 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
347 pub fn estimated_capacity(&self) -> usize {
348 let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
350 if self.args.is_empty() {
352 } else if self.pieces[0] == "" && pieces_length < 16 {
353 // If the format string starts with an argument,
354 // don't preallocate anything, unless length
355 // of pieces is significant.
358 // There are some arguments, so any additional push
359 // will reallocate the string. To avoid that,
360 // we're "pre-doubling" the capacity here.
361 pieces_length.checked_mul(2).unwrap_or(0)
366 /// This structure represents a safely precompiled version of a format string
367 /// and its arguments. This cannot be generated at runtime because it cannot
368 /// safely be done, so no constructors are given and the fields are private
369 /// to prevent modification.
371 /// The [`format_args!`] macro will safely create an instance of this structure.
372 /// The macro validates the format string at compile-time so usage of the
373 /// [`write()`] and [`format()`] functions can be safely performed.
375 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
376 /// and `Display` contexts as seen below. The example also shows that `Debug`
377 /// and `Display` format to the same thing: the interpolated format string
378 /// in `format_args!`.
381 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
382 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
383 /// assert_eq!("1 foo 2", display);
384 /// assert_eq!(display, debug);
387 /// [`format()`]: ../../std/fmt/fn.format.html
388 #[stable(feature = "rust1", since = "1.0.0")]
389 #[derive(Copy, Clone)]
390 pub struct Arguments<'a> {
391 // Format string pieces to print.
392 pieces: &'a [&'static str],
394 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
395 fmt: Option<&'a [rt::v1::Argument]>,
397 // Dynamic arguments for interpolation, to be interleaved with string
398 // pieces. (Every argument is preceded by a string piece.)
399 args: &'a [ArgumentV1<'a>],
402 impl<'a> Arguments<'a> {
403 /// Get the formatted string, if it has no arguments to be formatted.
405 /// This can be used to avoid allocations in the most trivial case.
410 /// #![feature(fmt_as_str)]
412 /// use core::fmt::Arguments;
414 /// fn write_str(_: &str) { /* ... */ }
416 /// fn write_fmt(args: &Arguments) {
417 /// if let Some(s) = args.as_str() {
420 /// write_str(&args.to_string());
426 /// #![feature(fmt_as_str)]
428 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
429 /// assert_eq!(format_args!("").as_str(), Some(""));
430 /// assert_eq!(format_args!("{}", 1).as_str(), None);
432 #[unstable(feature = "fmt_as_str", issue = "74442")]
434 pub fn as_str(&self) -> Option<&'static str> {
435 match (self.pieces, self.args) {
436 ([], []) => Some(""),
437 ([s], []) => Some(s),
443 #[stable(feature = "rust1", since = "1.0.0")]
444 impl Debug for Arguments<'_> {
445 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
446 Display::fmt(self, fmt)
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl Display for Arguments<'_> {
452 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
453 write(fmt.buf, *self)
459 /// `Debug` should format the output in a programmer-facing, debugging context.
461 /// Generally speaking, you should just `derive` a `Debug` implementation.
463 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
465 /// For more information on formatters, see [the module-level documentation][self].
467 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
468 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
469 /// comma-separated list of each field's name and `Debug` value, then `}`. For
470 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
471 /// `Debug` values of the fields, then `)`.
475 /// Derived `Debug` formats are not stable, and so may change with future Rust
476 /// versions. Additionally, `Debug` implementations of types provided by the
477 /// standard library (`libstd`, `libcore`, `liballoc`, etc.) are not stable, and
478 /// may also change with future Rust versions.
482 /// Deriving an implementation:
491 /// let origin = Point { x: 0, y: 0 };
493 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
496 /// Manually implementing:
506 /// impl fmt::Debug for Point {
507 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508 /// f.debug_struct("Point")
509 /// .field("x", &self.x)
510 /// .field("y", &self.y)
515 /// let origin = Point { x: 0, y: 0 };
517 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
520 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
521 /// implementations, such as [`debug_struct`].
523 /// `Debug` implementations using either `derive` or the debug builder API
524 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
526 /// [`debug_struct`]: Formatter::debug_struct
528 /// Pretty-printing with `#?`:
537 /// let origin = Point { x: 0, y: 0 };
539 /// assert_eq!(format!("The origin is: {:#?}", origin),
540 /// "The origin is: Point {
546 #[stable(feature = "rust1", since = "1.0.0")]
547 #[rustc_on_unimplemented(
550 label = "`{Self}` cannot be formatted using `{{:?}}`",
551 note = "add `#[derive(Debug)]` or manually implement `{Debug}`"
553 message = "`{Self}` doesn't implement `{Debug}`",
554 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
556 #[doc(alias = "{:?}")]
557 #[rustc_diagnostic_item = "debug_trait"]
559 /// Formats the value using the given formatter.
566 /// struct Position {
571 /// impl fmt::Debug for Position {
572 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573 /// f.debug_tuple("")
574 /// .field(&self.longitude)
575 /// .field(&self.latitude)
580 /// let position = Position { longitude: 1.987, latitude: 2.983 };
581 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
583 /// assert_eq!(format!("{:#?}", position), "(
588 #[stable(feature = "rust1", since = "1.0.0")]
589 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
592 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
593 pub(crate) mod macros {
594 /// Derive macro generating an impl of the trait `Debug`.
595 #[rustc_builtin_macro]
596 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
597 #[allow_internal_unstable(core_intrinsics)]
598 pub macro Debug($item:item) {
599 /* compiler built-in */
602 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
604 pub use macros::Debug;
606 /// Format trait for an empty format, `{}`.
608 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
609 /// output, and so cannot be derived.
611 /// For more information on formatters, see [the module-level documentation][self].
615 /// Implementing `Display` on a type:
625 /// impl fmt::Display for Point {
626 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627 /// write!(f, "({}, {})", self.x, self.y)
631 /// let origin = Point { x: 0, y: 0 };
633 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
635 #[rustc_on_unimplemented(
637 _Self = "std::path::Path",
638 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
639 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
640 as they may contain non-Unicode data"
642 message = "`{Self}` doesn't implement `{Display}`",
643 label = "`{Self}` cannot be formatted with the default formatter",
644 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
647 #[stable(feature = "rust1", since = "1.0.0")]
649 /// Formats the value using the given formatter.
656 /// struct Position {
661 /// impl fmt::Display for Position {
662 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663 /// write!(f, "({}, {})", self.longitude, self.latitude)
667 /// assert_eq!("(1.987, 2.983)",
668 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
670 #[stable(feature = "rust1", since = "1.0.0")]
671 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
676 /// The `Octal` trait should format its output as a number in base-8.
678 /// For primitive signed integers (`i8` to `i128`, and `isize`),
679 /// negative values are formatted as the two’s complement representation.
681 /// The alternate flag, `#`, adds a `0o` in front of the output.
683 /// For more information on formatters, see [the module-level documentation][self].
687 /// Basic usage with `i32`:
690 /// let x = 42; // 42 is '52' in octal
692 /// assert_eq!(format!("{:o}", x), "52");
693 /// assert_eq!(format!("{:#o}", x), "0o52");
695 /// assert_eq!(format!("{:o}", -16), "37777777760");
698 /// Implementing `Octal` on a type:
703 /// struct Length(i32);
705 /// impl fmt::Octal for Length {
706 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707 /// let val = self.0;
709 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
713 /// let l = Length(9);
715 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
717 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
719 #[stable(feature = "rust1", since = "1.0.0")]
721 /// Formats the value using the given formatter.
722 #[stable(feature = "rust1", since = "1.0.0")]
723 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
728 /// The `Binary` trait should format its output as a number in binary.
730 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
731 /// negative values are formatted as the two’s complement representation.
733 /// The alternate flag, `#`, adds a `0b` in front of the output.
735 /// For more information on formatters, see [the module-level documentation][self].
739 /// Basic usage with [`i32`]:
742 /// let x = 42; // 42 is '101010' in binary
744 /// assert_eq!(format!("{:b}", x), "101010");
745 /// assert_eq!(format!("{:#b}", x), "0b101010");
747 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
750 /// Implementing `Binary` on a type:
755 /// struct Length(i32);
757 /// impl fmt::Binary for Length {
758 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
759 /// let val = self.0;
761 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
765 /// let l = Length(107);
767 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
770 /// format!("l as binary is: {:#032b}", l),
771 /// "l as binary is: 0b000000000000000000000001101011"
774 #[stable(feature = "rust1", since = "1.0.0")]
776 /// Formats the value using the given formatter.
777 #[stable(feature = "rust1", since = "1.0.0")]
778 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
783 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
786 /// For primitive signed integers (`i8` to `i128`, and `isize`),
787 /// negative values are formatted as the two’s complement representation.
789 /// The alternate flag, `#`, adds a `0x` in front of the output.
791 /// For more information on formatters, see [the module-level documentation][self].
795 /// Basic usage with `i32`:
798 /// let x = 42; // 42 is '2a' in hex
800 /// assert_eq!(format!("{:x}", x), "2a");
801 /// assert_eq!(format!("{:#x}", x), "0x2a");
803 /// assert_eq!(format!("{:x}", -16), "fffffff0");
806 /// Implementing `LowerHex` on a type:
811 /// struct Length(i32);
813 /// impl fmt::LowerHex for Length {
814 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
815 /// let val = self.0;
817 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
821 /// let l = Length(9);
823 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
825 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
827 #[stable(feature = "rust1", since = "1.0.0")]
829 /// Formats the value using the given formatter.
830 #[stable(feature = "rust1", since = "1.0.0")]
831 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
836 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
839 /// For primitive signed integers (`i8` to `i128`, and `isize`),
840 /// negative values are formatted as the two’s complement representation.
842 /// The alternate flag, `#`, adds a `0x` in front of the output.
844 /// For more information on formatters, see [the module-level documentation][self].
848 /// Basic usage with `i32`:
851 /// let x = 42; // 42 is '2A' in hex
853 /// assert_eq!(format!("{:X}", x), "2A");
854 /// assert_eq!(format!("{:#X}", x), "0x2A");
856 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
859 /// Implementing `UpperHex` on a type:
864 /// struct Length(i32);
866 /// impl fmt::UpperHex for Length {
867 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
868 /// let val = self.0;
870 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
874 /// let l = Length(i32::MAX);
876 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
878 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
880 #[stable(feature = "rust1", since = "1.0.0")]
882 /// Formats the value using the given formatter.
883 #[stable(feature = "rust1", since = "1.0.0")]
884 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
889 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
892 /// For more information on formatters, see [the module-level documentation][self].
896 /// Basic usage with `&i32`:
901 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
904 /// Implementing `Pointer` on a type:
909 /// struct Length(i32);
911 /// impl fmt::Pointer for Length {
912 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
913 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
915 /// let ptr = self as *const Self;
916 /// fmt::Pointer::fmt(&ptr, f)
920 /// let l = Length(42);
922 /// println!("l is in memory here: {:p}", l);
924 /// let l_ptr = format!("{:018p}", l);
925 /// assert_eq!(l_ptr.len(), 18);
926 /// assert_eq!(&l_ptr[..2], "0x");
928 #[stable(feature = "rust1", since = "1.0.0")]
930 /// Formats the value using the given formatter.
931 #[stable(feature = "rust1", since = "1.0.0")]
932 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
937 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
939 /// For more information on formatters, see [the module-level documentation][self].
943 /// Basic usage with `f64`:
946 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
948 /// assert_eq!(format!("{:e}", x), "4.2e1");
951 /// Implementing `LowerExp` on a type:
956 /// struct Length(i32);
958 /// impl fmt::LowerExp for Length {
959 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960 /// let val = f64::from(self.0);
961 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
965 /// let l = Length(100);
968 /// format!("l in scientific notation is: {:e}", l),
969 /// "l in scientific notation is: 1e2"
973 /// format!("l in scientific notation is: {:05e}", l),
974 /// "l in scientific notation is: 001e2"
977 #[stable(feature = "rust1", since = "1.0.0")]
979 /// Formats the value using the given formatter.
980 #[stable(feature = "rust1", since = "1.0.0")]
981 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
986 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
988 /// For more information on formatters, see [the module-level documentation][self].
992 /// Basic usage with `f64`:
995 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
997 /// assert_eq!(format!("{:E}", x), "4.2E1");
1000 /// Implementing `UpperExp` on a type:
1005 /// struct Length(i32);
1007 /// impl fmt::UpperExp for Length {
1008 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1009 /// let val = f64::from(self.0);
1010 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1014 /// let l = Length(100);
1017 /// format!("l in scientific notation is: {:E}", l),
1018 /// "l in scientific notation is: 1E2"
1022 /// format!("l in scientific notation is: {:05E}", l),
1023 /// "l in scientific notation is: 001E2"
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 pub trait UpperExp {
1028 /// Formats the value using the given formatter.
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1033 /// The `write` function takes an output stream, and an `Arguments` struct
1034 /// that can be precompiled with the `format_args!` macro.
1036 /// The arguments will be formatted according to the specified format string
1037 /// into the output stream provided.
1046 /// let mut output = String::new();
1047 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1048 /// .expect("Error occurred while trying to write in String");
1049 /// assert_eq!(output, "Hello world!");
1052 /// Please note that using [`write!`] might be preferable. Example:
1055 /// use std::fmt::Write;
1057 /// let mut output = String::new();
1058 /// write!(&mut output, "Hello {}!", "world")
1059 /// .expect("Error occurred while trying to write in String");
1060 /// assert_eq!(output, "Hello world!");
1063 /// [`write!`]: ../../std/macro.write.html
1064 #[stable(feature = "rust1", since = "1.0.0")]
1065 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1066 let mut formatter = Formatter {
1071 align: rt::v1::Alignment::Unknown,
1079 // We can use default formatting parameters for all arguments.
1080 for (arg, piece) in args.args.iter().zip(args.pieces.iter()) {
1081 formatter.buf.write_str(*piece)?;
1082 (arg.formatter)(arg.value, &mut formatter)?;
1087 // Every spec has a corresponding argument that is preceded by
1089 for (arg, piece) in fmt.iter().zip(args.pieces.iter()) {
1090 formatter.buf.write_str(*piece)?;
1091 run(&mut formatter, arg, &args.args)?;
1097 // There can be only one trailing string piece left.
1098 if let Some(piece) = args.pieces.get(idx) {
1099 formatter.buf.write_str(*piece)?;
1105 fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1106 fmt.fill = arg.format.fill;
1107 fmt.align = arg.format.align;
1108 fmt.flags = arg.format.flags;
1109 fmt.width = getcount(args, &arg.format.width);
1110 fmt.precision = getcount(args, &arg.format.precision);
1112 // Extract the correct argument
1113 let value = args[arg.position];
1115 // Then actually do some printing
1116 (value.formatter)(value.value, fmt)
1119 fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1121 rt::v1::Count::Is(n) => Some(n),
1122 rt::v1::Count::Implied => None,
1123 rt::v1::Count::Param(i) => args[i].as_usize(),
1127 /// Padding after the end of something. Returned by `Formatter::padding`.
1128 #[must_use = "don't forget to write the post padding"]
1129 struct PostPadding {
1135 fn new(fill: char, padding: usize) -> PostPadding {
1136 PostPadding { fill, padding }
1139 /// Write this post padding.
1140 fn write(self, buf: &mut dyn Write) -> Result {
1141 for _ in 0..self.padding {
1142 buf.write_char(self.fill)?;
1148 impl<'a> Formatter<'a> {
1149 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1152 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1155 // We want to change this
1156 buf: wrap(self.buf),
1158 // And preserve these
1163 precision: self.precision,
1167 // Helper methods used for padding and processing formatting arguments that
1168 // all formatting traits can use.
1170 /// Performs the correct padding for an integer which has already been
1171 /// emitted into a str. The str should *not* contain the sign for the
1172 /// integer, that will be added by this method.
1176 /// * is_nonnegative - whether the original integer was either positive or zero.
1177 /// * prefix - if the '#' character (Alternate) is provided, this
1178 /// is the prefix to put in front of the number.
1179 /// * buf - the byte array that the number has been formatted into
1181 /// This function will correctly account for the flags provided as well as
1182 /// the minimum width. It will not take precision into account.
1189 /// struct Foo { nb: i32 };
1192 /// fn new(nb: i32) -> Foo {
1199 /// impl fmt::Display for Foo {
1200 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1201 /// // We need to remove "-" from the number output.
1202 /// let tmp = self.nb.abs().to_string();
1204 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1208 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1209 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1210 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1211 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1215 let mut width = buf.len();
1217 let mut sign = None;
1218 if !is_nonnegative {
1221 } else if self.sign_plus() {
1226 let prefix = if self.alternate() {
1227 width += prefix.chars().count();
1233 // Writes the sign if it exists, and then the prefix if it was requested
1235 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1236 if let Some(c) = sign {
1237 f.buf.write_char(c)?;
1239 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1242 // The `width` field is more of a `min-width` parameter at this point.
1244 // If there's no minimum length requirements then we can just
1247 write_prefix(self, sign, prefix)?;
1248 self.buf.write_str(buf)
1250 // Check if we're over the minimum width, if so then we can also
1251 // just write the bytes.
1252 Some(min) if width >= min => {
1253 write_prefix(self, sign, prefix)?;
1254 self.buf.write_str(buf)
1256 // The sign and prefix goes before the padding if the fill character
1258 Some(min) if self.sign_aware_zero_pad() => {
1259 let old_fill = crate::mem::replace(&mut self.fill, '0');
1260 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1261 write_prefix(self, sign, prefix)?;
1262 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1263 self.buf.write_str(buf)?;
1264 post_padding.write(self.buf)?;
1265 self.fill = old_fill;
1266 self.align = old_align;
1269 // Otherwise, the sign and prefix goes after the padding
1271 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1272 write_prefix(self, sign, prefix)?;
1273 self.buf.write_str(buf)?;
1274 post_padding.write(self.buf)
1279 /// This function takes a string slice and emits it to the internal buffer
1280 /// after applying the relevant formatting flags specified. The flags
1281 /// recognized for generic strings are:
1283 /// * width - the minimum width of what to emit
1284 /// * fill/align - what to emit and where to emit it if the string
1285 /// provided needs to be padded
1286 /// * precision - the maximum length to emit, the string is truncated if it
1287 /// is longer than this length
1289 /// Notably this function ignores the `flag` parameters.
1298 /// impl fmt::Display for Foo {
1299 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1300 /// formatter.pad("Foo")
1304 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1305 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 pub fn pad(&mut self, s: &str) -> Result {
1309 // Make sure there's a fast path up front
1310 if self.width.is_none() && self.precision.is_none() {
1311 return self.buf.write_str(s);
1313 // The `precision` field can be interpreted as a `max-width` for the
1314 // string being formatted.
1315 let s = if let Some(max) = self.precision {
1316 // If our string is longer that the precision, then we must have
1317 // truncation. However other flags like `fill`, `width` and `align`
1318 // must act as always.
1319 if let Some((i, _)) = s.char_indices().nth(max) {
1320 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1321 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1322 // `unsafe` and otherwise don't emit any panic-related code
1324 s.get(..i).unwrap_or(&s)
1331 // The `width` field is more of a `min-width` parameter at this point.
1333 // If we're under the maximum length, and there's no minimum length
1334 // requirements, then we can just emit the string
1335 None => self.buf.write_str(s),
1336 // If we're under the maximum width, check if we're over the minimum
1337 // width, if so it's as easy as just emitting the string.
1338 Some(width) if s.chars().count() >= width => self.buf.write_str(s),
1339 // If we're under both the maximum and the minimum width, then fill
1340 // up the minimum width with the specified string + some alignment.
1342 let align = rt::v1::Alignment::Left;
1343 let post_padding = self.padding(width - s.chars().count(), align)?;
1344 self.buf.write_str(s)?;
1345 post_padding.write(self.buf)
1350 /// Write the pre-padding and return the unwritten post-padding. Callers are
1351 /// responsible for ensuring post-padding is written after the thing that is
1356 default: rt::v1::Alignment,
1357 ) -> result::Result<PostPadding, Error> {
1358 let align = match self.align {
1359 rt::v1::Alignment::Unknown => default,
1363 let (pre_pad, post_pad) = match align {
1364 rt::v1::Alignment::Left => (0, padding),
1365 rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1366 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1369 for _ in 0..pre_pad {
1370 self.buf.write_char(self.fill)?;
1373 Ok(PostPadding::new(self.fill, post_pad))
1376 /// Takes the formatted parts and applies the padding.
1377 /// Assumes that the caller already has rendered the parts with required precision,
1378 /// so that `self.precision` can be ignored.
1379 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted<'_>) -> Result {
1380 if let Some(mut width) = self.width {
1381 // for the sign-aware zero padding, we render the sign first and
1382 // behave as if we had no sign from the beginning.
1383 let mut formatted = formatted.clone();
1384 let old_fill = self.fill;
1385 let old_align = self.align;
1386 let mut align = old_align;
1387 if self.sign_aware_zero_pad() {
1388 // a sign always goes first
1389 let sign = formatted.sign;
1390 self.buf.write_str(sign)?;
1392 // remove the sign from the formatted parts
1393 formatted.sign = "";
1394 width = width.saturating_sub(sign.len());
1395 align = rt::v1::Alignment::Right;
1397 self.align = rt::v1::Alignment::Right;
1400 // remaining parts go through the ordinary padding process.
1401 let len = formatted.len();
1402 let ret = if width <= len {
1404 self.write_formatted_parts(&formatted)
1406 let post_padding = self.padding(width - len, align)?;
1407 self.write_formatted_parts(&formatted)?;
1408 post_padding.write(self.buf)
1410 self.fill = old_fill;
1411 self.align = old_align;
1414 // this is the common case and we take a shortcut
1415 self.write_formatted_parts(formatted)
1419 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted<'_>) -> Result {
1420 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1421 // SAFETY: This is used for `flt2dec::Part::Num` and `flt2dec::Part::Copy`.
1422 // It's safe to use for `flt2dec::Part::Num` since every char `c` is between
1423 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1424 // It's also probably safe in practice to use for `flt2dec::Part::Copy(buf)`
1425 // since `buf` should be plain ASCII, but it's possible for someone to pass
1426 // in a bad value for `buf` into `flt2dec::to_shortest_str` since it is a
1428 // FIXME: Determine whether this could result in UB.
1429 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1432 if !formatted.sign.is_empty() {
1433 self.buf.write_str(formatted.sign)?;
1435 for part in formatted.parts {
1437 flt2dec::Part::Zero(mut nzeroes) => {
1438 const ZEROES: &str = // 64 zeroes
1439 "0000000000000000000000000000000000000000000000000000000000000000";
1440 while nzeroes > ZEROES.len() {
1441 self.buf.write_str(ZEROES)?;
1442 nzeroes -= ZEROES.len();
1445 self.buf.write_str(&ZEROES[..nzeroes])?;
1448 flt2dec::Part::Num(mut v) => {
1450 let len = part.len();
1451 for c in s[..len].iter_mut().rev() {
1452 *c = b'0' + (v % 10) as u8;
1455 write_bytes(self.buf, &s[..len])?;
1457 flt2dec::Part::Copy(buf) => {
1458 write_bytes(self.buf, buf)?;
1465 /// Writes some data to the underlying buffer contained within this
1475 /// impl fmt::Display for Foo {
1476 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1477 /// formatter.write_str("Foo")
1478 /// // This is equivalent to:
1479 /// // write!(formatter, "Foo")
1483 /// assert_eq!(&format!("{}", Foo), "Foo");
1484 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1486 #[stable(feature = "rust1", since = "1.0.0")]
1487 pub fn write_str(&mut self, data: &str) -> Result {
1488 self.buf.write_str(data)
1491 /// Writes some formatted information into this instance.
1498 /// struct Foo(i32);
1500 /// impl fmt::Display for Foo {
1501 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1502 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1506 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1507 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1511 write(self.buf, fmt)
1514 /// Flags for formatting
1515 #[stable(feature = "rust1", since = "1.0.0")]
1518 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1519 or `sign_aware_zero_pad` methods instead"
1521 pub fn flags(&self) -> u32 {
1525 /// Character used as 'fill' whenever there is alignment.
1534 /// impl fmt::Display for Foo {
1535 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1536 /// let c = formatter.fill();
1537 /// if let Some(width) = formatter.width() {
1538 /// for _ in 0..width {
1539 /// write!(formatter, "{}", c)?;
1543 /// write!(formatter, "{}", c)
1548 /// // We set alignment to the left with ">".
1549 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1550 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1552 #[stable(feature = "fmt_flags", since = "1.5.0")]
1553 pub fn fill(&self) -> char {
1557 /// Flag indicating what form of alignment was requested.
1562 /// extern crate core;
1564 /// use std::fmt::{self, Alignment};
1568 /// impl fmt::Display for Foo {
1569 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1570 /// let s = if let Some(s) = formatter.align() {
1572 /// Alignment::Left => "left",
1573 /// Alignment::Right => "right",
1574 /// Alignment::Center => "center",
1579 /// write!(formatter, "{}", s)
1583 /// assert_eq!(&format!("{:<}", Foo), "left");
1584 /// assert_eq!(&format!("{:>}", Foo), "right");
1585 /// assert_eq!(&format!("{:^}", Foo), "center");
1586 /// assert_eq!(&format!("{}", Foo), "into the void");
1588 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1589 pub fn align(&self) -> Option<Alignment> {
1591 rt::v1::Alignment::Left => Some(Alignment::Left),
1592 rt::v1::Alignment::Right => Some(Alignment::Right),
1593 rt::v1::Alignment::Center => Some(Alignment::Center),
1594 rt::v1::Alignment::Unknown => None,
1598 /// Optionally specified integer width that the output should be.
1605 /// struct Foo(i32);
1607 /// impl fmt::Display for Foo {
1608 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1609 /// if let Some(width) = formatter.width() {
1610 /// // If we received a width, we use it
1611 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1613 /// // Otherwise we do nothing special
1614 /// write!(formatter, "Foo({})", self.0)
1619 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1620 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1622 #[stable(feature = "fmt_flags", since = "1.5.0")]
1623 pub fn width(&self) -> Option<usize> {
1627 /// Optionally specified precision for numeric types. Alternatively, the
1628 /// maximum width for string types.
1635 /// struct Foo(f32);
1637 /// impl fmt::Display for Foo {
1638 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1639 /// if let Some(precision) = formatter.precision() {
1640 /// // If we received a precision, we use it.
1641 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1643 /// // Otherwise we default to 2.
1644 /// write!(formatter, "Foo({:.2})", self.0)
1649 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1650 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1652 #[stable(feature = "fmt_flags", since = "1.5.0")]
1653 pub fn precision(&self) -> Option<usize> {
1657 /// Determines if the `+` flag was specified.
1664 /// struct Foo(i32);
1666 /// impl fmt::Display for Foo {
1667 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1668 /// if formatter.sign_plus() {
1669 /// write!(formatter,
1671 /// if self.0 < 0 { '-' } else { '+' },
1674 /// write!(formatter, "Foo({})", self.0)
1679 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1680 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1682 #[stable(feature = "fmt_flags", since = "1.5.0")]
1683 pub fn sign_plus(&self) -> bool {
1684 self.flags & (1 << FlagV1::SignPlus as u32) != 0
1687 /// Determines if the `-` flag was specified.
1694 /// struct Foo(i32);
1696 /// impl fmt::Display for Foo {
1697 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1698 /// if formatter.sign_minus() {
1699 /// // You want a minus sign? Have one!
1700 /// write!(formatter, "-Foo({})", self.0)
1702 /// write!(formatter, "Foo({})", self.0)
1707 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1708 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1710 #[stable(feature = "fmt_flags", since = "1.5.0")]
1711 pub fn sign_minus(&self) -> bool {
1712 self.flags & (1 << FlagV1::SignMinus as u32) != 0
1715 /// Determines if the `#` flag was specified.
1722 /// struct Foo(i32);
1724 /// impl fmt::Display for Foo {
1725 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1726 /// if formatter.alternate() {
1727 /// write!(formatter, "Foo({})", self.0)
1729 /// write!(formatter, "{}", self.0)
1734 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1735 /// assert_eq!(&format!("{}", Foo(23)), "23");
1737 #[stable(feature = "fmt_flags", since = "1.5.0")]
1738 pub fn alternate(&self) -> bool {
1739 self.flags & (1 << FlagV1::Alternate as u32) != 0
1742 /// Determines if the `0` flag was specified.
1749 /// struct Foo(i32);
1751 /// impl fmt::Display for Foo {
1752 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1753 /// assert!(formatter.sign_aware_zero_pad());
1754 /// assert_eq!(formatter.width(), Some(4));
1755 /// // We ignore the formatter's options.
1756 /// write!(formatter, "{}", self.0)
1760 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1762 #[stable(feature = "fmt_flags", since = "1.5.0")]
1763 pub fn sign_aware_zero_pad(&self) -> bool {
1764 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1767 // FIXME: Decide what public API we want for these two flags.
1768 // https://github.com/rust-lang/rust/issues/48584
1769 fn debug_lower_hex(&self) -> bool {
1770 self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1773 fn debug_upper_hex(&self) -> bool {
1774 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1777 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1778 /// [`fmt::Debug`] implementations for structs.
1780 /// [`fmt::Debug`]: self::Debug
1786 /// use std::net::Ipv4Addr;
1794 /// impl fmt::Debug for Foo {
1795 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1796 /// fmt.debug_struct("Foo")
1797 /// .field("bar", &self.bar)
1798 /// .field("baz", &self.baz)
1799 /// .field("addr", &format_args!("{}", self.addr))
1805 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1806 /// format!("{:?}", Foo {
1808 /// baz: "Hello World".to_string(),
1809 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1813 #[stable(feature = "debug_builders", since = "1.2.0")]
1814 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1815 builders::debug_struct_new(self, name)
1818 /// Creates a `DebugTuple` builder designed to assist with creation of
1819 /// `fmt::Debug` implementations for tuple structs.
1825 /// use std::marker::PhantomData;
1827 /// struct Foo<T>(i32, String, PhantomData<T>);
1829 /// impl<T> fmt::Debug for Foo<T> {
1830 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1831 /// fmt.debug_tuple("Foo")
1834 /// .field(&format_args!("_"))
1840 /// "Foo(10, \"Hello\", _)",
1841 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1844 #[stable(feature = "debug_builders", since = "1.2.0")]
1845 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1846 builders::debug_tuple_new(self, name)
1849 /// Creates a `DebugList` builder designed to assist with creation of
1850 /// `fmt::Debug` implementations for list-like structures.
1857 /// struct Foo(Vec<i32>);
1859 /// impl fmt::Debug for Foo {
1860 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1861 /// fmt.debug_list().entries(self.0.iter()).finish()
1865 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
1867 #[stable(feature = "debug_builders", since = "1.2.0")]
1868 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1869 builders::debug_list_new(self)
1872 /// Creates a `DebugSet` builder designed to assist with creation of
1873 /// `fmt::Debug` implementations for set-like structures.
1880 /// struct Foo(Vec<i32>);
1882 /// impl fmt::Debug for Foo {
1883 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1884 /// fmt.debug_set().entries(self.0.iter()).finish()
1888 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
1891 /// [`format_args!`]: ../../std/macro.format_args.html
1893 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1894 /// to build a list of match arms:
1899 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1900 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1902 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1904 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1906 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1907 /// L::fmt(&(self.0).0, fmt)?;
1908 /// fmt.write_str(" => ")?;
1909 /// R::fmt(&(self.0).1, fmt)
1913 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1915 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1917 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1919 /// .entries(self.0.iter().map(Arm))
1920 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1925 #[stable(feature = "debug_builders", since = "1.2.0")]
1926 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1927 builders::debug_set_new(self)
1930 /// Creates a `DebugMap` builder designed to assist with creation of
1931 /// `fmt::Debug` implementations for map-like structures.
1938 /// struct Foo(Vec<(String, i32)>);
1940 /// impl fmt::Debug for Foo {
1941 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1942 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1947 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1948 /// r#"{"A": 10, "B": 11}"#
1951 #[stable(feature = "debug_builders", since = "1.2.0")]
1952 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1953 builders::debug_map_new(self)
1957 #[stable(since = "1.2.0", feature = "formatter_write")]
1958 impl Write for Formatter<'_> {
1959 fn write_str(&mut self, s: &str) -> Result {
1960 self.buf.write_str(s)
1963 fn write_char(&mut self, c: char) -> Result {
1964 self.buf.write_char(c)
1967 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
1968 write(self.buf, args)
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 impl Display for Error {
1974 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1975 Display::fmt("an error occurred when formatting an argument", f)
1979 // Implementations of the core formatting traits
1981 macro_rules! fmt_refs {
1982 ($($tr:ident),*) => {
1984 #[stable(feature = "rust1", since = "1.0.0")]
1985 impl<T: ?Sized + $tr> $tr for &T {
1986 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
1988 #[stable(feature = "rust1", since = "1.0.0")]
1989 impl<T: ?Sized + $tr> $tr for &mut T {
1990 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
1996 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1998 #[unstable(feature = "never_type", issue = "35121")]
2000 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2005 #[unstable(feature = "never_type", issue = "35121")]
2006 impl Display for ! {
2007 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 impl Debug for bool {
2015 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2016 Display::fmt(self, f)
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 impl Display for bool {
2022 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2023 Display::fmt(if *self { "true" } else { "false" }, f)
2027 #[stable(feature = "rust1", since = "1.0.0")]
2028 impl Debug for str {
2029 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2032 for (i, c) in self.char_indices() {
2033 let esc = c.escape_debug();
2034 // If char needs escaping, flush backlog so far and write, else skip
2036 f.write_str(&self[from..i])?;
2040 from = i + c.len_utf8();
2043 f.write_str(&self[from..])?;
2048 #[stable(feature = "rust1", since = "1.0.0")]
2049 impl Display for str {
2050 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2055 #[stable(feature = "rust1", since = "1.0.0")]
2056 impl Debug for char {
2057 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2058 f.write_char('\'')?;
2059 for c in self.escape_debug() {
2066 #[stable(feature = "rust1", since = "1.0.0")]
2067 impl Display for char {
2068 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2069 if f.width.is_none() && f.precision.is_none() {
2072 f.pad(self.encode_utf8(&mut [0; 4]))
2077 #[stable(feature = "rust1", since = "1.0.0")]
2078 impl<T: ?Sized> Pointer for *const T {
2079 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2080 let old_width = f.width;
2081 let old_flags = f.flags;
2083 // The alternate flag is already treated by LowerHex as being special-
2084 // it denotes whether to prefix with 0x. We use it to work out whether
2085 // or not to zero extend, and then unconditionally set it to get the
2088 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2090 if f.width.is_none() {
2091 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2094 f.flags |= 1 << (FlagV1::Alternate as u32);
2096 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2098 f.width = old_width;
2099 f.flags = old_flags;
2105 #[stable(feature = "rust1", since = "1.0.0")]
2106 impl<T: ?Sized> Pointer for *mut T {
2107 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2108 Pointer::fmt(&(*self as *const T), f)
2112 #[stable(feature = "rust1", since = "1.0.0")]
2113 impl<T: ?Sized> Pointer for &T {
2114 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2115 Pointer::fmt(&(*self as *const T), f)
2119 #[stable(feature = "rust1", since = "1.0.0")]
2120 impl<T: ?Sized> Pointer for &mut T {
2121 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2122 Pointer::fmt(&(&**self as *const T), f)
2126 // Implementation of Display/Debug for various core types
2128 #[stable(feature = "rust1", since = "1.0.0")]
2129 impl<T: ?Sized> Debug for *const T {
2130 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2131 Pointer::fmt(self, f)
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 impl<T: ?Sized> Debug for *mut T {
2136 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2137 Pointer::fmt(self, f)
2142 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2145 macro_rules! tuple {
2147 ( $($name:ident,)+ ) => (
2148 #[stable(feature = "rust1", since = "1.0.0")]
2149 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2150 #[allow(non_snake_case, unused_assignments)]
2151 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2152 let mut builder = f.debug_tuple("");
2153 let ($(ref $name,)+) = *self;
2155 builder.field(&$name);
2161 peel! { $($name,)+ }
2165 macro_rules! last_type {
2166 ($a:ident,) => { $a };
2167 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2170 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2172 #[stable(feature = "rust1", since = "1.0.0")]
2173 impl<T: Debug> Debug for [T] {
2174 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2175 f.debug_list().entries(self.iter()).finish()
2179 #[stable(feature = "rust1", since = "1.0.0")]
2182 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2186 #[stable(feature = "rust1", since = "1.0.0")]
2187 impl<T: ?Sized> Debug for PhantomData<T> {
2188 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2189 f.pad("PhantomData")
2193 #[stable(feature = "rust1", since = "1.0.0")]
2194 impl<T: Copy + Debug> Debug for Cell<T> {
2195 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2196 f.debug_struct("Cell").field("value", &self.get()).finish()
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2202 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2203 match self.try_borrow() {
2204 Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2206 // The RefCell is mutably borrowed so we can't look at its value
2207 // here. Show a placeholder instead.
2208 struct BorrowedPlaceholder;
2210 impl Debug for BorrowedPlaceholder {
2211 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2212 f.write_str("<borrowed>")
2216 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2222 #[stable(feature = "rust1", since = "1.0.0")]
2223 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2224 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2225 Debug::fmt(&**self, f)
2229 #[stable(feature = "rust1", since = "1.0.0")]
2230 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2231 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2232 Debug::fmt(&*(self.deref()), f)
2236 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2237 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2238 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2243 // If you expected tests to be here, look instead at the ui/ifmt.rs test,
2244 // it's a lot easier than creating all of the rt::Piece structures here.