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.
180 /// use std::fmt::{Error, Write};
182 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
183 /// f.write_fmt(format_args!("{s}"))
186 /// let mut buf = String::new();
187 /// writer(&mut buf, "world").unwrap();
188 /// assert_eq!(&buf, "world");
190 #[stable(feature = "rust1", since = "1.0.0")]
191 fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
192 write(&mut self, args)
196 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
197 impl<W: Write + ?Sized> Write for &mut W {
198 fn write_str(&mut self, s: &str) -> Result {
199 (**self).write_str(s)
202 fn write_char(&mut self, c: char) -> Result {
203 (**self).write_char(c)
206 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
207 (**self).write_fmt(args)
211 /// Configuration for formatting.
213 /// A `Formatter` represents various options related to formatting. Users do not
214 /// construct `Formatter`s directly; a mutable reference to one is passed to
215 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
217 /// To interact with a `Formatter`, you'll call various methods to change the
218 /// various options related to formatting. For examples, please see the
219 /// documentation of the methods defined on `Formatter` below.
220 #[allow(missing_debug_implementations)]
221 #[stable(feature = "rust1", since = "1.0.0")]
222 pub struct Formatter<'a> {
225 align: rt::v1::Alignment,
226 width: Option<usize>,
227 precision: Option<usize>,
229 buf: &'a mut (dyn Write + 'a),
232 impl<'a> Formatter<'a> {
233 /// Creates a new formatter with default settings.
235 /// This can be used as a micro-optimization in cases where a full `Arguments`
236 /// structure (as created by `format_args!`) is not necessary; `Arguments`
237 /// is a little more expensive to use in simple formatting scenarios.
239 /// Currently not intended for use outside of the standard library.
240 #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
242 pub fn new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
246 align: rt::v1::Alignment::Unknown,
254 // NB. Argument is essentially an optimized partially applied formatting function,
255 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
261 /// This struct represents the generic "argument" which is taken by the Xprintf
262 /// family of functions. It contains a function to format the given value. At
263 /// compile time it is ensured that the function and the value have the correct
264 /// types, and then this struct is used to canonicalize arguments to one type.
265 #[derive(Copy, Clone)]
266 #[allow(missing_debug_implementations)]
267 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
269 pub struct ArgumentV1<'a> {
271 formatter: fn(&Opaque, &mut Formatter<'_>) -> Result,
274 /// This struct represents the unsafety of constructing an `Arguments`.
275 /// It exists, rather than an unsafe function, in order to simplify the expansion
276 /// of `format_args!(..)` and reduce the scope of the `unsafe` block.
277 #[allow(missing_debug_implementations)]
279 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
280 pub struct UnsafeArg {
285 /// See documentation where `UnsafeArg` is required to know when it is safe to
286 /// create and use `UnsafeArg`.
288 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
290 pub unsafe fn new() -> Self {
291 Self { _private: () }
295 // This guarantees a single stable value for the function pointer associated with
296 // indices/counts in the formatting infrastructure.
298 // Note that a function defined as such would not be correct as functions are
299 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
300 // address is not considered important to LLVM and as such the as_usize cast
301 // could have been miscompiled. In practice, we never call as_usize on non-usize
302 // containing data (as a matter of static generation of the formatting
303 // arguments), so this is merely an additional check.
305 // We primarily want to ensure that the function pointer at `USIZE_MARKER` has
306 // an address corresponding *only* to functions that also take `&usize` as their
307 // first argument. The read_volatile here ensures that we can safely ready out a
308 // usize from the passed reference and that this address does not point at a
309 // non-usize taking function.
310 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
311 static USIZE_MARKER: fn(&usize, &mut Formatter<'_>) -> Result = |ptr, _| {
312 // SAFETY: ptr is a reference
313 let _v: usize = unsafe { crate::ptr::read_volatile(ptr) };
317 macro_rules! arg_new {
318 ($f: ident, $t: ident) => {
320 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
322 pub fn $f<'b, T: $t>(x: &'b T) -> ArgumentV1<'_> {
323 Self::new(x, $t::fmt)
328 #[rustc_diagnostic_item = "ArgumentV1Methods"]
329 impl<'a> ArgumentV1<'a> {
331 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
333 pub fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
334 // SAFETY: `mem::transmute(x)` is safe because
335 // 1. `&'b T` keeps the lifetime it originated with `'b`
336 // (so as to not have an unbounded lifetime)
337 // 2. `&'b T` and `&'b Opaque` have the same memory layout
338 // (when `T` is `Sized`, as it is here)
339 // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
340 // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
341 // (as long as `T` is `Sized`)
342 unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) } }
345 arg_new!(new_display, Display);
346 arg_new!(new_debug, Debug);
347 arg_new!(new_octal, Octal);
348 arg_new!(new_lower_hex, LowerHex);
349 arg_new!(new_upper_hex, UpperHex);
350 arg_new!(new_pointer, Pointer);
351 arg_new!(new_binary, Binary);
352 arg_new!(new_lower_exp, LowerExp);
353 arg_new!(new_upper_exp, UpperExp);
356 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
357 pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
358 ArgumentV1::new(x, USIZE_MARKER)
361 fn as_usize(&self) -> Option<usize> {
362 // We are type punning a bit here: USIZE_MARKER only takes an &usize but
363 // formatter takes an &Opaque. Rust understandably doesn't think we should compare
364 // the function pointers if they don't have the same signature, so we cast to
365 // usizes to tell it that we just want to compare addresses.
366 if self.formatter as usize == USIZE_MARKER as usize {
367 // SAFETY: The `formatter` field is only set to USIZE_MARKER if
368 // the value is a usize, so this is safe
369 Some(unsafe { *(self.value as *const _ as *const usize) })
376 // flags available in the v1 format of format_args
377 #[derive(Copy, Clone)]
387 impl<'a> Arguments<'a> {
388 /// When using the format_args!() macro, this function is used to generate the
389 /// Arguments structure.
392 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
393 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
394 pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
395 if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
396 panic!("invalid args");
398 Arguments { pieces, fmt: None, args }
401 /// This function is used to specify nonstandard formatting parameters.
403 /// An `UnsafeArg` is required because the following invariants must be held
404 /// in order for this function to be safe:
405 /// 1. The `pieces` slice must be at least as long as `fmt`.
406 /// 2. Every [`rt::v1::Argument::position`] value within `fmt` must be a
407 /// valid index of `args`.
408 /// 3. Every [`rt::v1::Count::Param`] within `fmt` must contain a valid index of
412 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
413 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
414 pub const fn new_v1_formatted(
415 pieces: &'a [&'static str],
416 args: &'a [ArgumentV1<'a>],
417 fmt: &'a [rt::v1::Argument],
418 _unsafe_arg: UnsafeArg,
420 Arguments { pieces, fmt: Some(fmt), args }
423 /// Estimates the length of the formatted text.
425 /// This is intended to be used for setting initial `String` capacity
426 /// when using `format!`. Note: this is neither the lower nor upper bound.
429 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
430 pub fn estimated_capacity(&self) -> usize {
431 let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
433 if self.args.is_empty() {
435 } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
436 // If the format string starts with an argument,
437 // don't preallocate anything, unless length
438 // of pieces is significant.
441 // There are some arguments, so any additional push
442 // will reallocate the string. To avoid that,
443 // we're "pre-doubling" the capacity here.
444 pieces_length.checked_mul(2).unwrap_or(0)
449 /// This structure represents a safely precompiled version of a format string
450 /// and its arguments. This cannot be generated at runtime because it cannot
451 /// safely be done, so no constructors are given and the fields are private
452 /// to prevent modification.
454 /// The [`format_args!`] macro will safely create an instance of this structure.
455 /// The macro validates the format string at compile-time so usage of the
456 /// [`write()`] and [`format()`] functions can be safely performed.
458 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
459 /// and `Display` contexts as seen below. The example also shows that `Debug`
460 /// and `Display` format to the same thing: the interpolated format string
461 /// in `format_args!`.
464 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
465 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
466 /// assert_eq!("1 foo 2", display);
467 /// assert_eq!(display, debug);
470 /// [`format()`]: ../../std/fmt/fn.format.html
471 #[stable(feature = "rust1", since = "1.0.0")]
472 #[cfg_attr(not(test), rustc_diagnostic_item = "Arguments")]
473 #[derive(Copy, Clone)]
474 pub struct Arguments<'a> {
475 // Format string pieces to print.
476 pieces: &'a [&'static str],
478 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
479 fmt: Option<&'a [rt::v1::Argument]>,
481 // Dynamic arguments for interpolation, to be interleaved with string
482 // pieces. (Every argument is preceded by a string piece.)
483 args: &'a [ArgumentV1<'a>],
486 impl<'a> Arguments<'a> {
487 /// Get the formatted string, if it has no arguments to be formatted.
489 /// This can be used to avoid allocations in the most trivial case.
494 /// use std::fmt::Arguments;
496 /// fn write_str(_: &str) { /* ... */ }
498 /// fn write_fmt(args: &Arguments) {
499 /// if let Some(s) = args.as_str() {
502 /// write_str(&args.to_string());
508 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
509 /// assert_eq!(format_args!("").as_str(), Some(""));
510 /// assert_eq!(format_args!("{}", 1).as_str(), None);
512 #[stable(feature = "fmt_as_str", since = "1.52.0")]
513 #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")]
516 pub const fn as_str(&self) -> Option<&'static str> {
517 match (self.pieces, self.args) {
518 ([], []) => Some(""),
519 ([s], []) => Some(s),
525 #[stable(feature = "rust1", since = "1.0.0")]
526 impl Debug for Arguments<'_> {
527 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
528 Display::fmt(self, fmt)
532 #[stable(feature = "rust1", since = "1.0.0")]
533 impl Display for Arguments<'_> {
534 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
535 write(fmt.buf, *self)
541 /// `Debug` should format the output in a programmer-facing, debugging context.
543 /// Generally speaking, you should just `derive` a `Debug` implementation.
545 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
547 /// For more information on formatters, see [the module-level documentation][module].
549 /// [module]: ../../std/fmt/index.html
551 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
552 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
553 /// comma-separated list of each field's name and `Debug` value, then `}`. For
554 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
555 /// `Debug` values of the fields, then `)`.
559 /// Derived `Debug` formats are not stable, and so may change with future Rust
560 /// versions. Additionally, `Debug` implementations of types provided by the
561 /// standard library (`std`, `core`, `alloc`, etc.) are not stable, and
562 /// may also change with future Rust versions.
566 /// Deriving an implementation:
575 /// let origin = Point { x: 0, y: 0 };
577 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
580 /// Manually implementing:
590 /// impl fmt::Debug for Point {
591 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592 /// f.debug_struct("Point")
593 /// .field("x", &self.x)
594 /// .field("y", &self.y)
599 /// let origin = Point { x: 0, y: 0 };
601 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
604 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
605 /// implementations, such as [`debug_struct`].
607 /// [`debug_struct`]: Formatter::debug_struct
609 /// Types that do not wish to use the standard suite of debug representations
610 /// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
611 /// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
612 /// manually writing an arbitrary representation to the `Formatter`.
621 /// impl fmt::Debug for Point {
622 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623 /// write!(f, "Point [{} {}]", self.x, self.y)
628 /// `Debug` implementations using either `derive` or the debug builder API
629 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
631 /// Pretty-printing with `#?`:
640 /// let origin = Point { x: 0, y: 0 };
642 /// assert_eq!(format!("The origin is: {origin:#?}"),
643 /// "The origin is: Point {
649 #[stable(feature = "rust1", since = "1.0.0")]
650 #[rustc_on_unimplemented(
653 label = "`{Self}` cannot be formatted using `{{:?}}`",
654 note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
656 message = "`{Self}` doesn't implement `{Debug}`",
657 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
659 #[doc(alias = "{:?}")]
660 #[rustc_diagnostic_item = "Debug"]
661 #[rustc_trivial_field_reads]
663 /// Formats the value using the given formatter.
670 /// struct Position {
675 /// impl fmt::Debug for Position {
676 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677 /// f.debug_tuple("")
678 /// .field(&self.longitude)
679 /// .field(&self.latitude)
684 /// let position = Position { longitude: 1.987, latitude: 2.983 };
685 /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
687 /// assert_eq!(format!("{position:#?}"), "(
692 #[stable(feature = "rust1", since = "1.0.0")]
693 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
696 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
697 pub(crate) mod macros {
698 /// Derive macro generating an impl of the trait `Debug`.
699 #[rustc_builtin_macro]
700 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
701 #[allow_internal_unstable(core_intrinsics, fmt_helpers_for_derive)]
702 pub macro Debug($item:item) {
703 /* compiler built-in */
706 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
708 pub use macros::Debug;
710 /// Format trait for an empty format, `{}`.
712 /// Implementing this trait for a type will automatically implement the
713 /// [`ToString`][tostring] trait for the type, allowing the usage
714 /// of the [`.to_string()`][tostring_function] method. Prefer implementing
715 /// the `Display` trait for a type, rather than [`ToString`][tostring].
717 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
718 /// output, and so cannot be derived.
720 /// For more information on formatters, see [the module-level documentation][module].
722 /// [module]: ../../std/fmt/index.html
723 /// [tostring]: ../../std/string/trait.ToString.html
724 /// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
728 /// Implementing `Display` on a type:
738 /// impl fmt::Display for Point {
739 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
740 /// write!(f, "({}, {})", self.x, self.y)
744 /// let origin = Point { x: 0, y: 0 };
746 /// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
748 #[rustc_on_unimplemented(
750 any(_Self = "std::path::Path", _Self = "std::path::PathBuf"),
751 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
752 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
753 as they may contain non-Unicode data"
755 message = "`{Self}` doesn't implement `{Display}`",
756 label = "`{Self}` cannot be formatted with the default formatter",
757 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
760 #[rustc_diagnostic_item = "Display"]
761 #[stable(feature = "rust1", since = "1.0.0")]
763 /// Formats the value using the given formatter.
770 /// struct Position {
775 /// impl fmt::Display for Position {
776 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
777 /// write!(f, "({}, {})", self.longitude, self.latitude)
781 /// assert_eq!("(1.987, 2.983)",
782 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
784 #[stable(feature = "rust1", since = "1.0.0")]
785 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
790 /// The `Octal` trait should format its output as a number in base-8.
792 /// For primitive signed integers (`i8` to `i128`, and `isize`),
793 /// negative values are formatted as the two’s complement representation.
795 /// The alternate flag, `#`, adds a `0o` in front of the output.
797 /// For more information on formatters, see [the module-level documentation][module].
799 /// [module]: ../../std/fmt/index.html
803 /// Basic usage with `i32`:
806 /// let x = 42; // 42 is '52' in octal
808 /// assert_eq!(format!("{x:o}"), "52");
809 /// assert_eq!(format!("{x:#o}"), "0o52");
811 /// assert_eq!(format!("{:o}", -16), "37777777760");
814 /// Implementing `Octal` on a type:
819 /// struct Length(i32);
821 /// impl fmt::Octal for Length {
822 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
823 /// let val = self.0;
825 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
829 /// let l = Length(9);
831 /// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
833 /// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
835 #[stable(feature = "rust1", since = "1.0.0")]
837 /// Formats the value using the given formatter.
838 #[stable(feature = "rust1", since = "1.0.0")]
839 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
844 /// The `Binary` trait should format its output as a number in binary.
846 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
847 /// negative values are formatted as the two’s complement representation.
849 /// The alternate flag, `#`, adds a `0b` in front of the output.
851 /// For more information on formatters, see [the module-level documentation][module].
853 /// [module]: ../../std/fmt/index.html
857 /// Basic usage with [`i32`]:
860 /// let x = 42; // 42 is '101010' in binary
862 /// assert_eq!(format!("{x:b}"), "101010");
863 /// assert_eq!(format!("{x:#b}"), "0b101010");
865 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
868 /// Implementing `Binary` on a type:
873 /// struct Length(i32);
875 /// impl fmt::Binary for Length {
876 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
877 /// let val = self.0;
879 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
883 /// let l = Length(107);
885 /// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
888 /// format!("l as binary is: {l:#032b}"),
889 /// "l as binary is: 0b000000000000000000000001101011"
892 #[stable(feature = "rust1", since = "1.0.0")]
894 /// Formats the value using the given formatter.
895 #[stable(feature = "rust1", since = "1.0.0")]
896 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
901 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
904 /// For primitive signed integers (`i8` to `i128`, and `isize`),
905 /// negative values are formatted as the two’s complement representation.
907 /// The alternate flag, `#`, adds a `0x` in front of the output.
909 /// For more information on formatters, see [the module-level documentation][module].
911 /// [module]: ../../std/fmt/index.html
915 /// Basic usage with `i32`:
918 /// let x = 42; // 42 is '2a' in hex
920 /// assert_eq!(format!("{x:x}"), "2a");
921 /// assert_eq!(format!("{x:#x}"), "0x2a");
923 /// assert_eq!(format!("{:x}", -16), "fffffff0");
926 /// Implementing `LowerHex` on a type:
931 /// struct Length(i32);
933 /// impl fmt::LowerHex for Length {
934 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
935 /// let val = self.0;
937 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
941 /// let l = Length(9);
943 /// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
945 /// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
947 #[stable(feature = "rust1", since = "1.0.0")]
949 /// Formats the value using the given formatter.
950 #[stable(feature = "rust1", since = "1.0.0")]
951 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
956 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
959 /// For primitive signed integers (`i8` to `i128`, and `isize`),
960 /// negative values are formatted as the two’s complement representation.
962 /// The alternate flag, `#`, adds a `0x` in front of the output.
964 /// For more information on formatters, see [the module-level documentation][module].
966 /// [module]: ../../std/fmt/index.html
970 /// Basic usage with `i32`:
973 /// let x = 42; // 42 is '2A' in hex
975 /// assert_eq!(format!("{x:X}"), "2A");
976 /// assert_eq!(format!("{x:#X}"), "0x2A");
978 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
981 /// Implementing `UpperHex` on a type:
986 /// struct Length(i32);
988 /// impl fmt::UpperHex for Length {
989 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
990 /// let val = self.0;
992 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
996 /// let l = Length(i32::MAX);
998 /// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
1000 /// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 pub trait UpperHex {
1004 /// Formats the value using the given formatter.
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1011 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
1014 /// For more information on formatters, see [the module-level documentation][module].
1016 /// [module]: ../../std/fmt/index.html
1020 /// Basic usage with `&i32`:
1025 /// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
1028 /// Implementing `Pointer` on a type:
1033 /// struct Length(i32);
1035 /// impl fmt::Pointer for Length {
1036 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1037 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1039 /// let ptr = self as *const Self;
1040 /// fmt::Pointer::fmt(&ptr, f)
1044 /// let l = Length(42);
1046 /// println!("l is in memory here: {l:p}");
1048 /// let l_ptr = format!("{l:018p}");
1049 /// assert_eq!(l_ptr.len(), 18);
1050 /// assert_eq!(&l_ptr[..2], "0x");
1052 #[stable(feature = "rust1", since = "1.0.0")]
1053 #[rustc_diagnostic_item = "Pointer"]
1055 /// Formats the value using the given formatter.
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1062 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1064 /// For more information on formatters, see [the module-level documentation][module].
1066 /// [module]: ../../std/fmt/index.html
1070 /// Basic usage with `f64`:
1073 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1075 /// assert_eq!(format!("{x:e}"), "4.2e1");
1078 /// Implementing `LowerExp` on a type:
1083 /// struct Length(i32);
1085 /// impl fmt::LowerExp for Length {
1086 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1087 /// let val = f64::from(self.0);
1088 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1092 /// let l = Length(100);
1095 /// format!("l in scientific notation is: {l:e}"),
1096 /// "l in scientific notation is: 1e2"
1100 /// format!("l in scientific notation is: {l:05e}"),
1101 /// "l in scientific notation is: 001e2"
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 pub trait LowerExp {
1106 /// Formats the value using the given formatter.
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1113 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1115 /// For more information on formatters, see [the module-level documentation][module].
1117 /// [module]: ../../std/fmt/index.html
1121 /// Basic usage with `f64`:
1124 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1126 /// assert_eq!(format!("{x:E}"), "4.2E1");
1129 /// Implementing `UpperExp` on a type:
1134 /// struct Length(i32);
1136 /// impl fmt::UpperExp for Length {
1137 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138 /// let val = f64::from(self.0);
1139 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1143 /// let l = Length(100);
1146 /// format!("l in scientific notation is: {l:E}"),
1147 /// "l in scientific notation is: 1E2"
1151 /// format!("l in scientific notation is: {l:05E}"),
1152 /// "l in scientific notation is: 001E2"
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub trait UpperExp {
1157 /// Formats the value using the given formatter.
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1162 /// The `write` function takes an output stream, and an `Arguments` struct
1163 /// that can be precompiled with the `format_args!` macro.
1165 /// The arguments will be formatted according to the specified format string
1166 /// into the output stream provided.
1175 /// let mut output = String::new();
1176 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1177 /// .expect("Error occurred while trying to write in String");
1178 /// assert_eq!(output, "Hello world!");
1181 /// Please note that using [`write!`] might be preferable. Example:
1184 /// use std::fmt::Write;
1186 /// let mut output = String::new();
1187 /// write!(&mut output, "Hello {}!", "world")
1188 /// .expect("Error occurred while trying to write in String");
1189 /// assert_eq!(output, "Hello world!");
1192 /// [`write!`]: crate::write!
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1195 let mut formatter = Formatter::new(output);
1200 // We can use default formatting parameters for all arguments.
1201 for (i, arg) in args.args.iter().enumerate() {
1202 // SAFETY: args.args and args.pieces come from the same Arguments,
1203 // which guarantees the indexes are always within bounds.
1204 let piece = unsafe { args.pieces.get_unchecked(i) };
1205 if !piece.is_empty() {
1206 formatter.buf.write_str(*piece)?;
1208 (arg.formatter)(arg.value, &mut formatter)?;
1213 // Every spec has a corresponding argument that is preceded by
1215 for (i, arg) in fmt.iter().enumerate() {
1216 // SAFETY: fmt and args.pieces come from the same Arguments,
1217 // which guarantees the indexes are always within bounds.
1218 let piece = unsafe { args.pieces.get_unchecked(i) };
1219 if !piece.is_empty() {
1220 formatter.buf.write_str(*piece)?;
1222 // SAFETY: arg and args.args come from the same Arguments,
1223 // which guarantees the indexes are always within bounds.
1224 unsafe { run(&mut formatter, arg, args.args) }?;
1230 // There can be only one trailing string piece left.
1231 if let Some(piece) = args.pieces.get(idx) {
1232 formatter.buf.write_str(*piece)?;
1238 unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1239 fmt.fill = arg.format.fill;
1240 fmt.align = arg.format.align;
1241 fmt.flags = arg.format.flags;
1242 // SAFETY: arg and args come from the same Arguments,
1243 // which guarantees the indexes are always within bounds.
1245 fmt.width = getcount(args, &arg.format.width);
1246 fmt.precision = getcount(args, &arg.format.precision);
1249 // Extract the correct argument
1250 debug_assert!(arg.position < args.len());
1251 // SAFETY: arg and args come from the same Arguments,
1252 // which guarantees its index is always within bounds.
1253 let value = unsafe { args.get_unchecked(arg.position) };
1255 // Then actually do some printing
1256 (value.formatter)(value.value, fmt)
1259 unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1261 rt::v1::Count::Is(n) => Some(n),
1262 rt::v1::Count::Implied => None,
1263 rt::v1::Count::Param(i) => {
1264 debug_assert!(i < args.len());
1265 // SAFETY: cnt and args come from the same Arguments,
1266 // which guarantees this index is always within bounds.
1267 unsafe { args.get_unchecked(i).as_usize() }
1272 /// Padding after the end of something. Returned by `Formatter::padding`.
1273 #[must_use = "don't forget to write the post padding"]
1274 pub(crate) struct PostPadding {
1280 fn new(fill: char, padding: usize) -> PostPadding {
1281 PostPadding { fill, padding }
1284 /// Write this post padding.
1285 pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1286 for _ in 0..self.padding {
1287 f.buf.write_char(self.fill)?;
1293 impl<'a> Formatter<'a> {
1294 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1297 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1300 // We want to change this
1301 buf: wrap(self.buf),
1303 // And preserve these
1308 precision: self.precision,
1312 // Helper methods used for padding and processing formatting arguments that
1313 // all formatting traits can use.
1315 /// Performs the correct padding for an integer which has already been
1316 /// emitted into a str. The str should *not* contain the sign for the
1317 /// integer, that will be added by this method.
1321 /// * is_nonnegative - whether the original integer was either positive or zero.
1322 /// * prefix - if the '#' character (Alternate) is provided, this
1323 /// is the prefix to put in front of the number.
1324 /// * buf - the byte array that the number has been formatted into
1326 /// This function will correctly account for the flags provided as well as
1327 /// the minimum width. It will not take precision into account.
1334 /// struct Foo { nb: i32 }
1337 /// fn new(nb: i32) -> Foo {
1344 /// impl fmt::Display for Foo {
1345 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1346 /// // We need to remove "-" from the number output.
1347 /// let tmp = self.nb.abs().to_string();
1349 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1353 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1354 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1355 /// assert_eq!(&format!("{}", Foo::new(0)), "0");
1356 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1357 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1361 let mut width = buf.len();
1363 let mut sign = None;
1364 if !is_nonnegative {
1367 } else if self.sign_plus() {
1372 let prefix = if self.alternate() {
1373 width += prefix.chars().count();
1379 // Writes the sign if it exists, and then the prefix if it was requested
1381 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1382 if let Some(c) = sign {
1383 f.buf.write_char(c)?;
1385 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1388 // The `width` field is more of a `min-width` parameter at this point.
1390 // If there's no minimum length requirements then we can just
1393 write_prefix(self, sign, prefix)?;
1394 self.buf.write_str(buf)
1396 // Check if we're over the minimum width, if so then we can also
1397 // just write the bytes.
1398 Some(min) if width >= min => {
1399 write_prefix(self, sign, prefix)?;
1400 self.buf.write_str(buf)
1402 // The sign and prefix goes before the padding if the fill character
1404 Some(min) if self.sign_aware_zero_pad() => {
1405 let old_fill = crate::mem::replace(&mut self.fill, '0');
1406 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1407 write_prefix(self, sign, prefix)?;
1408 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1409 self.buf.write_str(buf)?;
1410 post_padding.write(self)?;
1411 self.fill = old_fill;
1412 self.align = old_align;
1415 // Otherwise, the sign and prefix goes after the padding
1417 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1418 write_prefix(self, sign, prefix)?;
1419 self.buf.write_str(buf)?;
1420 post_padding.write(self)
1425 /// This function takes a string slice and emits it to the internal buffer
1426 /// after applying the relevant formatting flags specified. The flags
1427 /// recognized for generic strings are:
1429 /// * width - the minimum width of what to emit
1430 /// * fill/align - what to emit and where to emit it if the string
1431 /// provided needs to be padded
1432 /// * precision - the maximum length to emit, the string is truncated if it
1433 /// is longer than this length
1435 /// Notably this function ignores the `flag` parameters.
1444 /// impl fmt::Display for Foo {
1445 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1446 /// formatter.pad("Foo")
1450 /// assert_eq!(&format!("{Foo:<4}"), "Foo ");
1451 /// assert_eq!(&format!("{Foo:0>4}"), "0Foo");
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 pub fn pad(&mut self, s: &str) -> Result {
1455 // Make sure there's a fast path up front
1456 if self.width.is_none() && self.precision.is_none() {
1457 return self.buf.write_str(s);
1459 // The `precision` field can be interpreted as a `max-width` for the
1460 // string being formatted.
1461 let s = if let Some(max) = self.precision {
1462 // If our string is longer that the precision, then we must have
1463 // truncation. However other flags like `fill`, `width` and `align`
1464 // must act as always.
1465 if let Some((i, _)) = s.char_indices().nth(max) {
1466 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1467 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1468 // `unsafe` and otherwise don't emit any panic-related code
1470 s.get(..i).unwrap_or(s)
1477 // The `width` field is more of a `min-width` parameter at this point.
1479 // If we're under the maximum length, and there's no minimum length
1480 // requirements, then we can just emit the string
1481 None => self.buf.write_str(s),
1483 let chars_count = s.chars().count();
1484 // If we're under the maximum width, check if we're over the minimum
1485 // width, if so it's as easy as just emitting the string.
1486 if chars_count >= width {
1487 self.buf.write_str(s)
1489 // If we're under both the maximum and the minimum width, then fill
1490 // up the minimum width with the specified string + some alignment.
1492 let align = rt::v1::Alignment::Left;
1493 let post_padding = self.padding(width - chars_count, align)?;
1494 self.buf.write_str(s)?;
1495 post_padding.write(self)
1501 /// Write the pre-padding and return the unwritten post-padding. Callers are
1502 /// responsible for ensuring post-padding is written after the thing that is
1504 pub(crate) fn padding(
1507 default: rt::v1::Alignment,
1508 ) -> result::Result<PostPadding, Error> {
1509 let align = match self.align {
1510 rt::v1::Alignment::Unknown => default,
1514 let (pre_pad, post_pad) = match align {
1515 rt::v1::Alignment::Left => (0, padding),
1516 rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1517 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1520 for _ in 0..pre_pad {
1521 self.buf.write_char(self.fill)?;
1524 Ok(PostPadding::new(self.fill, post_pad))
1527 /// Takes the formatted parts and applies the padding.
1528 /// Assumes that the caller already has rendered the parts with required precision,
1529 /// so that `self.precision` can be ignored.
1530 fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1531 if let Some(mut width) = self.width {
1532 // for the sign-aware zero padding, we render the sign first and
1533 // behave as if we had no sign from the beginning.
1534 let mut formatted = formatted.clone();
1535 let old_fill = self.fill;
1536 let old_align = self.align;
1537 let mut align = old_align;
1538 if self.sign_aware_zero_pad() {
1539 // a sign always goes first
1540 let sign = formatted.sign;
1541 self.buf.write_str(sign)?;
1543 // remove the sign from the formatted parts
1544 formatted.sign = "";
1545 width = width.saturating_sub(sign.len());
1546 align = rt::v1::Alignment::Right;
1548 self.align = rt::v1::Alignment::Right;
1551 // remaining parts go through the ordinary padding process.
1552 let len = formatted.len();
1553 let ret = if width <= len {
1555 self.write_formatted_parts(&formatted)
1557 let post_padding = self.padding(width - len, align)?;
1558 self.write_formatted_parts(&formatted)?;
1559 post_padding.write(self)
1561 self.fill = old_fill;
1562 self.align = old_align;
1565 // this is the common case and we take a shortcut
1566 self.write_formatted_parts(formatted)
1570 fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1571 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1572 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1573 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1574 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1575 // It's also probably safe in practice to use for `numfmt::Part::Copy(buf)`
1576 // since `buf` should be plain ASCII, but it's possible for someone to pass
1577 // in a bad value for `buf` into `numfmt::to_shortest_str` since it is a
1579 // FIXME: Determine whether this could result in UB.
1580 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1583 if !formatted.sign.is_empty() {
1584 self.buf.write_str(formatted.sign)?;
1586 for part in formatted.parts {
1588 numfmt::Part::Zero(mut nzeroes) => {
1589 const ZEROES: &str = // 64 zeroes
1590 "0000000000000000000000000000000000000000000000000000000000000000";
1591 while nzeroes > ZEROES.len() {
1592 self.buf.write_str(ZEROES)?;
1593 nzeroes -= ZEROES.len();
1596 self.buf.write_str(&ZEROES[..nzeroes])?;
1599 numfmt::Part::Num(mut v) => {
1601 let len = part.len();
1602 for c in s[..len].iter_mut().rev() {
1603 *c = b'0' + (v % 10) as u8;
1606 write_bytes(self.buf, &s[..len])?;
1608 numfmt::Part::Copy(buf) => {
1609 write_bytes(self.buf, buf)?;
1616 /// Writes some data to the underlying buffer contained within this
1626 /// impl fmt::Display for Foo {
1627 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1628 /// formatter.write_str("Foo")
1629 /// // This is equivalent to:
1630 /// // write!(formatter, "Foo")
1634 /// assert_eq!(&format!("{Foo}"), "Foo");
1635 /// assert_eq!(&format!("{Foo:0>8}"), "Foo");
1637 #[stable(feature = "rust1", since = "1.0.0")]
1638 pub fn write_str(&mut self, data: &str) -> Result {
1639 self.buf.write_str(data)
1642 /// Writes some formatted information into this instance.
1649 /// struct Foo(i32);
1651 /// impl fmt::Display for Foo {
1652 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1653 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1657 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1658 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1662 write(self.buf, fmt)
1665 /// Flags for formatting
1667 #[stable(feature = "rust1", since = "1.0.0")]
1670 note = "use the `sign_plus`, `sign_minus`, `alternate`, \
1671 or `sign_aware_zero_pad` methods instead"
1673 pub fn flags(&self) -> u32 {
1677 /// Character used as 'fill' whenever there is alignment.
1686 /// impl fmt::Display for Foo {
1687 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1688 /// let c = formatter.fill();
1689 /// if let Some(width) = formatter.width() {
1690 /// for _ in 0..width {
1691 /// write!(formatter, "{c}")?;
1695 /// write!(formatter, "{c}")
1700 /// // We set alignment to the right with ">".
1701 /// assert_eq!(&format!("{Foo:G>3}"), "GGG");
1702 /// assert_eq!(&format!("{Foo:t>6}"), "tttttt");
1705 #[stable(feature = "fmt_flags", since = "1.5.0")]
1706 pub fn fill(&self) -> char {
1710 /// Flag indicating what form of alignment was requested.
1715 /// extern crate core;
1717 /// use std::fmt::{self, Alignment};
1721 /// impl fmt::Display for Foo {
1722 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1723 /// let s = if let Some(s) = formatter.align() {
1725 /// Alignment::Left => "left",
1726 /// Alignment::Right => "right",
1727 /// Alignment::Center => "center",
1732 /// write!(formatter, "{s}")
1736 /// assert_eq!(&format!("{Foo:<}"), "left");
1737 /// assert_eq!(&format!("{Foo:>}"), "right");
1738 /// assert_eq!(&format!("{Foo:^}"), "center");
1739 /// assert_eq!(&format!("{Foo}"), "into the void");
1742 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1743 pub fn align(&self) -> Option<Alignment> {
1745 rt::v1::Alignment::Left => Some(Alignment::Left),
1746 rt::v1::Alignment::Right => Some(Alignment::Right),
1747 rt::v1::Alignment::Center => Some(Alignment::Center),
1748 rt::v1::Alignment::Unknown => None,
1752 /// Optionally specified integer width that the output should be.
1759 /// struct Foo(i32);
1761 /// impl fmt::Display for Foo {
1762 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1763 /// if let Some(width) = formatter.width() {
1764 /// // If we received a width, we use it
1765 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1767 /// // Otherwise we do nothing special
1768 /// write!(formatter, "Foo({})", self.0)
1773 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1774 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1777 #[stable(feature = "fmt_flags", since = "1.5.0")]
1778 pub fn width(&self) -> Option<usize> {
1782 /// Optionally specified precision for numeric types. Alternatively, the
1783 /// maximum width for string types.
1790 /// struct Foo(f32);
1792 /// impl fmt::Display for Foo {
1793 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1794 /// if let Some(precision) = formatter.precision() {
1795 /// // If we received a precision, we use it.
1796 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1798 /// // Otherwise we default to 2.
1799 /// write!(formatter, "Foo({:.2})", self.0)
1804 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1805 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1808 #[stable(feature = "fmt_flags", since = "1.5.0")]
1809 pub fn precision(&self) -> Option<usize> {
1813 /// Determines if the `+` flag was specified.
1820 /// struct Foo(i32);
1822 /// impl fmt::Display for Foo {
1823 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1824 /// if formatter.sign_plus() {
1825 /// write!(formatter,
1827 /// if self.0 < 0 { '-' } else { '+' },
1830 /// write!(formatter, "Foo({})", self.0)
1835 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1836 /// assert_eq!(&format!("{:+}", Foo(-23)), "Foo(-23)");
1837 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1840 #[stable(feature = "fmt_flags", since = "1.5.0")]
1841 pub fn sign_plus(&self) -> bool {
1842 self.flags & (1 << FlagV1::SignPlus as u32) != 0
1845 /// Determines if the `-` flag was specified.
1852 /// struct Foo(i32);
1854 /// impl fmt::Display for Foo {
1855 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1856 /// if formatter.sign_minus() {
1857 /// // You want a minus sign? Have one!
1858 /// write!(formatter, "-Foo({})", self.0)
1860 /// write!(formatter, "Foo({})", self.0)
1865 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1866 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1869 #[stable(feature = "fmt_flags", since = "1.5.0")]
1870 pub fn sign_minus(&self) -> bool {
1871 self.flags & (1 << FlagV1::SignMinus as u32) != 0
1874 /// Determines if the `#` flag was specified.
1881 /// struct Foo(i32);
1883 /// impl fmt::Display for Foo {
1884 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1885 /// if formatter.alternate() {
1886 /// write!(formatter, "Foo({})", self.0)
1888 /// write!(formatter, "{}", self.0)
1893 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1894 /// assert_eq!(&format!("{}", Foo(23)), "23");
1897 #[stable(feature = "fmt_flags", since = "1.5.0")]
1898 pub fn alternate(&self) -> bool {
1899 self.flags & (1 << FlagV1::Alternate as u32) != 0
1902 /// Determines if the `0` flag was specified.
1909 /// struct Foo(i32);
1911 /// impl fmt::Display for Foo {
1912 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1913 /// assert!(formatter.sign_aware_zero_pad());
1914 /// assert_eq!(formatter.width(), Some(4));
1915 /// // We ignore the formatter's options.
1916 /// write!(formatter, "{}", self.0)
1920 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1923 #[stable(feature = "fmt_flags", since = "1.5.0")]
1924 pub fn sign_aware_zero_pad(&self) -> bool {
1925 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1928 // FIXME: Decide what public API we want for these two flags.
1929 // https://github.com/rust-lang/rust/issues/48584
1930 fn debug_lower_hex(&self) -> bool {
1931 self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1934 fn debug_upper_hex(&self) -> bool {
1935 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1938 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1939 /// [`fmt::Debug`] implementations for structs.
1941 /// [`fmt::Debug`]: self::Debug
1947 /// use std::net::Ipv4Addr;
1955 /// impl fmt::Debug for Foo {
1956 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1957 /// fmt.debug_struct("Foo")
1958 /// .field("bar", &self.bar)
1959 /// .field("baz", &self.baz)
1960 /// .field("addr", &format_args!("{}", self.addr))
1966 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1967 /// format!("{:?}", Foo {
1969 /// baz: "Hello World".to_string(),
1970 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1974 #[stable(feature = "debug_builders", since = "1.2.0")]
1975 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1976 builders::debug_struct_new(self, name)
1979 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
1980 /// `debug_struct_fields_finish` is more general, but this is faster for 1 field.
1982 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
1983 pub fn debug_struct_field1_finish<'b>(
1989 let mut builder = builders::debug_struct_new(self, name);
1990 builder.field(name1, value1);
1994 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
1995 /// `debug_struct_fields_finish` is more general, but this is faster for 2 fields.
1997 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
1998 pub fn debug_struct_field2_finish<'b>(
2006 let mut builder = builders::debug_struct_new(self, name);
2007 builder.field(name1, value1);
2008 builder.field(name2, value2);
2012 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2013 /// `debug_struct_fields_finish` is more general, but this is faster for 3 fields.
2015 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2016 pub fn debug_struct_field3_finish<'b>(
2026 let mut builder = builders::debug_struct_new(self, name);
2027 builder.field(name1, value1);
2028 builder.field(name2, value2);
2029 builder.field(name3, value3);
2033 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2034 /// `debug_struct_fields_finish` is more general, but this is faster for 4 fields.
2036 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2037 pub fn debug_struct_field4_finish<'b>(
2049 let mut builder = builders::debug_struct_new(self, name);
2050 builder.field(name1, value1);
2051 builder.field(name2, value2);
2052 builder.field(name3, value3);
2053 builder.field(name4, value4);
2057 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2058 /// `debug_struct_fields_finish` is more general, but this is faster for 5 fields.
2060 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2061 pub fn debug_struct_field5_finish<'b>(
2075 let mut builder = builders::debug_struct_new(self, name);
2076 builder.field(name1, value1);
2077 builder.field(name2, value2);
2078 builder.field(name3, value3);
2079 builder.field(name4, value4);
2080 builder.field(name5, value5);
2084 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2085 /// For the cases not covered by `debug_struct_field[12345]_finish`.
2087 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2088 pub fn debug_struct_fields_finish<'b>(
2092 values: &[&dyn Debug],
2094 assert_eq!(names.len(), values.len());
2095 let mut builder = builders::debug_struct_new(self, name);
2096 for (name, value) in iter::zip(names, values) {
2097 builder.field(name, value);
2102 /// Creates a `DebugTuple` builder designed to assist with creation of
2103 /// `fmt::Debug` implementations for tuple structs.
2109 /// use std::marker::PhantomData;
2111 /// struct Foo<T>(i32, String, PhantomData<T>);
2113 /// impl<T> fmt::Debug for Foo<T> {
2114 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2115 /// fmt.debug_tuple("Foo")
2118 /// .field(&format_args!("_"))
2124 /// "Foo(10, \"Hello\", _)",
2125 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
2128 #[stable(feature = "debug_builders", since = "1.2.0")]
2129 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
2130 builders::debug_tuple_new(self, name)
2133 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2134 /// `debug_tuple_fields_finish` is more general, but this is faster for 1 field.
2136 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2137 pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result {
2138 let mut builder = builders::debug_tuple_new(self, name);
2139 builder.field(value1);
2143 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2144 /// `debug_tuple_fields_finish` is more general, but this is faster for 2 fields.
2146 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2147 pub fn debug_tuple_field2_finish<'b>(
2153 let mut builder = builders::debug_tuple_new(self, name);
2154 builder.field(value1);
2155 builder.field(value2);
2159 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2160 /// `debug_tuple_fields_finish` is more general, but this is faster for 3 fields.
2162 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2163 pub fn debug_tuple_field3_finish<'b>(
2170 let mut builder = builders::debug_tuple_new(self, name);
2171 builder.field(value1);
2172 builder.field(value2);
2173 builder.field(value3);
2177 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2178 /// `debug_tuple_fields_finish` is more general, but this is faster for 4 fields.
2180 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2181 pub fn debug_tuple_field4_finish<'b>(
2189 let mut builder = builders::debug_tuple_new(self, name);
2190 builder.field(value1);
2191 builder.field(value2);
2192 builder.field(value3);
2193 builder.field(value4);
2197 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2198 /// `debug_tuple_fields_finish` is more general, but this is faster for 5 fields.
2200 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2201 pub fn debug_tuple_field5_finish<'b>(
2210 let mut builder = builders::debug_tuple_new(self, name);
2211 builder.field(value1);
2212 builder.field(value2);
2213 builder.field(value3);
2214 builder.field(value4);
2215 builder.field(value5);
2219 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2220 /// For the cases not covered by `debug_tuple_field[12345]_finish`.
2222 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2223 pub fn debug_tuple_fields_finish<'b>(
2226 values: &[&dyn Debug],
2228 let mut builder = builders::debug_tuple_new(self, name);
2229 for value in values {
2230 builder.field(value);
2235 /// Creates a `DebugList` builder designed to assist with creation of
2236 /// `fmt::Debug` implementations for list-like structures.
2243 /// struct Foo(Vec<i32>);
2245 /// impl fmt::Debug for Foo {
2246 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2247 /// fmt.debug_list().entries(self.0.iter()).finish()
2251 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2253 #[stable(feature = "debug_builders", since = "1.2.0")]
2254 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2255 builders::debug_list_new(self)
2258 /// Creates a `DebugSet` builder designed to assist with creation of
2259 /// `fmt::Debug` implementations for set-like structures.
2266 /// struct Foo(Vec<i32>);
2268 /// impl fmt::Debug for Foo {
2269 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2270 /// fmt.debug_set().entries(self.0.iter()).finish()
2274 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2277 /// [`format_args!`]: crate::format_args
2279 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2280 /// to build a list of match arms:
2285 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
2286 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
2288 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2290 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
2292 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2293 /// L::fmt(&(self.0).0, fmt)?;
2294 /// fmt.write_str(" => ")?;
2295 /// R::fmt(&(self.0).1, fmt)
2299 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2301 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
2303 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2305 /// .entries(self.0.iter().map(Arm))
2306 /// .entry(&Arm(&(format_args!("_"), &self.1)))
2311 #[stable(feature = "debug_builders", since = "1.2.0")]
2312 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2313 builders::debug_set_new(self)
2316 /// Creates a `DebugMap` builder designed to assist with creation of
2317 /// `fmt::Debug` implementations for map-like structures.
2324 /// struct Foo(Vec<(String, i32)>);
2326 /// impl fmt::Debug for Foo {
2327 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2328 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2333 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2334 /// r#"{"A": 10, "B": 11}"#
2337 #[stable(feature = "debug_builders", since = "1.2.0")]
2338 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2339 builders::debug_map_new(self)
2343 #[stable(since = "1.2.0", feature = "formatter_write")]
2344 impl Write for Formatter<'_> {
2345 fn write_str(&mut self, s: &str) -> Result {
2346 self.buf.write_str(s)
2349 fn write_char(&mut self, c: char) -> Result {
2350 self.buf.write_char(c)
2353 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2354 write(self.buf, args)
2358 #[stable(feature = "rust1", since = "1.0.0")]
2359 impl Display for Error {
2360 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2361 Display::fmt("an error occurred when formatting an argument", f)
2365 // Implementations of the core formatting traits
2367 macro_rules! fmt_refs {
2368 ($($tr:ident),*) => {
2370 #[stable(feature = "rust1", since = "1.0.0")]
2371 impl<T: ?Sized + $tr> $tr for &T {
2372 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2374 #[stable(feature = "rust1", since = "1.0.0")]
2375 impl<T: ?Sized + $tr> $tr for &mut T {
2376 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2382 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2384 #[unstable(feature = "never_type", issue = "35121")]
2386 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2391 #[unstable(feature = "never_type", issue = "35121")]
2392 impl Display for ! {
2393 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2398 #[stable(feature = "rust1", since = "1.0.0")]
2399 impl Debug for bool {
2401 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2402 Display::fmt(self, f)
2406 #[stable(feature = "rust1", since = "1.0.0")]
2407 impl Display for bool {
2408 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2409 Display::fmt(if *self { "true" } else { "false" }, f)
2413 #[stable(feature = "rust1", since = "1.0.0")]
2414 impl Debug for str {
2415 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2418 for (i, c) in self.char_indices() {
2419 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2420 escape_grapheme_extended: true,
2421 escape_single_quote: false,
2422 escape_double_quote: true,
2424 // If char needs escaping, flush backlog so far and write, else skip
2426 f.write_str(&self[from..i])?;
2430 from = i + c.len_utf8();
2433 f.write_str(&self[from..])?;
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 impl Display for str {
2440 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2445 #[stable(feature = "rust1", since = "1.0.0")]
2446 impl Debug for char {
2447 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2448 f.write_char('\'')?;
2449 for c in self.escape_debug_ext(EscapeDebugExtArgs {
2450 escape_grapheme_extended: true,
2451 escape_single_quote: true,
2452 escape_double_quote: false,
2460 #[stable(feature = "rust1", since = "1.0.0")]
2461 impl Display for char {
2462 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2463 if f.width.is_none() && f.precision.is_none() {
2466 f.pad(self.encode_utf8(&mut [0; 4]))
2471 #[stable(feature = "rust1", since = "1.0.0")]
2472 impl<T: ?Sized> Pointer for *const T {
2473 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2474 // Cast is needed here because `.expose_addr()` requires `T: Sized`.
2475 pointer_fmt_inner((*self as *const ()).expose_addr(), f)
2479 /// Since the formatting will be identical for all pointer types, use a non-monomorphized
2480 /// implementation for the actual formatting to reduce the amount of codegen work needed.
2482 /// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
2483 /// `fn(...) -> ...` without using [problematic] "Oxford Casts".
2485 /// [problematic]: https://github.com/rust-lang/rust/issues/95489
2486 pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
2487 let old_width = f.width;
2488 let old_flags = f.flags;
2490 // The alternate flag is already treated by LowerHex as being special-
2491 // it denotes whether to prefix with 0x. We use it to work out whether
2492 // or not to zero extend, and then unconditionally set it to get the
2495 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2497 if f.width.is_none() {
2498 f.width = Some((usize::BITS / 4) as usize + 2);
2501 f.flags |= 1 << (FlagV1::Alternate as u32);
2503 let ret = LowerHex::fmt(&ptr_addr, f);
2505 f.width = old_width;
2506 f.flags = old_flags;
2511 #[stable(feature = "rust1", since = "1.0.0")]
2512 impl<T: ?Sized> Pointer for *mut T {
2513 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2514 Pointer::fmt(&(*self as *const T), f)
2518 #[stable(feature = "rust1", since = "1.0.0")]
2519 impl<T: ?Sized> Pointer for &T {
2520 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2521 Pointer::fmt(&(*self as *const T), f)
2525 #[stable(feature = "rust1", since = "1.0.0")]
2526 impl<T: ?Sized> Pointer for &mut T {
2527 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2528 Pointer::fmt(&(&**self as *const T), f)
2532 // Implementation of Display/Debug for various core types
2534 #[stable(feature = "rust1", since = "1.0.0")]
2535 impl<T: ?Sized> Debug for *const T {
2536 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2537 Pointer::fmt(self, f)
2540 #[stable(feature = "rust1", since = "1.0.0")]
2541 impl<T: ?Sized> Debug for *mut T {
2542 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2543 Pointer::fmt(self, f)
2548 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2551 macro_rules! tuple {
2553 ( $($name:ident,)+ ) => (
2556 #[stable(feature = "rust1", since = "1.0.0")]
2557 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2558 #[allow(non_snake_case, unused_assignments)]
2559 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2560 let mut builder = f.debug_tuple("");
2561 let ($(ref $name,)+) = *self;
2563 builder.field(&$name);
2570 peel! { $($name,)+ }
2574 macro_rules! maybe_tuple_doc {
2575 ($a:ident @ #[$meta:meta] $item:item) => {
2576 #[doc(fake_variadic)]
2577 #[doc = "This trait is implemented for tuples up to twelve items long."]
2581 ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
2588 macro_rules! last_type {
2589 ($a:ident,) => { $a };
2590 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2593 tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
2595 #[stable(feature = "rust1", since = "1.0.0")]
2596 impl<T: Debug> Debug for [T] {
2597 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2598 f.debug_list().entries(self.iter()).finish()
2602 #[stable(feature = "rust1", since = "1.0.0")]
2605 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2609 #[stable(feature = "rust1", since = "1.0.0")]
2610 impl<T: ?Sized> Debug for PhantomData<T> {
2611 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2612 write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
2616 #[stable(feature = "rust1", since = "1.0.0")]
2617 impl<T: Copy + Debug> Debug for Cell<T> {
2618 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2619 f.debug_struct("Cell").field("value", &self.get()).finish()
2623 #[stable(feature = "rust1", since = "1.0.0")]
2624 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2625 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2626 match self.try_borrow() {
2627 Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2629 // The RefCell is mutably borrowed so we can't look at its value
2630 // here. Show a placeholder instead.
2631 struct BorrowedPlaceholder;
2633 impl Debug for BorrowedPlaceholder {
2634 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2635 f.write_str("<borrowed>")
2639 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2645 #[stable(feature = "rust1", since = "1.0.0")]
2646 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2647 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2648 Debug::fmt(&**self, f)
2652 #[stable(feature = "rust1", since = "1.0.0")]
2653 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2654 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2655 Debug::fmt(&*(self.deref()), f)
2659 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2660 impl<T: ?Sized> Debug for UnsafeCell<T> {
2661 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2662 f.debug_struct("UnsafeCell").finish_non_exhaustive()
2666 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2667 impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
2668 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2669 f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
2673 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2674 // it's a lot easier than creating all of the rt::Piece structures here.
2675 // There are also tests in the alloc crate, for those that need allocations.