1 //! Utilities for formatting and printing strings.
3 #![stable(feature = "rust1", since = "1.0.0")]
5 use crate::cell::{Cell, Ref, RefCell, RefMut, SyncUnsafeCell, UnsafeCell};
6 use crate::char::EscapeDebugExtArgs;
8 use crate::marker::PhantomData;
10 use crate::num::fmt as numfmt;
11 use crate::ops::Deref;
16 #[cfg(not(no_fp_fmt_parse))]
18 #[cfg(no_fp_fmt_parse)]
22 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
23 #[cfg_attr(not(test), rustc_diagnostic_item = "Alignment")]
24 /// Possible alignments returned by `Formatter::align`
25 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
27 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
28 /// Indication that contents should be left-aligned.
30 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
31 /// Indication that contents should be right-aligned.
33 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
34 /// Indication that contents should be center-aligned.
38 #[stable(feature = "debug_builders", since = "1.2.0")]
39 pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
41 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
47 /// The type returned by formatter methods.
61 /// impl fmt::Display for Triangle {
62 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
67 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
69 /// assert_eq!(format!("{pythagorean_triple}"), "(3, 4, 5)");
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub type Result = result::Result<(), Error>;
74 /// The error type which is returned from formatting a message into a stream.
76 /// This type does not support transmission of an error other than that an error
77 /// occurred. Any extra information must be arranged to be transmitted through
80 /// An important thing to remember is that the type `fmt::Error` should not be
81 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
84 /// [`std::io::Error`]: ../../std/io/struct.Error.html
85 /// [`std::error::Error`]: ../../std/error/trait.Error.html
90 /// use std::fmt::{self, write};
92 /// let mut output = String::new();
93 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
94 /// panic!("An error occurred");
97 #[stable(feature = "rust1", since = "1.0.0")]
98 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
101 /// A trait for writing or formatting into Unicode-accepting buffers or streams.
103 /// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
104 /// want to accept Unicode and you don't need flushing, you should implement this trait;
105 /// otherwise you should implement [`std::io::Write`].
107 /// [`std::io::Write`]: ../../std/io/trait.Write.html
108 /// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
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 /// The purpose of std::fmt::Error is to abort the formatting operation when the underlying
123 /// destination encounters some error preventing it from accepting more text; it should
124 /// generally be propagated rather than handled, at least when implementing formatting traits.
129 /// use std::fmt::{Error, Write};
131 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
135 /// let mut buf = String::new();
136 /// writer(&mut buf, "hola").unwrap();
137 /// assert_eq!(&buf, "hola");
139 #[stable(feature = "rust1", since = "1.0.0")]
140 fn write_str(&mut self, s: &str) -> Result;
142 /// Writes a [`char`] into this writer, returning whether the write succeeded.
144 /// A single [`char`] may be encoded as more than one byte.
145 /// This method can only succeed if the entire byte sequence was successfully
146 /// written, and this method will not return until all data has been
147 /// written or an error occurs.
151 /// This function will return an instance of [`Error`] on error.
156 /// use std::fmt::{Error, Write};
158 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
162 /// let mut buf = String::new();
163 /// writer(&mut buf, 'a').unwrap();
164 /// writer(&mut buf, 'b').unwrap();
165 /// assert_eq!(&buf, "ab");
167 #[stable(feature = "fmt_write_char", since = "1.1.0")]
168 fn write_char(&mut self, c: char) -> Result {
169 self.write_str(c.encode_utf8(&mut [0; 4]))
172 /// Glue for usage of the [`write!`] macro with implementors of this trait.
174 /// This method should generally not be invoked manually, but rather through
175 /// the [`write!`] macro itself.
179 /// This function will return an instance of [`Error`] on error. Please see
180 /// [write_str](Write::write_str) for details.
185 /// use std::fmt::{Error, Write};
187 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
188 /// f.write_fmt(format_args!("{s}"))
191 /// let mut buf = String::new();
192 /// writer(&mut buf, "world").unwrap();
193 /// assert_eq!(&buf, "world");
195 #[stable(feature = "rust1", since = "1.0.0")]
196 fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
197 write(&mut self, args)
201 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
202 impl<W: Write + ?Sized> Write for &mut W {
203 fn write_str(&mut self, s: &str) -> Result {
204 (**self).write_str(s)
207 fn write_char(&mut self, c: char) -> Result {
208 (**self).write_char(c)
211 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
212 (**self).write_fmt(args)
216 /// Configuration for formatting.
218 /// A `Formatter` represents various options related to formatting. Users do not
219 /// construct `Formatter`s directly; a mutable reference to one is passed to
220 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
222 /// To interact with a `Formatter`, you'll call various methods to change the
223 /// various options related to formatting. For examples, please see the
224 /// documentation of the methods defined on `Formatter` below.
225 #[allow(missing_debug_implementations)]
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub struct Formatter<'a> {
230 align: rt::v1::Alignment,
231 width: Option<usize>,
232 precision: Option<usize>,
234 buf: &'a mut (dyn Write + 'a),
237 impl<'a> Formatter<'a> {
238 /// Creates a new formatter with default settings.
240 /// This can be used as a micro-optimization in cases where a full `Arguments`
241 /// structure (as created by `format_args!`) is not necessary; `Arguments`
242 /// is a little more expensive to use in simple formatting scenarios.
244 /// Currently not intended for use outside of the standard library.
245 #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
247 pub fn new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
251 align: rt::v1::Alignment::Unknown,
259 // NB. Argument is essentially an optimized partially applied formatting function,
260 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
266 /// This struct represents the generic "argument" which is taken by the Xprintf
267 /// family of functions. It contains a function to format the given value. At
268 /// compile time it is ensured that the function and the value have the correct
269 /// types, and then this struct is used to canonicalize arguments to one type.
270 #[derive(Copy, Clone)]
271 #[allow(missing_debug_implementations)]
272 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
274 pub struct ArgumentV1<'a> {
276 formatter: fn(&Opaque, &mut Formatter<'_>) -> Result,
279 /// This struct represents the unsafety of constructing an `Arguments`.
280 /// It exists, rather than an unsafe function, in order to simplify the expansion
281 /// of `format_args!(..)` and reduce the scope of the `unsafe` block.
282 #[allow(missing_debug_implementations)]
284 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
285 pub struct UnsafeArg {
290 /// See documentation where `UnsafeArg` is required to know when it is safe to
291 /// create and use `UnsafeArg`.
293 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
295 pub unsafe fn new() -> Self {
296 Self { _private: () }
300 // This guarantees a single stable value for the function pointer associated with
301 // indices/counts in the formatting infrastructure.
303 // Note that a function defined as such would not be correct as functions are
304 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
305 // address is not considered important to LLVM and as such the as_usize cast
306 // could have been miscompiled. In practice, we never call as_usize on non-usize
307 // containing data (as a matter of static generation of the formatting
308 // arguments), so this is merely an additional check.
310 // We primarily want to ensure that the function pointer at `USIZE_MARKER` has
311 // an address corresponding *only* to functions that also take `&usize` as their
312 // first argument. The read_volatile here ensures that we can safely ready out a
313 // usize from the passed reference and that this address does not point at a
314 // non-usize taking function.
315 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
316 static USIZE_MARKER: fn(&usize, &mut Formatter<'_>) -> Result = |ptr, _| {
317 // SAFETY: ptr is a reference
318 let _v: usize = unsafe { crate::ptr::read_volatile(ptr) };
322 macro_rules! arg_new {
323 ($f: ident, $t: ident) => {
325 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
327 pub fn $f<'b, T: $t>(x: &'b T) -> ArgumentV1<'_> {
328 Self::new(x, $t::fmt)
333 #[rustc_diagnostic_item = "ArgumentV1Methods"]
334 impl<'a> ArgumentV1<'a> {
336 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
338 pub fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
339 // SAFETY: `mem::transmute(x)` is safe because
340 // 1. `&'b T` keeps the lifetime it originated with `'b`
341 // (so as to not have an unbounded lifetime)
342 // 2. `&'b T` and `&'b Opaque` have the same memory layout
343 // (when `T` is `Sized`, as it is here)
344 // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
345 // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
346 // (as long as `T` is `Sized`)
347 unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) } }
350 arg_new!(new_display, Display);
351 arg_new!(new_debug, Debug);
352 arg_new!(new_octal, Octal);
353 arg_new!(new_lower_hex, LowerHex);
354 arg_new!(new_upper_hex, UpperHex);
355 arg_new!(new_pointer, Pointer);
356 arg_new!(new_binary, Binary);
357 arg_new!(new_lower_exp, LowerExp);
358 arg_new!(new_upper_exp, UpperExp);
361 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
362 pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
363 ArgumentV1::new(x, USIZE_MARKER)
366 fn as_usize(&self) -> Option<usize> {
367 // We are type punning a bit here: USIZE_MARKER only takes an &usize but
368 // formatter takes an &Opaque. Rust understandably doesn't think we should compare
369 // the function pointers if they don't have the same signature, so we cast to
370 // usizes to tell it that we just want to compare addresses.
371 if self.formatter as usize == USIZE_MARKER as usize {
372 // SAFETY: The `formatter` field is only set to USIZE_MARKER if
373 // the value is a usize, so this is safe
374 Some(unsafe { *(self.value as *const _ as *const usize) })
381 // flags available in the v1 format of format_args
382 #[derive(Copy, Clone)]
392 impl<'a> Arguments<'a> {
393 /// When using the format_args!() macro, this function is used to generate the
394 /// Arguments structure.
397 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
398 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
399 pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
400 if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
401 panic!("invalid args");
403 Arguments { pieces, fmt: None, args }
406 /// This function is used to specify nonstandard formatting parameters.
408 /// An `UnsafeArg` is required because the following invariants must be held
409 /// in order for this function to be safe:
410 /// 1. The `pieces` slice must be at least as long as `fmt`.
411 /// 2. Every [`rt::v1::Argument::position`] value within `fmt` must be a
412 /// valid index of `args`.
413 /// 3. Every [`rt::v1::Count::Param`] within `fmt` must contain a valid index of
417 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
418 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
419 pub const fn new_v1_formatted(
420 pieces: &'a [&'static str],
421 args: &'a [ArgumentV1<'a>],
422 fmt: &'a [rt::v1::Argument],
423 _unsafe_arg: UnsafeArg,
425 Arguments { pieces, fmt: Some(fmt), args }
428 /// Estimates the length of the formatted text.
430 /// This is intended to be used for setting initial `String` capacity
431 /// when using `format!`. Note: this is neither the lower nor upper bound.
434 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
435 pub fn estimated_capacity(&self) -> usize {
436 let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
438 if self.args.is_empty() {
440 } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
441 // If the format string starts with an argument,
442 // don't preallocate anything, unless length
443 // of pieces is significant.
446 // There are some arguments, so any additional push
447 // will reallocate the string. To avoid that,
448 // we're "pre-doubling" the capacity here.
449 pieces_length.checked_mul(2).unwrap_or(0)
454 /// This structure represents a safely precompiled version of a format string
455 /// and its arguments. This cannot be generated at runtime because it cannot
456 /// safely be done, so no constructors are given and the fields are private
457 /// to prevent modification.
459 /// The [`format_args!`] macro will safely create an instance of this structure.
460 /// The macro validates the format string at compile-time so usage of the
461 /// [`write()`] and [`format()`] functions can be safely performed.
463 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
464 /// and `Display` contexts as seen below. The example also shows that `Debug`
465 /// and `Display` format to the same thing: the interpolated format string
466 /// in `format_args!`.
469 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
470 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
471 /// assert_eq!("1 foo 2", display);
472 /// assert_eq!(display, debug);
475 /// [`format()`]: ../../std/fmt/fn.format.html
476 #[stable(feature = "rust1", since = "1.0.0")]
477 #[cfg_attr(not(test), rustc_diagnostic_item = "Arguments")]
478 #[derive(Copy, Clone)]
479 pub struct Arguments<'a> {
480 // Format string pieces to print.
481 pieces: &'a [&'static str],
483 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
484 fmt: Option<&'a [rt::v1::Argument]>,
486 // Dynamic arguments for interpolation, to be interleaved with string
487 // pieces. (Every argument is preceded by a string piece.)
488 args: &'a [ArgumentV1<'a>],
491 impl<'a> Arguments<'a> {
492 /// Get the formatted string, if it has no arguments to be formatted.
494 /// This can be used to avoid allocations in the most trivial case.
499 /// use std::fmt::Arguments;
501 /// fn write_str(_: &str) { /* ... */ }
503 /// fn write_fmt(args: &Arguments) {
504 /// if let Some(s) = args.as_str() {
507 /// write_str(&args.to_string());
513 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
514 /// assert_eq!(format_args!("").as_str(), Some(""));
515 /// assert_eq!(format_args!("{}", 1).as_str(), None);
517 #[stable(feature = "fmt_as_str", since = "1.52.0")]
518 #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")]
521 pub const fn as_str(&self) -> Option<&'static str> {
522 match (self.pieces, self.args) {
523 ([], []) => Some(""),
524 ([s], []) => Some(s),
530 #[stable(feature = "rust1", since = "1.0.0")]
531 impl Debug for Arguments<'_> {
532 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
533 Display::fmt(self, fmt)
537 #[stable(feature = "rust1", since = "1.0.0")]
538 impl Display for Arguments<'_> {
539 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
540 write(fmt.buf, *self)
546 /// `Debug` should format the output in a programmer-facing, debugging context.
548 /// Generally speaking, you should just `derive` a `Debug` implementation.
550 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
552 /// For more information on formatters, see [the module-level documentation][module].
554 /// [module]: ../../std/fmt/index.html
556 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
557 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
558 /// comma-separated list of each field's name and `Debug` value, then `}`. For
559 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
560 /// `Debug` values of the fields, then `)`.
564 /// Derived `Debug` formats are not stable, and so may change with future Rust
565 /// versions. Additionally, `Debug` implementations of types provided by the
566 /// standard library (`std`, `core`, `alloc`, etc.) are not stable, and
567 /// may also change with future Rust versions.
571 /// Deriving an implementation:
580 /// let origin = Point { x: 0, y: 0 };
582 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
585 /// Manually implementing:
595 /// impl fmt::Debug for Point {
596 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
597 /// f.debug_struct("Point")
598 /// .field("x", &self.x)
599 /// .field("y", &self.y)
604 /// let origin = Point { x: 0, y: 0 };
606 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
609 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
610 /// implementations, such as [`debug_struct`].
612 /// [`debug_struct`]: Formatter::debug_struct
614 /// Types that do not wish to use the standard suite of debug representations
615 /// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
616 /// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
617 /// manually writing an arbitrary representation to the `Formatter`.
626 /// impl fmt::Debug for Point {
627 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628 /// write!(f, "Point [{} {}]", self.x, self.y)
633 /// `Debug` implementations using either `derive` or the debug builder API
634 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
636 /// Pretty-printing with `#?`:
645 /// let origin = Point { x: 0, y: 0 };
647 /// assert_eq!(format!("The origin is: {origin:#?}"),
648 /// "The origin is: Point {
654 #[stable(feature = "rust1", since = "1.0.0")]
655 #[rustc_on_unimplemented(
658 label = "`{Self}` cannot be formatted using `{{:?}}`",
659 note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
661 message = "`{Self}` doesn't implement `{Debug}`",
662 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
664 #[doc(alias = "{:?}")]
665 #[rustc_diagnostic_item = "Debug"]
666 #[rustc_trivial_field_reads]
668 /// Formats the value using the given formatter.
675 /// struct Position {
680 /// impl fmt::Debug for Position {
681 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
682 /// f.debug_tuple("")
683 /// .field(&self.longitude)
684 /// .field(&self.latitude)
689 /// let position = Position { longitude: 1.987, latitude: 2.983 };
690 /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
692 /// assert_eq!(format!("{position:#?}"), "(
697 #[stable(feature = "rust1", since = "1.0.0")]
698 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
701 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
702 pub(crate) mod macros {
703 /// Derive macro generating an impl of the trait `Debug`.
704 #[rustc_builtin_macro]
705 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
706 #[allow_internal_unstable(core_intrinsics, fmt_helpers_for_derive)]
707 pub macro Debug($item:item) {
708 /* compiler built-in */
711 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
713 pub use macros::Debug;
715 /// Format trait for an empty format, `{}`.
717 /// Implementing this trait for a type will automatically implement the
718 /// [`ToString`][tostring] trait for the type, allowing the usage
719 /// of the [`.to_string()`][tostring_function] method. Prefer implementing
720 /// the `Display` trait for a type, rather than [`ToString`][tostring].
722 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
723 /// output, and so cannot be derived.
725 /// For more information on formatters, see [the module-level documentation][module].
727 /// [module]: ../../std/fmt/index.html
728 /// [tostring]: ../../std/string/trait.ToString.html
729 /// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
733 /// Implementing `Display` on a type:
743 /// impl fmt::Display for Point {
744 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
745 /// write!(f, "({}, {})", self.x, self.y)
749 /// let origin = Point { x: 0, y: 0 };
751 /// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
753 #[rustc_on_unimplemented(
755 any(_Self = "std::path::Path", _Self = "std::path::PathBuf"),
756 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
757 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
758 as they may contain non-Unicode data"
760 message = "`{Self}` doesn't implement `{Display}`",
761 label = "`{Self}` cannot be formatted with the default formatter",
762 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
765 #[rustc_diagnostic_item = "Display"]
766 #[stable(feature = "rust1", since = "1.0.0")]
768 /// Formats the value using the given formatter.
775 /// struct Position {
780 /// impl fmt::Display for Position {
781 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
782 /// write!(f, "({}, {})", self.longitude, self.latitude)
786 /// assert_eq!("(1.987, 2.983)",
787 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
789 #[stable(feature = "rust1", since = "1.0.0")]
790 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
795 /// The `Octal` trait should format its output as a number in base-8.
797 /// For primitive signed integers (`i8` to `i128`, and `isize`),
798 /// negative values are formatted as the two’s complement representation.
800 /// The alternate flag, `#`, adds a `0o` in front of the output.
802 /// For more information on formatters, see [the module-level documentation][module].
804 /// [module]: ../../std/fmt/index.html
808 /// Basic usage with `i32`:
811 /// let x = 42; // 42 is '52' in octal
813 /// assert_eq!(format!("{x:o}"), "52");
814 /// assert_eq!(format!("{x:#o}"), "0o52");
816 /// assert_eq!(format!("{:o}", -16), "37777777760");
819 /// Implementing `Octal` on a type:
824 /// struct Length(i32);
826 /// impl fmt::Octal for Length {
827 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
828 /// let val = self.0;
830 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
834 /// let l = Length(9);
836 /// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
838 /// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
840 #[stable(feature = "rust1", since = "1.0.0")]
842 /// Formats the value using the given formatter.
843 #[stable(feature = "rust1", since = "1.0.0")]
844 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
849 /// The `Binary` trait should format its output as a number in binary.
851 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
852 /// negative values are formatted as the two’s complement representation.
854 /// The alternate flag, `#`, adds a `0b` in front of the output.
856 /// For more information on formatters, see [the module-level documentation][module].
858 /// [module]: ../../std/fmt/index.html
862 /// Basic usage with [`i32`]:
865 /// let x = 42; // 42 is '101010' in binary
867 /// assert_eq!(format!("{x:b}"), "101010");
868 /// assert_eq!(format!("{x:#b}"), "0b101010");
870 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
873 /// Implementing `Binary` on a type:
878 /// struct Length(i32);
880 /// impl fmt::Binary for Length {
881 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882 /// let val = self.0;
884 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
888 /// let l = Length(107);
890 /// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
893 /// format!("l as binary is: {l:#032b}"),
894 /// "l as binary is: 0b000000000000000000000001101011"
897 #[stable(feature = "rust1", since = "1.0.0")]
899 /// Formats the value using the given formatter.
900 #[stable(feature = "rust1", since = "1.0.0")]
901 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
906 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
909 /// For primitive signed integers (`i8` to `i128`, and `isize`),
910 /// negative values are formatted as the two’s complement representation.
912 /// The alternate flag, `#`, adds a `0x` in front of the output.
914 /// For more information on formatters, see [the module-level documentation][module].
916 /// [module]: ../../std/fmt/index.html
920 /// Basic usage with `i32`:
923 /// let x = 42; // 42 is '2a' in hex
925 /// assert_eq!(format!("{x:x}"), "2a");
926 /// assert_eq!(format!("{x:#x}"), "0x2a");
928 /// assert_eq!(format!("{:x}", -16), "fffffff0");
931 /// Implementing `LowerHex` on a type:
936 /// struct Length(i32);
938 /// impl fmt::LowerHex for Length {
939 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
940 /// let val = self.0;
942 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
946 /// let l = Length(9);
948 /// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
950 /// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
952 #[stable(feature = "rust1", since = "1.0.0")]
954 /// Formats the value using the given formatter.
955 #[stable(feature = "rust1", since = "1.0.0")]
956 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
961 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
964 /// For primitive signed integers (`i8` to `i128`, and `isize`),
965 /// negative values are formatted as the two’s complement representation.
967 /// The alternate flag, `#`, adds a `0x` in front of the output.
969 /// For more information on formatters, see [the module-level documentation][module].
971 /// [module]: ../../std/fmt/index.html
975 /// Basic usage with `i32`:
978 /// let x = 42; // 42 is '2A' in hex
980 /// assert_eq!(format!("{x:X}"), "2A");
981 /// assert_eq!(format!("{x:#X}"), "0x2A");
983 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
986 /// Implementing `UpperHex` on a type:
991 /// struct Length(i32);
993 /// impl fmt::UpperHex for Length {
994 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
995 /// let val = self.0;
997 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
1001 /// let l = Length(i32::MAX);
1003 /// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
1005 /// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 pub trait UpperHex {
1009 /// Formats the value using the given formatter.
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1016 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
1019 /// For more information on formatters, see [the module-level documentation][module].
1021 /// [module]: ../../std/fmt/index.html
1025 /// Basic usage with `&i32`:
1030 /// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
1033 /// Implementing `Pointer` on a type:
1038 /// struct Length(i32);
1040 /// impl fmt::Pointer for Length {
1041 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1042 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1044 /// let ptr = self as *const Self;
1045 /// fmt::Pointer::fmt(&ptr, f)
1049 /// let l = Length(42);
1051 /// println!("l is in memory here: {l:p}");
1053 /// let l_ptr = format!("{l:018p}");
1054 /// assert_eq!(l_ptr.len(), 18);
1055 /// assert_eq!(&l_ptr[..2], "0x");
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 #[rustc_diagnostic_item = "Pointer"]
1060 /// Formats the value using the given formatter.
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1067 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1069 /// For more information on formatters, see [the module-level documentation][module].
1071 /// [module]: ../../std/fmt/index.html
1075 /// Basic usage with `f64`:
1078 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1080 /// assert_eq!(format!("{x:e}"), "4.2e1");
1083 /// Implementing `LowerExp` on a type:
1088 /// struct Length(i32);
1090 /// impl fmt::LowerExp for Length {
1091 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1092 /// let val = f64::from(self.0);
1093 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1097 /// let l = Length(100);
1100 /// format!("l in scientific notation is: {l:e}"),
1101 /// "l in scientific notation is: 1e2"
1105 /// format!("l in scientific notation is: {l:05e}"),
1106 /// "l in scientific notation is: 001e2"
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 pub trait LowerExp {
1111 /// Formats the value using the given formatter.
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1118 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1120 /// For more information on formatters, see [the module-level documentation][module].
1122 /// [module]: ../../std/fmt/index.html
1126 /// Basic usage with `f64`:
1129 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1131 /// assert_eq!(format!("{x:E}"), "4.2E1");
1134 /// Implementing `UpperExp` on a type:
1139 /// struct Length(i32);
1141 /// impl fmt::UpperExp for Length {
1142 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1143 /// let val = f64::from(self.0);
1144 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1148 /// let l = Length(100);
1151 /// format!("l in scientific notation is: {l:E}"),
1152 /// "l in scientific notation is: 1E2"
1156 /// format!("l in scientific notation is: {l:05E}"),
1157 /// "l in scientific notation is: 001E2"
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 pub trait UpperExp {
1162 /// Formats the value using the given formatter.
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1167 /// The `write` function takes an output stream, and an `Arguments` struct
1168 /// that can be precompiled with the `format_args!` macro.
1170 /// The arguments will be formatted according to the specified format string
1171 /// into the output stream provided.
1180 /// let mut output = String::new();
1181 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1182 /// .expect("Error occurred while trying to write in String");
1183 /// assert_eq!(output, "Hello world!");
1186 /// Please note that using [`write!`] might be preferable. Example:
1189 /// use std::fmt::Write;
1191 /// let mut output = String::new();
1192 /// write!(&mut output, "Hello {}!", "world")
1193 /// .expect("Error occurred while trying to write in String");
1194 /// assert_eq!(output, "Hello world!");
1197 /// [`write!`]: crate::write!
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1200 let mut formatter = Formatter::new(output);
1205 // We can use default formatting parameters for all arguments.
1206 for (i, arg) in args.args.iter().enumerate() {
1207 // SAFETY: args.args and args.pieces come from the same Arguments,
1208 // which guarantees the indexes are always within bounds.
1209 let piece = unsafe { args.pieces.get_unchecked(i) };
1210 if !piece.is_empty() {
1211 formatter.buf.write_str(*piece)?;
1213 (arg.formatter)(arg.value, &mut formatter)?;
1218 // Every spec has a corresponding argument that is preceded by
1220 for (i, arg) in fmt.iter().enumerate() {
1221 // SAFETY: fmt and args.pieces come from the same Arguments,
1222 // which guarantees the indexes are always within bounds.
1223 let piece = unsafe { args.pieces.get_unchecked(i) };
1224 if !piece.is_empty() {
1225 formatter.buf.write_str(*piece)?;
1227 // SAFETY: arg and args.args come from the same Arguments,
1228 // which guarantees the indexes are always within bounds.
1229 unsafe { run(&mut formatter, arg, args.args) }?;
1235 // There can be only one trailing string piece left.
1236 if let Some(piece) = args.pieces.get(idx) {
1237 formatter.buf.write_str(*piece)?;
1243 unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1244 fmt.fill = arg.format.fill;
1245 fmt.align = arg.format.align;
1246 fmt.flags = arg.format.flags;
1247 // SAFETY: arg and args come from the same Arguments,
1248 // which guarantees the indexes are always within bounds.
1250 fmt.width = getcount(args, &arg.format.width);
1251 fmt.precision = getcount(args, &arg.format.precision);
1254 // Extract the correct argument
1255 debug_assert!(arg.position < args.len());
1256 // SAFETY: arg and args come from the same Arguments,
1257 // which guarantees its index is always within bounds.
1258 let value = unsafe { args.get_unchecked(arg.position) };
1260 // Then actually do some printing
1261 (value.formatter)(value.value, fmt)
1264 unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1266 rt::v1::Count::Is(n) => Some(n),
1267 rt::v1::Count::Implied => None,
1268 rt::v1::Count::Param(i) => {
1269 debug_assert!(i < args.len());
1270 // SAFETY: cnt and args come from the same Arguments,
1271 // which guarantees this index is always within bounds.
1272 unsafe { args.get_unchecked(i).as_usize() }
1277 /// Padding after the end of something. Returned by `Formatter::padding`.
1278 #[must_use = "don't forget to write the post padding"]
1279 pub(crate) struct PostPadding {
1285 fn new(fill: char, padding: usize) -> PostPadding {
1286 PostPadding { fill, padding }
1289 /// Write this post padding.
1290 pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1291 for _ in 0..self.padding {
1292 f.buf.write_char(self.fill)?;
1298 impl<'a> Formatter<'a> {
1299 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1302 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1305 // We want to change this
1306 buf: wrap(self.buf),
1308 // And preserve these
1313 precision: self.precision,
1317 // Helper methods used for padding and processing formatting arguments that
1318 // all formatting traits can use.
1320 /// Performs the correct padding for an integer which has already been
1321 /// emitted into a str. The str should *not* contain the sign for the
1322 /// integer, that will be added by this method.
1326 /// * is_nonnegative - whether the original integer was either positive or zero.
1327 /// * prefix - if the '#' character (Alternate) is provided, this
1328 /// is the prefix to put in front of the number.
1329 /// * buf - the byte array that the number has been formatted into
1331 /// This function will correctly account for the flags provided as well as
1332 /// the minimum width. It will not take precision into account.
1339 /// struct Foo { nb: i32 }
1342 /// fn new(nb: i32) -> Foo {
1349 /// impl fmt::Display for Foo {
1350 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1351 /// // We need to remove "-" from the number output.
1352 /// let tmp = self.nb.abs().to_string();
1354 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1358 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1359 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1360 /// assert_eq!(&format!("{}", Foo::new(0)), "0");
1361 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1362 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1366 let mut width = buf.len();
1368 let mut sign = None;
1369 if !is_nonnegative {
1372 } else if self.sign_plus() {
1377 let prefix = if self.alternate() {
1378 width += prefix.chars().count();
1384 // Writes the sign if it exists, and then the prefix if it was requested
1386 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1387 if let Some(c) = sign {
1388 f.buf.write_char(c)?;
1390 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1393 // The `width` field is more of a `min-width` parameter at this point.
1395 // If there's no minimum length requirements then we can just
1398 write_prefix(self, sign, prefix)?;
1399 self.buf.write_str(buf)
1401 // Check if we're over the minimum width, if so then we can also
1402 // just write the bytes.
1403 Some(min) if width >= min => {
1404 write_prefix(self, sign, prefix)?;
1405 self.buf.write_str(buf)
1407 // The sign and prefix goes before the padding if the fill character
1409 Some(min) if self.sign_aware_zero_pad() => {
1410 let old_fill = crate::mem::replace(&mut self.fill, '0');
1411 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1412 write_prefix(self, sign, prefix)?;
1413 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1414 self.buf.write_str(buf)?;
1415 post_padding.write(self)?;
1416 self.fill = old_fill;
1417 self.align = old_align;
1420 // Otherwise, the sign and prefix goes after the padding
1422 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1423 write_prefix(self, sign, prefix)?;
1424 self.buf.write_str(buf)?;
1425 post_padding.write(self)
1430 /// This function takes a string slice and emits it to the internal buffer
1431 /// after applying the relevant formatting flags specified. The flags
1432 /// recognized for generic strings are:
1434 /// * width - the minimum width of what to emit
1435 /// * fill/align - what to emit and where to emit it if the string
1436 /// provided needs to be padded
1437 /// * precision - the maximum length to emit, the string is truncated if it
1438 /// is longer than this length
1440 /// Notably this function ignores the `flag` parameters.
1449 /// impl fmt::Display for Foo {
1450 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1451 /// formatter.pad("Foo")
1455 /// assert_eq!(&format!("{Foo:<4}"), "Foo ");
1456 /// assert_eq!(&format!("{Foo:0>4}"), "0Foo");
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 pub fn pad(&mut self, s: &str) -> Result {
1460 // Make sure there's a fast path up front
1461 if self.width.is_none() && self.precision.is_none() {
1462 return self.buf.write_str(s);
1464 // The `precision` field can be interpreted as a `max-width` for the
1465 // string being formatted.
1466 let s = if let Some(max) = self.precision {
1467 // If our string is longer that the precision, then we must have
1468 // truncation. However other flags like `fill`, `width` and `align`
1469 // must act as always.
1470 if let Some((i, _)) = s.char_indices().nth(max) {
1471 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1472 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1473 // `unsafe` and otherwise don't emit any panic-related code
1475 s.get(..i).unwrap_or(s)
1482 // The `width` field is more of a `min-width` parameter at this point.
1484 // If we're under the maximum length, and there's no minimum length
1485 // requirements, then we can just emit the string
1486 None => self.buf.write_str(s),
1488 let chars_count = s.chars().count();
1489 // If we're under the maximum width, check if we're over the minimum
1490 // width, if so it's as easy as just emitting the string.
1491 if chars_count >= width {
1492 self.buf.write_str(s)
1494 // If we're under both the maximum and the minimum width, then fill
1495 // up the minimum width with the specified string + some alignment.
1497 let align = rt::v1::Alignment::Left;
1498 let post_padding = self.padding(width - chars_count, align)?;
1499 self.buf.write_str(s)?;
1500 post_padding.write(self)
1506 /// Write the pre-padding and return the unwritten post-padding. Callers are
1507 /// responsible for ensuring post-padding is written after the thing that is
1509 pub(crate) fn padding(
1512 default: rt::v1::Alignment,
1513 ) -> result::Result<PostPadding, Error> {
1514 let align = match self.align {
1515 rt::v1::Alignment::Unknown => default,
1519 let (pre_pad, post_pad) = match align {
1520 rt::v1::Alignment::Left => (0, padding),
1521 rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1522 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1525 for _ in 0..pre_pad {
1526 self.buf.write_char(self.fill)?;
1529 Ok(PostPadding::new(self.fill, post_pad))
1532 /// Takes the formatted parts and applies the padding.
1533 /// Assumes that the caller already has rendered the parts with required precision,
1534 /// so that `self.precision` can be ignored.
1535 fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1536 if let Some(mut width) = self.width {
1537 // for the sign-aware zero padding, we render the sign first and
1538 // behave as if we had no sign from the beginning.
1539 let mut formatted = formatted.clone();
1540 let old_fill = self.fill;
1541 let old_align = self.align;
1542 let mut align = old_align;
1543 if self.sign_aware_zero_pad() {
1544 // a sign always goes first
1545 let sign = formatted.sign;
1546 self.buf.write_str(sign)?;
1548 // remove the sign from the formatted parts
1549 formatted.sign = "";
1550 width = width.saturating_sub(sign.len());
1551 align = rt::v1::Alignment::Right;
1553 self.align = rt::v1::Alignment::Right;
1556 // remaining parts go through the ordinary padding process.
1557 let len = formatted.len();
1558 let ret = if width <= len {
1560 self.write_formatted_parts(&formatted)
1562 let post_padding = self.padding(width - len, align)?;
1563 self.write_formatted_parts(&formatted)?;
1564 post_padding.write(self)
1566 self.fill = old_fill;
1567 self.align = old_align;
1570 // this is the common case and we take a shortcut
1571 self.write_formatted_parts(formatted)
1575 fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1576 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1577 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1578 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1579 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1580 // It's also probably safe in practice to use for `numfmt::Part::Copy(buf)`
1581 // since `buf` should be plain ASCII, but it's possible for someone to pass
1582 // in a bad value for `buf` into `numfmt::to_shortest_str` since it is a
1584 // FIXME: Determine whether this could result in UB.
1585 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1588 if !formatted.sign.is_empty() {
1589 self.buf.write_str(formatted.sign)?;
1591 for part in formatted.parts {
1593 numfmt::Part::Zero(mut nzeroes) => {
1594 const ZEROES: &str = // 64 zeroes
1595 "0000000000000000000000000000000000000000000000000000000000000000";
1596 while nzeroes > ZEROES.len() {
1597 self.buf.write_str(ZEROES)?;
1598 nzeroes -= ZEROES.len();
1601 self.buf.write_str(&ZEROES[..nzeroes])?;
1604 numfmt::Part::Num(mut v) => {
1606 let len = part.len();
1607 for c in s[..len].iter_mut().rev() {
1608 *c = b'0' + (v % 10) as u8;
1611 write_bytes(self.buf, &s[..len])?;
1613 numfmt::Part::Copy(buf) => {
1614 write_bytes(self.buf, buf)?;
1621 /// Writes some data to the underlying buffer contained within this
1631 /// impl fmt::Display for Foo {
1632 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1633 /// formatter.write_str("Foo")
1634 /// // This is equivalent to:
1635 /// // write!(formatter, "Foo")
1639 /// assert_eq!(&format!("{Foo}"), "Foo");
1640 /// assert_eq!(&format!("{Foo:0>8}"), "Foo");
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 pub fn write_str(&mut self, data: &str) -> Result {
1644 self.buf.write_str(data)
1647 /// Writes some formatted information into this instance.
1654 /// struct Foo(i32);
1656 /// impl fmt::Display for Foo {
1657 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1658 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1662 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1663 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1667 write(self.buf, fmt)
1670 /// Flags for formatting
1672 #[stable(feature = "rust1", since = "1.0.0")]
1675 note = "use the `sign_plus`, `sign_minus`, `alternate`, \
1676 or `sign_aware_zero_pad` methods instead"
1678 pub fn flags(&self) -> u32 {
1682 /// Character used as 'fill' whenever there is alignment.
1691 /// impl fmt::Display for Foo {
1692 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1693 /// let c = formatter.fill();
1694 /// if let Some(width) = formatter.width() {
1695 /// for _ in 0..width {
1696 /// write!(formatter, "{c}")?;
1700 /// write!(formatter, "{c}")
1705 /// // We set alignment to the right with ">".
1706 /// assert_eq!(&format!("{Foo:G>3}"), "GGG");
1707 /// assert_eq!(&format!("{Foo:t>6}"), "tttttt");
1710 #[stable(feature = "fmt_flags", since = "1.5.0")]
1711 pub fn fill(&self) -> char {
1715 /// Flag indicating what form of alignment was requested.
1720 /// extern crate core;
1722 /// use std::fmt::{self, Alignment};
1726 /// impl fmt::Display for Foo {
1727 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1728 /// let s = if let Some(s) = formatter.align() {
1730 /// Alignment::Left => "left",
1731 /// Alignment::Right => "right",
1732 /// Alignment::Center => "center",
1737 /// write!(formatter, "{s}")
1741 /// assert_eq!(&format!("{Foo:<}"), "left");
1742 /// assert_eq!(&format!("{Foo:>}"), "right");
1743 /// assert_eq!(&format!("{Foo:^}"), "center");
1744 /// assert_eq!(&format!("{Foo}"), "into the void");
1747 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1748 pub fn align(&self) -> Option<Alignment> {
1750 rt::v1::Alignment::Left => Some(Alignment::Left),
1751 rt::v1::Alignment::Right => Some(Alignment::Right),
1752 rt::v1::Alignment::Center => Some(Alignment::Center),
1753 rt::v1::Alignment::Unknown => None,
1757 /// Optionally specified integer width that the output should be.
1764 /// struct Foo(i32);
1766 /// impl fmt::Display for Foo {
1767 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1768 /// if let Some(width) = formatter.width() {
1769 /// // If we received a width, we use it
1770 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1772 /// // Otherwise we do nothing special
1773 /// write!(formatter, "Foo({})", self.0)
1778 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1779 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1782 #[stable(feature = "fmt_flags", since = "1.5.0")]
1783 pub fn width(&self) -> Option<usize> {
1787 /// Optionally specified precision for numeric types. Alternatively, the
1788 /// maximum width for string types.
1795 /// struct Foo(f32);
1797 /// impl fmt::Display for Foo {
1798 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1799 /// if let Some(precision) = formatter.precision() {
1800 /// // If we received a precision, we use it.
1801 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1803 /// // Otherwise we default to 2.
1804 /// write!(formatter, "Foo({:.2})", self.0)
1809 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1810 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1813 #[stable(feature = "fmt_flags", since = "1.5.0")]
1814 pub fn precision(&self) -> Option<usize> {
1818 /// Determines if the `+` flag was specified.
1825 /// struct Foo(i32);
1827 /// impl fmt::Display for Foo {
1828 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1829 /// if formatter.sign_plus() {
1830 /// write!(formatter,
1832 /// if self.0 < 0 { '-' } else { '+' },
1835 /// write!(formatter, "Foo({})", self.0)
1840 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1841 /// assert_eq!(&format!("{:+}", Foo(-23)), "Foo(-23)");
1842 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1845 #[stable(feature = "fmt_flags", since = "1.5.0")]
1846 pub fn sign_plus(&self) -> bool {
1847 self.flags & (1 << FlagV1::SignPlus as u32) != 0
1850 /// Determines if the `-` flag was specified.
1857 /// struct Foo(i32);
1859 /// impl fmt::Display for Foo {
1860 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1861 /// if formatter.sign_minus() {
1862 /// // You want a minus sign? Have one!
1863 /// write!(formatter, "-Foo({})", self.0)
1865 /// write!(formatter, "Foo({})", self.0)
1870 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1871 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1874 #[stable(feature = "fmt_flags", since = "1.5.0")]
1875 pub fn sign_minus(&self) -> bool {
1876 self.flags & (1 << FlagV1::SignMinus as u32) != 0
1879 /// Determines if the `#` flag was specified.
1886 /// struct Foo(i32);
1888 /// impl fmt::Display for Foo {
1889 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1890 /// if formatter.alternate() {
1891 /// write!(formatter, "Foo({})", self.0)
1893 /// write!(formatter, "{}", self.0)
1898 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1899 /// assert_eq!(&format!("{}", Foo(23)), "23");
1902 #[stable(feature = "fmt_flags", since = "1.5.0")]
1903 pub fn alternate(&self) -> bool {
1904 self.flags & (1 << FlagV1::Alternate as u32) != 0
1907 /// Determines if the `0` flag was specified.
1914 /// struct Foo(i32);
1916 /// impl fmt::Display for Foo {
1917 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1918 /// assert!(formatter.sign_aware_zero_pad());
1919 /// assert_eq!(formatter.width(), Some(4));
1920 /// // We ignore the formatter's options.
1921 /// write!(formatter, "{}", self.0)
1925 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1928 #[stable(feature = "fmt_flags", since = "1.5.0")]
1929 pub fn sign_aware_zero_pad(&self) -> bool {
1930 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1933 // FIXME: Decide what public API we want for these two flags.
1934 // https://github.com/rust-lang/rust/issues/48584
1935 fn debug_lower_hex(&self) -> bool {
1936 self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1939 fn debug_upper_hex(&self) -> bool {
1940 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1943 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1944 /// [`fmt::Debug`] implementations for structs.
1946 /// [`fmt::Debug`]: self::Debug
1952 /// use std::net::Ipv4Addr;
1960 /// impl fmt::Debug for Foo {
1961 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1962 /// fmt.debug_struct("Foo")
1963 /// .field("bar", &self.bar)
1964 /// .field("baz", &self.baz)
1965 /// .field("addr", &format_args!("{}", self.addr))
1971 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1972 /// format!("{:?}", Foo {
1974 /// baz: "Hello World".to_string(),
1975 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1979 #[stable(feature = "debug_builders", since = "1.2.0")]
1980 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1981 builders::debug_struct_new(self, name)
1984 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
1985 /// `debug_struct_fields_finish` is more general, but this is faster for 1 field.
1987 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
1988 pub fn debug_struct_field1_finish<'b>(
1994 let mut builder = builders::debug_struct_new(self, name);
1995 builder.field(name1, value1);
1999 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2000 /// `debug_struct_fields_finish` is more general, but this is faster for 2 fields.
2002 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2003 pub fn debug_struct_field2_finish<'b>(
2011 let mut builder = builders::debug_struct_new(self, name);
2012 builder.field(name1, value1);
2013 builder.field(name2, value2);
2017 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2018 /// `debug_struct_fields_finish` is more general, but this is faster for 3 fields.
2020 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2021 pub fn debug_struct_field3_finish<'b>(
2031 let mut builder = builders::debug_struct_new(self, name);
2032 builder.field(name1, value1);
2033 builder.field(name2, value2);
2034 builder.field(name3, value3);
2038 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2039 /// `debug_struct_fields_finish` is more general, but this is faster for 4 fields.
2041 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2042 pub fn debug_struct_field4_finish<'b>(
2054 let mut builder = builders::debug_struct_new(self, name);
2055 builder.field(name1, value1);
2056 builder.field(name2, value2);
2057 builder.field(name3, value3);
2058 builder.field(name4, value4);
2062 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2063 /// `debug_struct_fields_finish` is more general, but this is faster for 5 fields.
2065 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2066 pub fn debug_struct_field5_finish<'b>(
2080 let mut builder = builders::debug_struct_new(self, name);
2081 builder.field(name1, value1);
2082 builder.field(name2, value2);
2083 builder.field(name3, value3);
2084 builder.field(name4, value4);
2085 builder.field(name5, value5);
2089 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2090 /// For the cases not covered by `debug_struct_field[12345]_finish`.
2092 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2093 pub fn debug_struct_fields_finish<'b>(
2097 values: &[&dyn Debug],
2099 assert_eq!(names.len(), values.len());
2100 let mut builder = builders::debug_struct_new(self, name);
2101 for (name, value) in iter::zip(names, values) {
2102 builder.field(name, value);
2107 /// Creates a `DebugTuple` builder designed to assist with creation of
2108 /// `fmt::Debug` implementations for tuple structs.
2114 /// use std::marker::PhantomData;
2116 /// struct Foo<T>(i32, String, PhantomData<T>);
2118 /// impl<T> fmt::Debug for Foo<T> {
2119 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2120 /// fmt.debug_tuple("Foo")
2123 /// .field(&format_args!("_"))
2129 /// "Foo(10, \"Hello\", _)",
2130 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
2133 #[stable(feature = "debug_builders", since = "1.2.0")]
2134 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
2135 builders::debug_tuple_new(self, name)
2138 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2139 /// `debug_tuple_fields_finish` is more general, but this is faster for 1 field.
2141 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2142 pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result {
2143 let mut builder = builders::debug_tuple_new(self, name);
2144 builder.field(value1);
2148 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2149 /// `debug_tuple_fields_finish` is more general, but this is faster for 2 fields.
2151 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2152 pub fn debug_tuple_field2_finish<'b>(
2158 let mut builder = builders::debug_tuple_new(self, name);
2159 builder.field(value1);
2160 builder.field(value2);
2164 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2165 /// `debug_tuple_fields_finish` is more general, but this is faster for 3 fields.
2167 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2168 pub fn debug_tuple_field3_finish<'b>(
2175 let mut builder = builders::debug_tuple_new(self, name);
2176 builder.field(value1);
2177 builder.field(value2);
2178 builder.field(value3);
2182 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2183 /// `debug_tuple_fields_finish` is more general, but this is faster for 4 fields.
2185 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2186 pub fn debug_tuple_field4_finish<'b>(
2194 let mut builder = builders::debug_tuple_new(self, name);
2195 builder.field(value1);
2196 builder.field(value2);
2197 builder.field(value3);
2198 builder.field(value4);
2202 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2203 /// `debug_tuple_fields_finish` is more general, but this is faster for 5 fields.
2205 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2206 pub fn debug_tuple_field5_finish<'b>(
2215 let mut builder = builders::debug_tuple_new(self, name);
2216 builder.field(value1);
2217 builder.field(value2);
2218 builder.field(value3);
2219 builder.field(value4);
2220 builder.field(value5);
2224 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2225 /// For the cases not covered by `debug_tuple_field[12345]_finish`.
2227 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2228 pub fn debug_tuple_fields_finish<'b>(
2231 values: &[&dyn Debug],
2233 let mut builder = builders::debug_tuple_new(self, name);
2234 for value in values {
2235 builder.field(value);
2240 /// Creates a `DebugList` builder designed to assist with creation of
2241 /// `fmt::Debug` implementations for list-like structures.
2248 /// struct Foo(Vec<i32>);
2250 /// impl fmt::Debug for Foo {
2251 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2252 /// fmt.debug_list().entries(self.0.iter()).finish()
2256 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2258 #[stable(feature = "debug_builders", since = "1.2.0")]
2259 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2260 builders::debug_list_new(self)
2263 /// Creates a `DebugSet` builder designed to assist with creation of
2264 /// `fmt::Debug` implementations for set-like structures.
2271 /// struct Foo(Vec<i32>);
2273 /// impl fmt::Debug for Foo {
2274 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2275 /// fmt.debug_set().entries(self.0.iter()).finish()
2279 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2282 /// [`format_args!`]: crate::format_args
2284 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2285 /// to build a list of match arms:
2290 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
2291 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
2293 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2295 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
2297 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2298 /// L::fmt(&(self.0).0, fmt)?;
2299 /// fmt.write_str(" => ")?;
2300 /// R::fmt(&(self.0).1, fmt)
2304 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2306 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
2308 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2310 /// .entries(self.0.iter().map(Arm))
2311 /// .entry(&Arm(&(format_args!("_"), &self.1)))
2316 #[stable(feature = "debug_builders", since = "1.2.0")]
2317 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2318 builders::debug_set_new(self)
2321 /// Creates a `DebugMap` builder designed to assist with creation of
2322 /// `fmt::Debug` implementations for map-like structures.
2329 /// struct Foo(Vec<(String, i32)>);
2331 /// impl fmt::Debug for Foo {
2332 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2333 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2338 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2339 /// r#"{"A": 10, "B": 11}"#
2342 #[stable(feature = "debug_builders", since = "1.2.0")]
2343 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2344 builders::debug_map_new(self)
2348 #[stable(since = "1.2.0", feature = "formatter_write")]
2349 impl Write for Formatter<'_> {
2350 fn write_str(&mut self, s: &str) -> Result {
2351 self.buf.write_str(s)
2354 fn write_char(&mut self, c: char) -> Result {
2355 self.buf.write_char(c)
2358 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2359 write(self.buf, args)
2363 #[stable(feature = "rust1", since = "1.0.0")]
2364 impl Display for Error {
2365 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2366 Display::fmt("an error occurred when formatting an argument", f)
2370 // Implementations of the core formatting traits
2372 macro_rules! fmt_refs {
2373 ($($tr:ident),*) => {
2375 #[stable(feature = "rust1", since = "1.0.0")]
2376 impl<T: ?Sized + $tr> $tr for &T {
2377 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2379 #[stable(feature = "rust1", since = "1.0.0")]
2380 impl<T: ?Sized + $tr> $tr for &mut T {
2381 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2387 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2389 #[unstable(feature = "never_type", issue = "35121")]
2391 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2396 #[unstable(feature = "never_type", issue = "35121")]
2397 impl Display for ! {
2398 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2403 #[stable(feature = "rust1", since = "1.0.0")]
2404 impl Debug for bool {
2406 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2407 Display::fmt(self, f)
2411 #[stable(feature = "rust1", since = "1.0.0")]
2412 impl Display for bool {
2413 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2414 Display::fmt(if *self { "true" } else { "false" }, f)
2418 #[stable(feature = "rust1", since = "1.0.0")]
2419 impl Debug for str {
2420 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2423 for (i, c) in self.char_indices() {
2424 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2425 escape_grapheme_extended: true,
2426 escape_single_quote: false,
2427 escape_double_quote: true,
2429 // If char needs escaping, flush backlog so far and write, else skip
2431 f.write_str(&self[from..i])?;
2435 from = i + c.len_utf8();
2438 f.write_str(&self[from..])?;
2443 #[stable(feature = "rust1", since = "1.0.0")]
2444 impl Display for str {
2445 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2450 #[stable(feature = "rust1", since = "1.0.0")]
2451 impl Debug for char {
2452 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2453 f.write_char('\'')?;
2454 for c in self.escape_debug_ext(EscapeDebugExtArgs {
2455 escape_grapheme_extended: true,
2456 escape_single_quote: true,
2457 escape_double_quote: false,
2465 #[stable(feature = "rust1", since = "1.0.0")]
2466 impl Display for char {
2467 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2468 if f.width.is_none() && f.precision.is_none() {
2471 f.pad(self.encode_utf8(&mut [0; 4]))
2476 #[stable(feature = "rust1", since = "1.0.0")]
2477 impl<T: ?Sized> Pointer for *const T {
2478 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2479 // Cast is needed here because `.expose_addr()` requires `T: Sized`.
2480 pointer_fmt_inner((*self as *const ()).expose_addr(), f)
2484 /// Since the formatting will be identical for all pointer types, use a non-monomorphized
2485 /// implementation for the actual formatting to reduce the amount of codegen work needed.
2487 /// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
2488 /// `fn(...) -> ...` without using [problematic] "Oxford Casts".
2490 /// [problematic]: https://github.com/rust-lang/rust/issues/95489
2491 pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
2492 let old_width = f.width;
2493 let old_flags = f.flags;
2495 // The alternate flag is already treated by LowerHex as being special-
2496 // it denotes whether to prefix with 0x. We use it to work out whether
2497 // or not to zero extend, and then unconditionally set it to get the
2500 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2502 if f.width.is_none() {
2503 f.width = Some((usize::BITS / 4) as usize + 2);
2506 f.flags |= 1 << (FlagV1::Alternate as u32);
2508 let ret = LowerHex::fmt(&ptr_addr, f);
2510 f.width = old_width;
2511 f.flags = old_flags;
2516 #[stable(feature = "rust1", since = "1.0.0")]
2517 impl<T: ?Sized> Pointer for *mut T {
2518 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2519 Pointer::fmt(&(*self as *const T), f)
2523 #[stable(feature = "rust1", since = "1.0.0")]
2524 impl<T: ?Sized> Pointer for &T {
2525 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2526 Pointer::fmt(&(*self as *const T), f)
2530 #[stable(feature = "rust1", since = "1.0.0")]
2531 impl<T: ?Sized> Pointer for &mut T {
2532 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2533 Pointer::fmt(&(&**self as *const T), f)
2537 // Implementation of Display/Debug for various core types
2539 #[stable(feature = "rust1", since = "1.0.0")]
2540 impl<T: ?Sized> Debug for *const T {
2541 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2542 Pointer::fmt(self, f)
2545 #[stable(feature = "rust1", since = "1.0.0")]
2546 impl<T: ?Sized> Debug for *mut T {
2547 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2548 Pointer::fmt(self, f)
2553 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2556 macro_rules! tuple {
2558 ( $($name:ident,)+ ) => (
2561 #[stable(feature = "rust1", since = "1.0.0")]
2562 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2563 #[allow(non_snake_case, unused_assignments)]
2564 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2565 let mut builder = f.debug_tuple("");
2566 let ($(ref $name,)+) = *self;
2568 builder.field(&$name);
2575 peel! { $($name,)+ }
2579 macro_rules! maybe_tuple_doc {
2580 ($a:ident @ #[$meta:meta] $item:item) => {
2581 #[doc(fake_variadic)]
2582 #[doc = "This trait is implemented for tuples up to twelve items long."]
2586 ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
2593 macro_rules! last_type {
2594 ($a:ident,) => { $a };
2595 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2598 tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
2600 #[stable(feature = "rust1", since = "1.0.0")]
2601 impl<T: Debug> Debug for [T] {
2602 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2603 f.debug_list().entries(self.iter()).finish()
2607 #[stable(feature = "rust1", since = "1.0.0")]
2610 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2614 #[stable(feature = "rust1", since = "1.0.0")]
2615 impl<T: ?Sized> Debug for PhantomData<T> {
2616 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2617 write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
2621 #[stable(feature = "rust1", since = "1.0.0")]
2622 impl<T: Copy + Debug> Debug for Cell<T> {
2623 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2624 f.debug_struct("Cell").field("value", &self.get()).finish()
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2630 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2631 match self.try_borrow() {
2632 Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2634 // The RefCell is mutably borrowed so we can't look at its value
2635 // here. Show a placeholder instead.
2636 struct BorrowedPlaceholder;
2638 impl Debug for BorrowedPlaceholder {
2639 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2640 f.write_str("<borrowed>")
2644 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2650 #[stable(feature = "rust1", since = "1.0.0")]
2651 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2652 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2653 Debug::fmt(&**self, f)
2657 #[stable(feature = "rust1", since = "1.0.0")]
2658 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2659 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2660 Debug::fmt(&*(self.deref()), f)
2664 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2665 impl<T: ?Sized> Debug for UnsafeCell<T> {
2666 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2667 f.debug_struct("UnsafeCell").finish_non_exhaustive()
2671 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2672 impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
2673 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2674 f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
2678 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2679 // it's a lot easier than creating all of the rt::Piece structures here.
2680 // There are also tests in the alloc crate, for those that need allocations.