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 at runtime.
494 /// This can be used to avoid allocations in some cases.
498 /// For `format_args!("just a literal")`, this function is guaranteed to
499 /// return `Some("just a literal")`.
501 /// For most cases with placeholders, this function will return `None`.
503 /// However, the compiler may perform optimizations that can cause this
504 /// function to return `Some(_)` even if the format string contains
505 /// placeholders. For example, `format_args!("Hello, {}!", "world")` may be
506 /// optimized to `format_args!("Hello, world!")`, such that `as_str()`
507 /// returns `Some("Hello, world!")`.
509 /// The behavior for anything but the trivial case (without placeholders)
510 /// is not guaranteed, and should not be relied upon for anything other
511 /// than optimization.
516 /// use std::fmt::Arguments;
518 /// fn write_str(_: &str) { /* ... */ }
520 /// fn write_fmt(args: &Arguments) {
521 /// if let Some(s) = args.as_str() {
524 /// write_str(&args.to_string());
530 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
531 /// assert_eq!(format_args!("").as_str(), Some(""));
532 /// assert_eq!(format_args!("{:?}", std::env::current_dir()).as_str(), None);
534 #[stable(feature = "fmt_as_str", since = "1.52.0")]
535 #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")]
538 pub const fn as_str(&self) -> Option<&'static str> {
539 match (self.pieces, self.args) {
540 ([], []) => Some(""),
541 ([s], []) => Some(s),
547 #[stable(feature = "rust1", since = "1.0.0")]
548 impl Debug for Arguments<'_> {
549 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
550 Display::fmt(self, fmt)
554 #[stable(feature = "rust1", since = "1.0.0")]
555 impl Display for Arguments<'_> {
556 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
557 write(fmt.buf, *self)
563 /// `Debug` should format the output in a programmer-facing, debugging context.
565 /// Generally speaking, you should just `derive` a `Debug` implementation.
567 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
569 /// For more information on formatters, see [the module-level documentation][module].
571 /// [module]: ../../std/fmt/index.html
573 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
574 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
575 /// comma-separated list of each field's name and `Debug` value, then `}`. For
576 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
577 /// `Debug` values of the fields, then `)`.
581 /// Derived `Debug` formats are not stable, and so may change with future Rust
582 /// versions. Additionally, `Debug` implementations of types provided by the
583 /// standard library (`std`, `core`, `alloc`, etc.) are not stable, and
584 /// may also change with future Rust versions.
588 /// Deriving an implementation:
597 /// let origin = Point { x: 0, y: 0 };
599 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
602 /// Manually implementing:
612 /// impl fmt::Debug for Point {
613 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 /// f.debug_struct("Point")
615 /// .field("x", &self.x)
616 /// .field("y", &self.y)
621 /// let origin = Point { x: 0, y: 0 };
623 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
626 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
627 /// implementations, such as [`debug_struct`].
629 /// [`debug_struct`]: Formatter::debug_struct
631 /// Types that do not wish to use the standard suite of debug representations
632 /// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
633 /// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
634 /// manually writing an arbitrary representation to the `Formatter`.
643 /// impl fmt::Debug for Point {
644 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
645 /// write!(f, "Point [{} {}]", self.x, self.y)
650 /// `Debug` implementations using either `derive` or the debug builder API
651 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
653 /// Pretty-printing with `#?`:
662 /// let origin = Point { x: 0, y: 0 };
664 /// assert_eq!(format!("The origin is: {origin:#?}"),
665 /// "The origin is: Point {
671 #[stable(feature = "rust1", since = "1.0.0")]
672 #[rustc_on_unimplemented(
675 label = "`{Self}` cannot be formatted using `{{:?}}`",
676 note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
678 message = "`{Self}` doesn't implement `{Debug}`",
679 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
681 #[doc(alias = "{:?}")]
682 #[rustc_diagnostic_item = "Debug"]
683 #[rustc_trivial_field_reads]
685 /// Formats the value using the given formatter.
692 /// struct Position {
697 /// impl fmt::Debug for Position {
698 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699 /// f.debug_tuple("")
700 /// .field(&self.longitude)
701 /// .field(&self.latitude)
706 /// let position = Position { longitude: 1.987, latitude: 2.983 };
707 /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
709 /// assert_eq!(format!("{position:#?}"), "(
714 #[stable(feature = "rust1", since = "1.0.0")]
715 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
718 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
719 pub(crate) mod macros {
720 /// Derive macro generating an impl of the trait `Debug`.
721 #[rustc_builtin_macro]
722 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
723 #[allow_internal_unstable(core_intrinsics, fmt_helpers_for_derive)]
724 pub macro Debug($item:item) {
725 /* compiler built-in */
728 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
730 pub use macros::Debug;
732 /// Format trait for an empty format, `{}`.
734 /// Implementing this trait for a type will automatically implement the
735 /// [`ToString`][tostring] trait for the type, allowing the usage
736 /// of the [`.to_string()`][tostring_function] method. Prefer implementing
737 /// the `Display` trait for a type, rather than [`ToString`][tostring].
739 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
740 /// output, and so cannot be derived.
742 /// For more information on formatters, see [the module-level documentation][module].
744 /// [module]: ../../std/fmt/index.html
745 /// [tostring]: ../../std/string/trait.ToString.html
746 /// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
750 /// Implementing `Display` on a type:
760 /// impl fmt::Display for Point {
761 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762 /// write!(f, "({}, {})", self.x, self.y)
766 /// let origin = Point { x: 0, y: 0 };
768 /// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
770 #[rustc_on_unimplemented(
772 any(_Self = "std::path::Path", _Self = "std::path::PathBuf"),
773 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
774 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
775 as they may contain non-Unicode data"
777 message = "`{Self}` doesn't implement `{Display}`",
778 label = "`{Self}` cannot be formatted with the default formatter",
779 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
782 #[rustc_diagnostic_item = "Display"]
783 #[stable(feature = "rust1", since = "1.0.0")]
785 /// Formats the value using the given formatter.
792 /// struct Position {
797 /// impl fmt::Display for Position {
798 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
799 /// write!(f, "({}, {})", self.longitude, self.latitude)
803 /// assert_eq!("(1.987, 2.983)",
804 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
806 #[stable(feature = "rust1", since = "1.0.0")]
807 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
812 /// The `Octal` trait should format its output as a number in base-8.
814 /// For primitive signed integers (`i8` to `i128`, and `isize`),
815 /// negative values are formatted as the two’s complement representation.
817 /// The alternate flag, `#`, adds a `0o` in front of the output.
819 /// For more information on formatters, see [the module-level documentation][module].
821 /// [module]: ../../std/fmt/index.html
825 /// Basic usage with `i32`:
828 /// let x = 42; // 42 is '52' in octal
830 /// assert_eq!(format!("{x:o}"), "52");
831 /// assert_eq!(format!("{x:#o}"), "0o52");
833 /// assert_eq!(format!("{:o}", -16), "37777777760");
836 /// Implementing `Octal` on a type:
841 /// struct Length(i32);
843 /// impl fmt::Octal for Length {
844 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845 /// let val = self.0;
847 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
851 /// let l = Length(9);
853 /// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
855 /// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
857 #[stable(feature = "rust1", since = "1.0.0")]
859 /// Formats the value using the given formatter.
860 #[stable(feature = "rust1", since = "1.0.0")]
861 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
866 /// The `Binary` trait should format its output as a number in binary.
868 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
869 /// negative values are formatted as the two’s complement representation.
871 /// The alternate flag, `#`, adds a `0b` in front of the output.
873 /// For more information on formatters, see [the module-level documentation][module].
875 /// [module]: ../../std/fmt/index.html
879 /// Basic usage with [`i32`]:
882 /// let x = 42; // 42 is '101010' in binary
884 /// assert_eq!(format!("{x:b}"), "101010");
885 /// assert_eq!(format!("{x:#b}"), "0b101010");
887 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
890 /// Implementing `Binary` on a type:
895 /// struct Length(i32);
897 /// impl fmt::Binary for Length {
898 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899 /// let val = self.0;
901 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
905 /// let l = Length(107);
907 /// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
910 /// format!("l as binary is: {l:#032b}"),
911 /// "l as binary is: 0b000000000000000000000001101011"
914 #[stable(feature = "rust1", since = "1.0.0")]
916 /// Formats the value using the given formatter.
917 #[stable(feature = "rust1", since = "1.0.0")]
918 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
923 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
926 /// For primitive signed integers (`i8` to `i128`, and `isize`),
927 /// negative values are formatted as the two’s complement representation.
929 /// The alternate flag, `#`, adds a `0x` in front of the output.
931 /// For more information on formatters, see [the module-level documentation][module].
933 /// [module]: ../../std/fmt/index.html
937 /// Basic usage with `i32`:
940 /// let x = 42; // 42 is '2a' in hex
942 /// assert_eq!(format!("{x:x}"), "2a");
943 /// assert_eq!(format!("{x:#x}"), "0x2a");
945 /// assert_eq!(format!("{:x}", -16), "fffffff0");
948 /// Implementing `LowerHex` on a type:
953 /// struct Length(i32);
955 /// impl fmt::LowerHex for Length {
956 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
957 /// let val = self.0;
959 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
963 /// let l = Length(9);
965 /// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
967 /// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
969 #[stable(feature = "rust1", since = "1.0.0")]
971 /// Formats the value using the given formatter.
972 #[stable(feature = "rust1", since = "1.0.0")]
973 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
978 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
981 /// For primitive signed integers (`i8` to `i128`, and `isize`),
982 /// negative values are formatted as the two’s complement representation.
984 /// The alternate flag, `#`, adds a `0x` in front of the output.
986 /// For more information on formatters, see [the module-level documentation][module].
988 /// [module]: ../../std/fmt/index.html
992 /// Basic usage with `i32`:
995 /// let x = 42; // 42 is '2A' in hex
997 /// assert_eq!(format!("{x:X}"), "2A");
998 /// assert_eq!(format!("{x:#X}"), "0x2A");
1000 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
1003 /// Implementing `UpperHex` on a type:
1008 /// struct Length(i32);
1010 /// impl fmt::UpperHex for Length {
1011 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012 /// let val = self.0;
1014 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
1018 /// let l = Length(i32::MAX);
1020 /// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
1022 /// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 pub trait UpperHex {
1026 /// Formats the value using the given formatter.
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1033 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
1036 /// For more information on formatters, see [the module-level documentation][module].
1038 /// [module]: ../../std/fmt/index.html
1042 /// Basic usage with `&i32`:
1047 /// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
1050 /// Implementing `Pointer` on a type:
1055 /// struct Length(i32);
1057 /// impl fmt::Pointer for Length {
1058 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1059 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1061 /// let ptr = self as *const Self;
1062 /// fmt::Pointer::fmt(&ptr, f)
1066 /// let l = Length(42);
1068 /// println!("l is in memory here: {l:p}");
1070 /// let l_ptr = format!("{l:018p}");
1071 /// assert_eq!(l_ptr.len(), 18);
1072 /// assert_eq!(&l_ptr[..2], "0x");
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 #[rustc_diagnostic_item = "Pointer"]
1077 /// Formats the value using the given formatter.
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1084 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1086 /// For more information on formatters, see [the module-level documentation][module].
1088 /// [module]: ../../std/fmt/index.html
1092 /// Basic usage with `f64`:
1095 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1097 /// assert_eq!(format!("{x:e}"), "4.2e1");
1100 /// Implementing `LowerExp` on a type:
1105 /// struct Length(i32);
1107 /// impl fmt::LowerExp for Length {
1108 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 /// let val = f64::from(self.0);
1110 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1114 /// let l = Length(100);
1117 /// format!("l in scientific notation is: {l:e}"),
1118 /// "l in scientific notation is: 1e2"
1122 /// format!("l in scientific notation is: {l:05e}"),
1123 /// "l in scientific notation is: 001e2"
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 pub trait LowerExp {
1128 /// Formats the value using the given formatter.
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1135 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1137 /// For more information on formatters, see [the module-level documentation][module].
1139 /// [module]: ../../std/fmt/index.html
1143 /// Basic usage with `f64`:
1146 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1148 /// assert_eq!(format!("{x:E}"), "4.2E1");
1151 /// Implementing `UpperExp` on a type:
1156 /// struct Length(i32);
1158 /// impl fmt::UpperExp for Length {
1159 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1160 /// let val = f64::from(self.0);
1161 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1165 /// let l = Length(100);
1168 /// format!("l in scientific notation is: {l:E}"),
1169 /// "l in scientific notation is: 1E2"
1173 /// format!("l in scientific notation is: {l:05E}"),
1174 /// "l in scientific notation is: 001E2"
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 pub trait UpperExp {
1179 /// Formats the value using the given formatter.
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1184 /// The `write` function takes an output stream, and an `Arguments` struct
1185 /// that can be precompiled with the `format_args!` macro.
1187 /// The arguments will be formatted according to the specified format string
1188 /// into the output stream provided.
1197 /// let mut output = String::new();
1198 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1199 /// .expect("Error occurred while trying to write in String");
1200 /// assert_eq!(output, "Hello world!");
1203 /// Please note that using [`write!`] might be preferable. Example:
1206 /// use std::fmt::Write;
1208 /// let mut output = String::new();
1209 /// write!(&mut output, "Hello {}!", "world")
1210 /// .expect("Error occurred while trying to write in String");
1211 /// assert_eq!(output, "Hello world!");
1214 /// [`write!`]: crate::write!
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1217 let mut formatter = Formatter::new(output);
1222 // We can use default formatting parameters for all arguments.
1223 for (i, arg) in args.args.iter().enumerate() {
1224 // SAFETY: args.args and args.pieces come from the same Arguments,
1225 // which guarantees the indexes are always within bounds.
1226 let piece = unsafe { args.pieces.get_unchecked(i) };
1227 if !piece.is_empty() {
1228 formatter.buf.write_str(*piece)?;
1230 (arg.formatter)(arg.value, &mut formatter)?;
1235 // Every spec has a corresponding argument that is preceded by
1237 for (i, arg) in fmt.iter().enumerate() {
1238 // SAFETY: fmt and args.pieces come from the same Arguments,
1239 // which guarantees the indexes are always within bounds.
1240 let piece = unsafe { args.pieces.get_unchecked(i) };
1241 if !piece.is_empty() {
1242 formatter.buf.write_str(*piece)?;
1244 // SAFETY: arg and args.args come from the same Arguments,
1245 // which guarantees the indexes are always within bounds.
1246 unsafe { run(&mut formatter, arg, args.args) }?;
1252 // There can be only one trailing string piece left.
1253 if let Some(piece) = args.pieces.get(idx) {
1254 formatter.buf.write_str(*piece)?;
1260 unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1261 fmt.fill = arg.format.fill;
1262 fmt.align = arg.format.align;
1263 fmt.flags = arg.format.flags;
1264 // SAFETY: arg and args come from the same Arguments,
1265 // which guarantees the indexes are always within bounds.
1267 fmt.width = getcount(args, &arg.format.width);
1268 fmt.precision = getcount(args, &arg.format.precision);
1271 // Extract the correct argument
1272 debug_assert!(arg.position < args.len());
1273 // SAFETY: arg and args come from the same Arguments,
1274 // which guarantees its index is always within bounds.
1275 let value = unsafe { args.get_unchecked(arg.position) };
1277 // Then actually do some printing
1278 (value.formatter)(value.value, fmt)
1281 unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1283 rt::v1::Count::Is(n) => Some(n),
1284 rt::v1::Count::Implied => None,
1285 rt::v1::Count::Param(i) => {
1286 debug_assert!(i < args.len());
1287 // SAFETY: cnt and args come from the same Arguments,
1288 // which guarantees this index is always within bounds.
1289 unsafe { args.get_unchecked(i).as_usize() }
1294 /// Padding after the end of something. Returned by `Formatter::padding`.
1295 #[must_use = "don't forget to write the post padding"]
1296 pub(crate) struct PostPadding {
1302 fn new(fill: char, padding: usize) -> PostPadding {
1303 PostPadding { fill, padding }
1306 /// Write this post padding.
1307 pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1308 for _ in 0..self.padding {
1309 f.buf.write_char(self.fill)?;
1315 impl<'a> Formatter<'a> {
1316 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1319 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1322 // We want to change this
1323 buf: wrap(self.buf),
1325 // And preserve these
1330 precision: self.precision,
1334 // Helper methods used for padding and processing formatting arguments that
1335 // all formatting traits can use.
1337 /// Performs the correct padding for an integer which has already been
1338 /// emitted into a str. The str should *not* contain the sign for the
1339 /// integer, that will be added by this method.
1343 /// * is_nonnegative - whether the original integer was either positive or zero.
1344 /// * prefix - if the '#' character (Alternate) is provided, this
1345 /// is the prefix to put in front of the number.
1346 /// * buf - the byte array that the number has been formatted into
1348 /// This function will correctly account for the flags provided as well as
1349 /// the minimum width. It will not take precision into account.
1356 /// struct Foo { nb: i32 }
1359 /// fn new(nb: i32) -> Foo {
1366 /// impl fmt::Display for Foo {
1367 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1368 /// // We need to remove "-" from the number output.
1369 /// let tmp = self.nb.abs().to_string();
1371 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1375 /// assert_eq!(format!("{}", Foo::new(2)), "2");
1376 /// assert_eq!(format!("{}", Foo::new(-1)), "-1");
1377 /// assert_eq!(format!("{}", Foo::new(0)), "0");
1378 /// assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
1379 /// assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1383 let mut width = buf.len();
1385 let mut sign = None;
1386 if !is_nonnegative {
1389 } else if self.sign_plus() {
1394 let prefix = if self.alternate() {
1395 width += prefix.chars().count();
1401 // Writes the sign if it exists, and then the prefix if it was requested
1403 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1404 if let Some(c) = sign {
1405 f.buf.write_char(c)?;
1407 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1410 // The `width` field is more of a `min-width` parameter at this point.
1412 // If there's no minimum length requirements then we can just
1415 write_prefix(self, sign, prefix)?;
1416 self.buf.write_str(buf)
1418 // Check if we're over the minimum width, if so then we can also
1419 // just write the bytes.
1420 Some(min) if width >= min => {
1421 write_prefix(self, sign, prefix)?;
1422 self.buf.write_str(buf)
1424 // The sign and prefix goes before the padding if the fill character
1426 Some(min) if self.sign_aware_zero_pad() => {
1427 let old_fill = crate::mem::replace(&mut self.fill, '0');
1428 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1429 write_prefix(self, sign, prefix)?;
1430 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1431 self.buf.write_str(buf)?;
1432 post_padding.write(self)?;
1433 self.fill = old_fill;
1434 self.align = old_align;
1437 // Otherwise, the sign and prefix goes after the padding
1439 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1440 write_prefix(self, sign, prefix)?;
1441 self.buf.write_str(buf)?;
1442 post_padding.write(self)
1447 /// This function takes a string slice and emits it to the internal buffer
1448 /// after applying the relevant formatting flags specified. The flags
1449 /// recognized for generic strings are:
1451 /// * width - the minimum width of what to emit
1452 /// * fill/align - what to emit and where to emit it if the string
1453 /// provided needs to be padded
1454 /// * precision - the maximum length to emit, the string is truncated if it
1455 /// is longer than this length
1457 /// Notably this function ignores the `flag` parameters.
1466 /// impl fmt::Display for Foo {
1467 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1468 /// formatter.pad("Foo")
1472 /// assert_eq!(format!("{Foo:<4}"), "Foo ");
1473 /// assert_eq!(format!("{Foo:0>4}"), "0Foo");
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 pub fn pad(&mut self, s: &str) -> Result {
1477 // Make sure there's a fast path up front
1478 if self.width.is_none() && self.precision.is_none() {
1479 return self.buf.write_str(s);
1481 // The `precision` field can be interpreted as a `max-width` for the
1482 // string being formatted.
1483 let s = if let Some(max) = self.precision {
1484 // If our string is longer that the precision, then we must have
1485 // truncation. However other flags like `fill`, `width` and `align`
1486 // must act as always.
1487 if let Some((i, _)) = s.char_indices().nth(max) {
1488 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1489 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1490 // `unsafe` and otherwise don't emit any panic-related code
1492 s.get(..i).unwrap_or(s)
1499 // The `width` field is more of a `min-width` parameter at this point.
1501 // If we're under the maximum length, and there's no minimum length
1502 // requirements, then we can just emit the string
1503 None => self.buf.write_str(s),
1505 let chars_count = s.chars().count();
1506 // If we're under the maximum width, check if we're over the minimum
1507 // width, if so it's as easy as just emitting the string.
1508 if chars_count >= width {
1509 self.buf.write_str(s)
1511 // If we're under both the maximum and the minimum width, then fill
1512 // up the minimum width with the specified string + some alignment.
1514 let align = rt::v1::Alignment::Left;
1515 let post_padding = self.padding(width - chars_count, align)?;
1516 self.buf.write_str(s)?;
1517 post_padding.write(self)
1523 /// Write the pre-padding and return the unwritten post-padding. Callers are
1524 /// responsible for ensuring post-padding is written after the thing that is
1526 pub(crate) fn padding(
1529 default: rt::v1::Alignment,
1530 ) -> result::Result<PostPadding, Error> {
1531 let align = match self.align {
1532 rt::v1::Alignment::Unknown => default,
1536 let (pre_pad, post_pad) = match align {
1537 rt::v1::Alignment::Left => (0, padding),
1538 rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1539 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1542 for _ in 0..pre_pad {
1543 self.buf.write_char(self.fill)?;
1546 Ok(PostPadding::new(self.fill, post_pad))
1549 /// Takes the formatted parts and applies the padding.
1550 /// Assumes that the caller already has rendered the parts with required precision,
1551 /// so that `self.precision` can be ignored.
1552 fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1553 if let Some(mut width) = self.width {
1554 // for the sign-aware zero padding, we render the sign first and
1555 // behave as if we had no sign from the beginning.
1556 let mut formatted = formatted.clone();
1557 let old_fill = self.fill;
1558 let old_align = self.align;
1559 let mut align = old_align;
1560 if self.sign_aware_zero_pad() {
1561 // a sign always goes first
1562 let sign = formatted.sign;
1563 self.buf.write_str(sign)?;
1565 // remove the sign from the formatted parts
1566 formatted.sign = "";
1567 width = width.saturating_sub(sign.len());
1568 align = rt::v1::Alignment::Right;
1570 self.align = rt::v1::Alignment::Right;
1573 // remaining parts go through the ordinary padding process.
1574 let len = formatted.len();
1575 let ret = if width <= len {
1577 self.write_formatted_parts(&formatted)
1579 let post_padding = self.padding(width - len, align)?;
1580 self.write_formatted_parts(&formatted)?;
1581 post_padding.write(self)
1583 self.fill = old_fill;
1584 self.align = old_align;
1587 // this is the common case and we take a shortcut
1588 self.write_formatted_parts(formatted)
1592 fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1593 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1594 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1595 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1596 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1597 // It's also probably safe in practice to use for `numfmt::Part::Copy(buf)`
1598 // since `buf` should be plain ASCII, but it's possible for someone to pass
1599 // in a bad value for `buf` into `numfmt::to_shortest_str` since it is a
1601 // FIXME: Determine whether this could result in UB.
1602 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1605 if !formatted.sign.is_empty() {
1606 self.buf.write_str(formatted.sign)?;
1608 for part in formatted.parts {
1610 numfmt::Part::Zero(mut nzeroes) => {
1611 const ZEROES: &str = // 64 zeroes
1612 "0000000000000000000000000000000000000000000000000000000000000000";
1613 while nzeroes > ZEROES.len() {
1614 self.buf.write_str(ZEROES)?;
1615 nzeroes -= ZEROES.len();
1618 self.buf.write_str(&ZEROES[..nzeroes])?;
1621 numfmt::Part::Num(mut v) => {
1623 let len = part.len();
1624 for c in s[..len].iter_mut().rev() {
1625 *c = b'0' + (v % 10) as u8;
1628 write_bytes(self.buf, &s[..len])?;
1630 numfmt::Part::Copy(buf) => {
1631 write_bytes(self.buf, buf)?;
1638 /// Writes some data to the underlying buffer contained within this
1648 /// impl fmt::Display for Foo {
1649 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1650 /// formatter.write_str("Foo")
1651 /// // This is equivalent to:
1652 /// // write!(formatter, "Foo")
1656 /// assert_eq!(format!("{Foo}"), "Foo");
1657 /// assert_eq!(format!("{Foo:0>8}"), "Foo");
1659 #[stable(feature = "rust1", since = "1.0.0")]
1660 pub fn write_str(&mut self, data: &str) -> Result {
1661 self.buf.write_str(data)
1664 /// Writes some formatted information into this instance.
1671 /// struct Foo(i32);
1673 /// impl fmt::Display for Foo {
1674 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1675 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1679 /// assert_eq!(format!("{}", Foo(-1)), "Foo -1");
1680 /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1684 write(self.buf, fmt)
1687 /// Flags for formatting
1689 #[stable(feature = "rust1", since = "1.0.0")]
1692 note = "use the `sign_plus`, `sign_minus`, `alternate`, \
1693 or `sign_aware_zero_pad` methods instead"
1695 pub fn flags(&self) -> u32 {
1699 /// Character used as 'fill' whenever there is alignment.
1708 /// impl fmt::Display for Foo {
1709 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1710 /// let c = formatter.fill();
1711 /// if let Some(width) = formatter.width() {
1712 /// for _ in 0..width {
1713 /// write!(formatter, "{c}")?;
1717 /// write!(formatter, "{c}")
1722 /// // We set alignment to the right with ">".
1723 /// assert_eq!(format!("{Foo:G>3}"), "GGG");
1724 /// assert_eq!(format!("{Foo:t>6}"), "tttttt");
1727 #[stable(feature = "fmt_flags", since = "1.5.0")]
1728 pub fn fill(&self) -> char {
1732 /// Flag indicating what form of alignment was requested.
1737 /// extern crate core;
1739 /// use std::fmt::{self, Alignment};
1743 /// impl fmt::Display for Foo {
1744 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1745 /// let s = if let Some(s) = formatter.align() {
1747 /// Alignment::Left => "left",
1748 /// Alignment::Right => "right",
1749 /// Alignment::Center => "center",
1754 /// write!(formatter, "{s}")
1758 /// assert_eq!(format!("{Foo:<}"), "left");
1759 /// assert_eq!(format!("{Foo:>}"), "right");
1760 /// assert_eq!(format!("{Foo:^}"), "center");
1761 /// assert_eq!(format!("{Foo}"), "into the void");
1764 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1765 pub fn align(&self) -> Option<Alignment> {
1767 rt::v1::Alignment::Left => Some(Alignment::Left),
1768 rt::v1::Alignment::Right => Some(Alignment::Right),
1769 rt::v1::Alignment::Center => Some(Alignment::Center),
1770 rt::v1::Alignment::Unknown => None,
1774 /// Optionally specified integer width that the output should be.
1781 /// struct Foo(i32);
1783 /// impl fmt::Display for Foo {
1784 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1785 /// if let Some(width) = formatter.width() {
1786 /// // If we received a width, we use it
1787 /// write!(formatter, "{:width$}", format!("Foo({})", self.0), width = width)
1789 /// // Otherwise we do nothing special
1790 /// write!(formatter, "Foo({})", self.0)
1795 /// assert_eq!(format!("{:10}", Foo(23)), "Foo(23) ");
1796 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
1799 #[stable(feature = "fmt_flags", since = "1.5.0")]
1800 pub fn width(&self) -> Option<usize> {
1804 /// Optionally specified precision for numeric types. Alternatively, the
1805 /// maximum width for string types.
1812 /// struct Foo(f32);
1814 /// impl fmt::Display for Foo {
1815 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1816 /// if let Some(precision) = formatter.precision() {
1817 /// // If we received a precision, we use it.
1818 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1820 /// // Otherwise we default to 2.
1821 /// write!(formatter, "Foo({:.2})", self.0)
1826 /// assert_eq!(format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1827 /// assert_eq!(format!("{}", Foo(23.2)), "Foo(23.20)");
1830 #[stable(feature = "fmt_flags", since = "1.5.0")]
1831 pub fn precision(&self) -> Option<usize> {
1835 /// Determines if the `+` flag was specified.
1842 /// struct Foo(i32);
1844 /// impl fmt::Display for Foo {
1845 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1846 /// if formatter.sign_plus() {
1847 /// write!(formatter,
1849 /// if self.0 < 0 { '-' } else { '+' },
1852 /// write!(formatter, "Foo({})", self.0)
1857 /// assert_eq!(format!("{:+}", Foo(23)), "Foo(+23)");
1858 /// assert_eq!(format!("{:+}", Foo(-23)), "Foo(-23)");
1859 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
1862 #[stable(feature = "fmt_flags", since = "1.5.0")]
1863 pub fn sign_plus(&self) -> bool {
1864 self.flags & (1 << FlagV1::SignPlus as u32) != 0
1867 /// Determines if the `-` flag was specified.
1874 /// struct Foo(i32);
1876 /// impl fmt::Display for Foo {
1877 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1878 /// if formatter.sign_minus() {
1879 /// // You want a minus sign? Have one!
1880 /// write!(formatter, "-Foo({})", self.0)
1882 /// write!(formatter, "Foo({})", self.0)
1887 /// assert_eq!(format!("{:-}", Foo(23)), "-Foo(23)");
1888 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
1891 #[stable(feature = "fmt_flags", since = "1.5.0")]
1892 pub fn sign_minus(&self) -> bool {
1893 self.flags & (1 << FlagV1::SignMinus as u32) != 0
1896 /// Determines if the `#` flag was specified.
1903 /// struct Foo(i32);
1905 /// impl fmt::Display for Foo {
1906 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1907 /// if formatter.alternate() {
1908 /// write!(formatter, "Foo({})", self.0)
1910 /// write!(formatter, "{}", self.0)
1915 /// assert_eq!(format!("{:#}", Foo(23)), "Foo(23)");
1916 /// assert_eq!(format!("{}", Foo(23)), "23");
1919 #[stable(feature = "fmt_flags", since = "1.5.0")]
1920 pub fn alternate(&self) -> bool {
1921 self.flags & (1 << FlagV1::Alternate as u32) != 0
1924 /// Determines if the `0` flag was specified.
1931 /// struct Foo(i32);
1933 /// impl fmt::Display for Foo {
1934 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1935 /// assert!(formatter.sign_aware_zero_pad());
1936 /// assert_eq!(formatter.width(), Some(4));
1937 /// // We ignore the formatter's options.
1938 /// write!(formatter, "{}", self.0)
1942 /// assert_eq!(format!("{:04}", Foo(23)), "23");
1945 #[stable(feature = "fmt_flags", since = "1.5.0")]
1946 pub fn sign_aware_zero_pad(&self) -> bool {
1947 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1950 // FIXME: Decide what public API we want for these two flags.
1951 // https://github.com/rust-lang/rust/issues/48584
1952 fn debug_lower_hex(&self) -> bool {
1953 self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1956 fn debug_upper_hex(&self) -> bool {
1957 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1960 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1961 /// [`fmt::Debug`] implementations for structs.
1963 /// [`fmt::Debug`]: self::Debug
1969 /// use std::net::Ipv4Addr;
1977 /// impl fmt::Debug for Foo {
1978 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1979 /// fmt.debug_struct("Foo")
1980 /// .field("bar", &self.bar)
1981 /// .field("baz", &self.baz)
1982 /// .field("addr", &format_args!("{}", self.addr))
1988 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1989 /// format!("{:?}", Foo {
1991 /// baz: "Hello World".to_string(),
1992 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1996 #[stable(feature = "debug_builders", since = "1.2.0")]
1997 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1998 builders::debug_struct_new(self, name)
2001 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2002 /// `debug_struct_fields_finish` is more general, but this is faster for 1 field.
2004 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2005 pub fn debug_struct_field1_finish<'b>(
2011 let mut builder = builders::debug_struct_new(self, name);
2012 builder.field(name1, value1);
2016 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2017 /// `debug_struct_fields_finish` is more general, but this is faster for 2 fields.
2019 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2020 pub fn debug_struct_field2_finish<'b>(
2028 let mut builder = builders::debug_struct_new(self, name);
2029 builder.field(name1, value1);
2030 builder.field(name2, value2);
2034 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2035 /// `debug_struct_fields_finish` is more general, but this is faster for 3 fields.
2037 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2038 pub fn debug_struct_field3_finish<'b>(
2048 let mut builder = builders::debug_struct_new(self, name);
2049 builder.field(name1, value1);
2050 builder.field(name2, value2);
2051 builder.field(name3, value3);
2055 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2056 /// `debug_struct_fields_finish` is more general, but this is faster for 4 fields.
2058 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2059 pub fn debug_struct_field4_finish<'b>(
2071 let mut builder = builders::debug_struct_new(self, name);
2072 builder.field(name1, value1);
2073 builder.field(name2, value2);
2074 builder.field(name3, value3);
2075 builder.field(name4, value4);
2079 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2080 /// `debug_struct_fields_finish` is more general, but this is faster for 5 fields.
2082 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2083 pub fn debug_struct_field5_finish<'b>(
2097 let mut builder = builders::debug_struct_new(self, name);
2098 builder.field(name1, value1);
2099 builder.field(name2, value2);
2100 builder.field(name3, value3);
2101 builder.field(name4, value4);
2102 builder.field(name5, value5);
2106 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2107 /// For the cases not covered by `debug_struct_field[12345]_finish`.
2109 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2110 pub fn debug_struct_fields_finish<'b>(
2114 values: &[&dyn Debug],
2116 assert_eq!(names.len(), values.len());
2117 let mut builder = builders::debug_struct_new(self, name);
2118 for (name, value) in iter::zip(names, values) {
2119 builder.field(name, value);
2124 /// Creates a `DebugTuple` builder designed to assist with creation of
2125 /// `fmt::Debug` implementations for tuple structs.
2131 /// use std::marker::PhantomData;
2133 /// struct Foo<T>(i32, String, PhantomData<T>);
2135 /// impl<T> fmt::Debug for Foo<T> {
2136 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2137 /// fmt.debug_tuple("Foo")
2140 /// .field(&format_args!("_"))
2146 /// "Foo(10, \"Hello\", _)",
2147 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
2150 #[stable(feature = "debug_builders", since = "1.2.0")]
2151 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
2152 builders::debug_tuple_new(self, name)
2155 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2156 /// `debug_tuple_fields_finish` is more general, but this is faster for 1 field.
2158 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2159 pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result {
2160 let mut builder = builders::debug_tuple_new(self, name);
2161 builder.field(value1);
2165 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2166 /// `debug_tuple_fields_finish` is more general, but this is faster for 2 fields.
2168 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2169 pub fn debug_tuple_field2_finish<'b>(
2175 let mut builder = builders::debug_tuple_new(self, name);
2176 builder.field(value1);
2177 builder.field(value2);
2181 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2182 /// `debug_tuple_fields_finish` is more general, but this is faster for 3 fields.
2184 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2185 pub fn debug_tuple_field3_finish<'b>(
2192 let mut builder = builders::debug_tuple_new(self, name);
2193 builder.field(value1);
2194 builder.field(value2);
2195 builder.field(value3);
2199 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2200 /// `debug_tuple_fields_finish` is more general, but this is faster for 4 fields.
2202 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2203 pub fn debug_tuple_field4_finish<'b>(
2211 let mut builder = builders::debug_tuple_new(self, name);
2212 builder.field(value1);
2213 builder.field(value2);
2214 builder.field(value3);
2215 builder.field(value4);
2219 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2220 /// `debug_tuple_fields_finish` is more general, but this is faster for 5 fields.
2222 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2223 pub fn debug_tuple_field5_finish<'b>(
2232 let mut builder = builders::debug_tuple_new(self, name);
2233 builder.field(value1);
2234 builder.field(value2);
2235 builder.field(value3);
2236 builder.field(value4);
2237 builder.field(value5);
2241 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2242 /// For the cases not covered by `debug_tuple_field[12345]_finish`.
2244 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2245 pub fn debug_tuple_fields_finish<'b>(
2248 values: &[&dyn Debug],
2250 let mut builder = builders::debug_tuple_new(self, name);
2251 for value in values {
2252 builder.field(value);
2257 /// Creates a `DebugList` builder designed to assist with creation of
2258 /// `fmt::Debug` implementations for list-like structures.
2265 /// struct Foo(Vec<i32>);
2267 /// impl fmt::Debug for Foo {
2268 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2269 /// fmt.debug_list().entries(self.0.iter()).finish()
2273 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2275 #[stable(feature = "debug_builders", since = "1.2.0")]
2276 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2277 builders::debug_list_new(self)
2280 /// Creates a `DebugSet` builder designed to assist with creation of
2281 /// `fmt::Debug` implementations for set-like structures.
2288 /// struct Foo(Vec<i32>);
2290 /// impl fmt::Debug for Foo {
2291 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2292 /// fmt.debug_set().entries(self.0.iter()).finish()
2296 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2299 /// [`format_args!`]: crate::format_args
2301 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2302 /// to build a list of match arms:
2307 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
2308 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
2310 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2312 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
2314 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2315 /// L::fmt(&(self.0).0, fmt)?;
2316 /// fmt.write_str(" => ")?;
2317 /// R::fmt(&(self.0).1, fmt)
2321 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2323 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
2325 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2327 /// .entries(self.0.iter().map(Arm))
2328 /// .entry(&Arm(&(format_args!("_"), &self.1)))
2333 #[stable(feature = "debug_builders", since = "1.2.0")]
2334 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2335 builders::debug_set_new(self)
2338 /// Creates a `DebugMap` builder designed to assist with creation of
2339 /// `fmt::Debug` implementations for map-like structures.
2346 /// struct Foo(Vec<(String, i32)>);
2348 /// impl fmt::Debug for Foo {
2349 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2350 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2355 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2356 /// r#"{"A": 10, "B": 11}"#
2359 #[stable(feature = "debug_builders", since = "1.2.0")]
2360 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2361 builders::debug_map_new(self)
2365 #[stable(since = "1.2.0", feature = "formatter_write")]
2366 impl Write for Formatter<'_> {
2367 fn write_str(&mut self, s: &str) -> Result {
2368 self.buf.write_str(s)
2371 fn write_char(&mut self, c: char) -> Result {
2372 self.buf.write_char(c)
2375 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2376 write(self.buf, args)
2380 #[stable(feature = "rust1", since = "1.0.0")]
2381 impl Display for Error {
2382 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2383 Display::fmt("an error occurred when formatting an argument", f)
2387 // Implementations of the core formatting traits
2389 macro_rules! fmt_refs {
2390 ($($tr:ident),*) => {
2392 #[stable(feature = "rust1", since = "1.0.0")]
2393 impl<T: ?Sized + $tr> $tr for &T {
2394 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2396 #[stable(feature = "rust1", since = "1.0.0")]
2397 impl<T: ?Sized + $tr> $tr for &mut T {
2398 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2404 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2406 #[unstable(feature = "never_type", issue = "35121")]
2408 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2413 #[unstable(feature = "never_type", issue = "35121")]
2414 impl Display for ! {
2415 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2420 #[stable(feature = "rust1", since = "1.0.0")]
2421 impl Debug for bool {
2423 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2424 Display::fmt(self, f)
2428 #[stable(feature = "rust1", since = "1.0.0")]
2429 impl Display for bool {
2430 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2431 Display::fmt(if *self { "true" } else { "false" }, f)
2435 #[stable(feature = "rust1", since = "1.0.0")]
2436 impl Debug for str {
2437 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2440 for (i, c) in self.char_indices() {
2441 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2442 escape_grapheme_extended: true,
2443 escape_single_quote: false,
2444 escape_double_quote: true,
2446 // If char needs escaping, flush backlog so far and write, else skip
2448 f.write_str(&self[from..i])?;
2452 from = i + c.len_utf8();
2455 f.write_str(&self[from..])?;
2460 #[stable(feature = "rust1", since = "1.0.0")]
2461 impl Display for str {
2462 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2467 #[stable(feature = "rust1", since = "1.0.0")]
2468 impl Debug for char {
2469 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2470 f.write_char('\'')?;
2471 for c in self.escape_debug_ext(EscapeDebugExtArgs {
2472 escape_grapheme_extended: true,
2473 escape_single_quote: true,
2474 escape_double_quote: false,
2482 #[stable(feature = "rust1", since = "1.0.0")]
2483 impl Display for char {
2484 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2485 if f.width.is_none() && f.precision.is_none() {
2488 f.pad(self.encode_utf8(&mut [0; 4]))
2493 #[stable(feature = "rust1", since = "1.0.0")]
2494 impl<T: ?Sized> Pointer for *const T {
2495 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2496 // Cast is needed here because `.expose_addr()` requires `T: Sized`.
2497 pointer_fmt_inner((*self as *const ()).expose_addr(), f)
2501 /// Since the formatting will be identical for all pointer types, use a non-monomorphized
2502 /// implementation for the actual formatting to reduce the amount of codegen work needed.
2504 /// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
2505 /// `fn(...) -> ...` without using [problematic] "Oxford Casts".
2507 /// [problematic]: https://github.com/rust-lang/rust/issues/95489
2508 pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
2509 let old_width = f.width;
2510 let old_flags = f.flags;
2512 // The alternate flag is already treated by LowerHex as being special-
2513 // it denotes whether to prefix with 0x. We use it to work out whether
2514 // or not to zero extend, and then unconditionally set it to get the
2517 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2519 if f.width.is_none() {
2520 f.width = Some((usize::BITS / 4) as usize + 2);
2523 f.flags |= 1 << (FlagV1::Alternate as u32);
2525 let ret = LowerHex::fmt(&ptr_addr, f);
2527 f.width = old_width;
2528 f.flags = old_flags;
2533 #[stable(feature = "rust1", since = "1.0.0")]
2534 impl<T: ?Sized> Pointer for *mut T {
2535 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2536 Pointer::fmt(&(*self as *const T), f)
2540 #[stable(feature = "rust1", since = "1.0.0")]
2541 impl<T: ?Sized> Pointer for &T {
2542 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2543 Pointer::fmt(&(*self as *const T), f)
2547 #[stable(feature = "rust1", since = "1.0.0")]
2548 impl<T: ?Sized> Pointer for &mut T {
2549 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2550 Pointer::fmt(&(&**self as *const T), f)
2554 // Implementation of Display/Debug for various core types
2556 #[stable(feature = "rust1", since = "1.0.0")]
2557 impl<T: ?Sized> Debug for *const T {
2558 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2559 Pointer::fmt(self, f)
2562 #[stable(feature = "rust1", since = "1.0.0")]
2563 impl<T: ?Sized> Debug for *mut T {
2564 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2565 Pointer::fmt(self, f)
2570 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2573 macro_rules! tuple {
2575 ( $($name:ident,)+ ) => (
2578 #[stable(feature = "rust1", since = "1.0.0")]
2579 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2580 #[allow(non_snake_case, unused_assignments)]
2581 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2582 let mut builder = f.debug_tuple("");
2583 let ($(ref $name,)+) = *self;
2585 builder.field(&$name);
2592 peel! { $($name,)+ }
2596 macro_rules! maybe_tuple_doc {
2597 ($a:ident @ #[$meta:meta] $item:item) => {
2598 #[doc(fake_variadic)]
2599 #[doc = "This trait is implemented for tuples up to twelve items long."]
2603 ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
2610 macro_rules! last_type {
2611 ($a:ident,) => { $a };
2612 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2615 tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
2617 #[stable(feature = "rust1", since = "1.0.0")]
2618 impl<T: Debug> Debug for [T] {
2619 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2620 f.debug_list().entries(self.iter()).finish()
2624 #[stable(feature = "rust1", since = "1.0.0")]
2627 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2631 #[stable(feature = "rust1", since = "1.0.0")]
2632 impl<T: ?Sized> Debug for PhantomData<T> {
2633 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2634 write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
2638 #[stable(feature = "rust1", since = "1.0.0")]
2639 impl<T: Copy + Debug> Debug for Cell<T> {
2640 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2641 f.debug_struct("Cell").field("value", &self.get()).finish()
2645 #[stable(feature = "rust1", since = "1.0.0")]
2646 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2647 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2648 match self.try_borrow() {
2649 Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2651 // The RefCell is mutably borrowed so we can't look at its value
2652 // here. Show a placeholder instead.
2653 struct BorrowedPlaceholder;
2655 impl Debug for BorrowedPlaceholder {
2656 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2657 f.write_str("<borrowed>")
2661 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2667 #[stable(feature = "rust1", since = "1.0.0")]
2668 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2669 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2670 Debug::fmt(&**self, f)
2674 #[stable(feature = "rust1", since = "1.0.0")]
2675 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2676 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2677 Debug::fmt(&*(self.deref()), f)
2681 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2682 impl<T: ?Sized> Debug for UnsafeCell<T> {
2683 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2684 f.debug_struct("UnsafeCell").finish_non_exhaustive()
2688 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2689 impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
2690 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2691 f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
2695 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2696 // it's a lot easier than creating all of the rt::Piece structures here.
2697 // There are also tests in the alloc crate, for those that need allocations.