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;
7 use crate::marker::PhantomData;
9 use crate::num::fmt as numfmt;
10 use crate::ops::Deref;
15 #[cfg(not(no_fp_fmt_parse))]
17 #[cfg(no_fp_fmt_parse)]
21 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
22 #[cfg_attr(not(test), rustc_diagnostic_item = "Alignment")]
23 /// Possible alignments returned by `Formatter::align`
24 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
26 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
27 /// Indication that contents should be left-aligned.
29 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
30 /// Indication that contents should be right-aligned.
32 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
33 /// Indication that contents should be center-aligned.
37 #[stable(feature = "debug_builders", since = "1.2.0")]
38 pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
40 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
46 /// The type returned by formatter methods.
60 /// impl fmt::Display for Triangle {
61 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
66 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
68 /// assert_eq!(format!("{pythagorean_triple}"), "(3, 4, 5)");
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub type Result = result::Result<(), Error>;
73 /// The error type which is returned from formatting a message into a stream.
75 /// This type does not support transmission of an error other than that an error
76 /// occurred. Any extra information must be arranged to be transmitted through
79 /// An important thing to remember is that the type `fmt::Error` should not be
80 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
83 /// [`std::io::Error`]: ../../std/io/struct.Error.html
84 /// [`std::error::Error`]: ../../std/error/trait.Error.html
89 /// use std::fmt::{self, write};
91 /// let mut output = String::new();
92 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
93 /// panic!("An error occurred");
96 #[stable(feature = "rust1", since = "1.0.0")]
97 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
100 /// A trait for writing or formatting into Unicode-accepting buffers or streams.
102 /// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
103 /// want to accept Unicode and you don't need flushing, you should implement this trait;
104 /// otherwise you should implement [`std::io::Write`].
106 /// [`std::io::Write`]: ../../std/io/trait.Write.html
107 /// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
108 #[stable(feature = "rust1", since = "1.0.0")]
110 /// Writes a string slice into this writer, returning whether the write
113 /// This method can only succeed if the entire string slice was successfully
114 /// written, and this method will not return until all data has been
115 /// written or an error occurs.
119 /// This function will return an instance of [`Error`] on error.
124 /// use std::fmt::{Error, Write};
126 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
130 /// let mut buf = String::new();
131 /// writer(&mut buf, "hola").unwrap();
132 /// assert_eq!(&buf, "hola");
134 #[stable(feature = "rust1", since = "1.0.0")]
135 fn write_str(&mut self, s: &str) -> Result;
137 /// Writes a [`char`] into this writer, returning whether the write succeeded.
139 /// A single [`char`] may be encoded as more than one byte.
140 /// This method can only succeed if the entire byte sequence was successfully
141 /// written, and this method will not return until all data has been
142 /// written or an error occurs.
146 /// This function will return an instance of [`Error`] on error.
151 /// use std::fmt::{Error, Write};
153 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
157 /// let mut buf = String::new();
158 /// writer(&mut buf, 'a').unwrap();
159 /// writer(&mut buf, 'b').unwrap();
160 /// assert_eq!(&buf, "ab");
162 #[stable(feature = "fmt_write_char", since = "1.1.0")]
163 fn write_char(&mut self, c: char) -> Result {
164 self.write_str(c.encode_utf8(&mut [0; 4]))
167 /// Glue for usage of the [`write!`] macro with implementors of this trait.
169 /// This method should generally not be invoked manually, but rather through
170 /// the [`write!`] macro itself.
175 /// use std::fmt::{Error, Write};
177 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
178 /// f.write_fmt(format_args!("{s}"))
181 /// let mut buf = String::new();
182 /// writer(&mut buf, "world").unwrap();
183 /// assert_eq!(&buf, "world");
185 #[stable(feature = "rust1", since = "1.0.0")]
186 fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
187 write(&mut self, args)
191 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
192 impl<W: Write + ?Sized> Write for &mut W {
193 fn write_str(&mut self, s: &str) -> Result {
194 (**self).write_str(s)
197 fn write_char(&mut self, c: char) -> Result {
198 (**self).write_char(c)
201 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
202 (**self).write_fmt(args)
206 /// Configuration for formatting.
208 /// A `Formatter` represents various options related to formatting. Users do not
209 /// construct `Formatter`s directly; a mutable reference to one is passed to
210 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
212 /// To interact with a `Formatter`, you'll call various methods to change the
213 /// various options related to formatting. For examples, please see the
214 /// documentation of the methods defined on `Formatter` below.
215 #[allow(missing_debug_implementations)]
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub struct Formatter<'a> {
220 align: rt::v1::Alignment,
221 width: Option<usize>,
222 precision: Option<usize>,
224 buf: &'a mut (dyn Write + 'a),
227 impl<'a> Formatter<'a> {
228 /// Creates a new formatter with default settings.
230 /// This can be used as a micro-optimization in cases where a full `Arguments`
231 /// structure (as created by `format_args!`) is not necessary; `Arguments`
232 /// is a little more expensive to use in simple formatting scenarios.
234 /// Currently not intended for use outside of the standard library.
235 #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
237 pub fn new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
241 align: rt::v1::Alignment::Unknown,
249 // NB. Argument is essentially an optimized partially applied formatting function,
250 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
256 /// This struct represents the generic "argument" which is taken by the Xprintf
257 /// family of functions. It contains a function to format the given value. At
258 /// compile time it is ensured that the function and the value have the correct
259 /// types, and then this struct is used to canonicalize arguments to one type.
260 #[derive(Copy, Clone)]
261 #[allow(missing_debug_implementations)]
262 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
264 pub struct ArgumentV1<'a> {
266 formatter: fn(&Opaque, &mut Formatter<'_>) -> Result,
269 /// This struct represents the unsafety of constructing an `Arguments`.
270 /// It exists, rather than an unsafe function, in order to simplify the expansion
271 /// of `format_args!(..)` and reduce the scope of the `unsafe` block.
272 #[allow(missing_debug_implementations)]
274 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
275 pub struct UnsafeArg {
280 /// See documentation where `UnsafeArg` is required to know when it is safe to
281 /// create and use `UnsafeArg`.
283 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
285 pub unsafe fn new() -> Self {
286 Self { _private: () }
290 // This guarantees a single stable value for the function pointer associated with
291 // indices/counts in the formatting infrastructure.
293 // Note that a function defined as such would not be correct as functions are
294 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
295 // address is not considered important to LLVM and as such the as_usize cast
296 // could have been miscompiled. In practice, we never call as_usize on non-usize
297 // containing data (as a matter of static generation of the formatting
298 // arguments), so this is merely an additional check.
300 // We primarily want to ensure that the function pointer at `USIZE_MARKER` has
301 // an address corresponding *only* to functions that also take `&usize` as their
302 // first argument. The read_volatile here ensures that we can safely ready out a
303 // usize from the passed reference and that this address does not point at a
304 // non-usize taking function.
305 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
306 static USIZE_MARKER: fn(&usize, &mut Formatter<'_>) -> Result = |ptr, _| {
307 // SAFETY: ptr is a reference
308 let _v: usize = unsafe { crate::ptr::read_volatile(ptr) };
312 macro_rules! arg_new {
313 ($f: ident, $t: ident) => {
315 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
317 pub fn $f<'b, T: $t>(x: &'b T) -> ArgumentV1<'_> {
318 Self::new(x, $t::fmt)
323 impl<'a> ArgumentV1<'a> {
325 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
327 pub fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
328 // SAFETY: `mem::transmute(x)` is safe because
329 // 1. `&'b T` keeps the lifetime it originated with `'b`
330 // (so as to not have an unbounded lifetime)
331 // 2. `&'b T` and `&'b Opaque` have the same memory layout
332 // (when `T` is `Sized`, as it is here)
333 // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
334 // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
335 // (as long as `T` is `Sized`)
336 unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) } }
339 arg_new!(new_display, Display);
340 arg_new!(new_debug, Debug);
341 arg_new!(new_octal, Octal);
342 arg_new!(new_lower_hex, LowerHex);
343 arg_new!(new_upper_hex, UpperHex);
344 arg_new!(new_pointer, Pointer);
345 arg_new!(new_binary, Binary);
346 arg_new!(new_lower_exp, LowerExp);
347 arg_new!(new_upper_exp, UpperExp);
350 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
351 pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
352 ArgumentV1::new(x, USIZE_MARKER)
355 fn as_usize(&self) -> Option<usize> {
356 // We are type punning a bit here: USIZE_MARKER only takes an &usize but
357 // formatter takes an &Opaque. Rust understandably doesn't think we should compare
358 // the function pointers if they don't have the same signature, so we cast to
359 // usizes to tell it that we just want to compare addresses.
360 if self.formatter as usize == USIZE_MARKER as usize {
361 // SAFETY: The `formatter` field is only set to USIZE_MARKER if
362 // the value is a usize, so this is safe
363 Some(unsafe { *(self.value as *const _ as *const usize) })
370 // flags available in the v1 format of format_args
371 #[derive(Copy, Clone)]
381 impl<'a> Arguments<'a> {
382 /// When using the format_args!() macro, this function is used to generate the
383 /// Arguments structure.
386 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
387 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
388 pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
389 if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
390 panic!("invalid args");
392 Arguments { pieces, fmt: None, args }
395 /// This function is used to specify nonstandard formatting parameters.
397 /// An `UnsafeArg` is required because the following invariants must be held
398 /// in order for this function to be safe:
399 /// 1. The `pieces` slice must be at least as long as `fmt`.
400 /// 2. Every [`rt::v1::Argument::position`] value within `fmt` must be a
401 /// valid index of `args`.
402 /// 3. Every [`Count::Param`] within `fmt` must contain a valid index of
406 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
407 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
408 pub const fn new_v1_formatted(
409 pieces: &'a [&'static str],
410 args: &'a [ArgumentV1<'a>],
411 fmt: &'a [rt::v1::Argument],
412 _unsafe_arg: UnsafeArg,
414 Arguments { pieces, fmt: Some(fmt), args }
417 /// Estimates the length of the formatted text.
419 /// This is intended to be used for setting initial `String` capacity
420 /// when using `format!`. Note: this is neither the lower nor upper bound.
423 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
424 pub fn estimated_capacity(&self) -> usize {
425 let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
427 if self.args.is_empty() {
429 } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
430 // If the format string starts with an argument,
431 // don't preallocate anything, unless length
432 // of pieces is significant.
435 // There are some arguments, so any additional push
436 // will reallocate the string. To avoid that,
437 // we're "pre-doubling" the capacity here.
438 pieces_length.checked_mul(2).unwrap_or(0)
443 /// This structure represents a safely precompiled version of a format string
444 /// and its arguments. This cannot be generated at runtime because it cannot
445 /// safely be done, so no constructors are given and the fields are private
446 /// to prevent modification.
448 /// The [`format_args!`] macro will safely create an instance of this structure.
449 /// The macro validates the format string at compile-time so usage of the
450 /// [`write()`] and [`format()`] functions can be safely performed.
452 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
453 /// and `Display` contexts as seen below. The example also shows that `Debug`
454 /// and `Display` format to the same thing: the interpolated format string
455 /// in `format_args!`.
458 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
459 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
460 /// assert_eq!("1 foo 2", display);
461 /// assert_eq!(display, debug);
464 /// [`format()`]: ../../std/fmt/fn.format.html
465 #[stable(feature = "rust1", since = "1.0.0")]
466 #[cfg_attr(not(test), rustc_diagnostic_item = "Arguments")]
467 #[derive(Copy, Clone)]
468 pub struct Arguments<'a> {
469 // Format string pieces to print.
470 pieces: &'a [&'static str],
472 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
473 fmt: Option<&'a [rt::v1::Argument]>,
475 // Dynamic arguments for interpolation, to be interleaved with string
476 // pieces. (Every argument is preceded by a string piece.)
477 args: &'a [ArgumentV1<'a>],
480 impl<'a> Arguments<'a> {
481 /// Get the formatted string, if it has no arguments to be formatted.
483 /// This can be used to avoid allocations in the most trivial case.
488 /// use std::fmt::Arguments;
490 /// fn write_str(_: &str) { /* ... */ }
492 /// fn write_fmt(args: &Arguments) {
493 /// if let Some(s) = args.as_str() {
496 /// write_str(&args.to_string());
502 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
503 /// assert_eq!(format_args!("").as_str(), Some(""));
504 /// assert_eq!(format_args!("{}", 1).as_str(), None);
506 #[stable(feature = "fmt_as_str", since = "1.52.0")]
507 #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "none")]
510 pub const fn as_str(&self) -> Option<&'static str> {
511 match (self.pieces, self.args) {
512 ([], []) => Some(""),
513 ([s], []) => Some(s),
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl Debug for Arguments<'_> {
521 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
522 Display::fmt(self, fmt)
526 #[stable(feature = "rust1", since = "1.0.0")]
527 impl Display for Arguments<'_> {
528 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
529 write(fmt.buf, *self)
535 /// `Debug` should format the output in a programmer-facing, debugging context.
537 /// Generally speaking, you should just `derive` a `Debug` implementation.
539 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
541 /// For more information on formatters, see [the module-level documentation][module].
543 /// [module]: ../../std/fmt/index.html
545 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
546 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
547 /// comma-separated list of each field's name and `Debug` value, then `}`. For
548 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
549 /// `Debug` values of the fields, then `)`.
553 /// Derived `Debug` formats are not stable, and so may change with future Rust
554 /// versions. Additionally, `Debug` implementations of types provided by the
555 /// standard library (`libstd`, `libcore`, `liballoc`, etc.) are not stable, and
556 /// may also change with future Rust versions.
560 /// Deriving an implementation:
569 /// let origin = Point { x: 0, y: 0 };
571 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
574 /// Manually implementing:
584 /// impl fmt::Debug for Point {
585 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
586 /// f.debug_struct("Point")
587 /// .field("x", &self.x)
588 /// .field("y", &self.y)
593 /// let origin = Point { x: 0, y: 0 };
595 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
598 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
599 /// implementations, such as [`debug_struct`].
601 /// [`debug_struct`]: Formatter::debug_struct
603 /// Types that do not wish to use the standard suite of debug representations
604 /// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
605 /// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
606 /// manually writing an arbitrary representation to the `Formatter`.
615 /// impl fmt::Debug for Point {
616 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
617 /// write!(f, "Point [{} {}]", self.x, self.y)
622 /// `Debug` implementations using either `derive` or the debug builder API
623 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
625 /// Pretty-printing with `#?`:
634 /// let origin = Point { x: 0, y: 0 };
636 /// assert_eq!(format!("The origin is: {origin:#?}"),
637 /// "The origin is: Point {
643 #[stable(feature = "rust1", since = "1.0.0")]
644 #[rustc_on_unimplemented(
647 label = "`{Self}` cannot be formatted using `{{:?}}`",
648 note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
650 message = "`{Self}` doesn't implement `{Debug}`",
651 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
653 #[doc(alias = "{:?}")]
654 #[rustc_diagnostic_item = "Debug"]
655 #[rustc_trivial_field_reads]
657 /// Formats the value using the given formatter.
664 /// struct Position {
669 /// impl fmt::Debug for Position {
670 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671 /// f.debug_tuple("")
672 /// .field(&self.longitude)
673 /// .field(&self.latitude)
678 /// let position = Position { longitude: 1.987, latitude: 2.983 };
679 /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
681 /// assert_eq!(format!("{position:#?}"), "(
686 #[stable(feature = "rust1", since = "1.0.0")]
687 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
690 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
691 pub(crate) mod macros {
692 /// Derive macro generating an impl of the trait `Debug`.
693 #[rustc_builtin_macro]
694 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
695 #[allow_internal_unstable(core_intrinsics)]
696 pub macro Debug($item:item) {
697 /* compiler built-in */
700 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
702 pub use macros::Debug;
704 /// Format trait for an empty format, `{}`.
706 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
707 /// output, and so cannot be derived.
709 /// For more information on formatters, see [the module-level documentation][module].
711 /// [module]: ../../std/fmt/index.html
715 /// Implementing `Display` on a type:
725 /// impl fmt::Display for Point {
726 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
727 /// write!(f, "({}, {})", self.x, self.y)
731 /// let origin = Point { x: 0, y: 0 };
733 /// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
735 #[rustc_on_unimplemented(
737 any(_Self = "std::path::Path", _Self = "std::path::PathBuf"),
738 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
739 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
740 as they may contain non-Unicode data"
742 message = "`{Self}` doesn't implement `{Display}`",
743 label = "`{Self}` cannot be formatted with the default formatter",
744 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
747 #[rustc_diagnostic_item = "Display"]
748 #[stable(feature = "rust1", since = "1.0.0")]
750 /// Formats the value using the given formatter.
757 /// struct Position {
762 /// impl fmt::Display for Position {
763 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
764 /// write!(f, "({}, {})", self.longitude, self.latitude)
768 /// assert_eq!("(1.987, 2.983)",
769 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
771 #[stable(feature = "rust1", since = "1.0.0")]
772 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
777 /// The `Octal` trait should format its output as a number in base-8.
779 /// For primitive signed integers (`i8` to `i128`, and `isize`),
780 /// negative values are formatted as the two’s complement representation.
782 /// The alternate flag, `#`, adds a `0o` in front of the output.
784 /// For more information on formatters, see [the module-level documentation][module].
786 /// [module]: ../../std/fmt/index.html
790 /// Basic usage with `i32`:
793 /// let x = 42; // 42 is '52' in octal
795 /// assert_eq!(format!("{x:o}"), "52");
796 /// assert_eq!(format!("{x:#o}"), "0o52");
798 /// assert_eq!(format!("{:o}", -16), "37777777760");
801 /// Implementing `Octal` on a type:
806 /// struct Length(i32);
808 /// impl fmt::Octal for Length {
809 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
810 /// let val = self.0;
812 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
816 /// let l = Length(9);
818 /// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
820 /// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
822 #[stable(feature = "rust1", since = "1.0.0")]
824 /// Formats the value using the given formatter.
825 #[stable(feature = "rust1", since = "1.0.0")]
826 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
831 /// The `Binary` trait should format its output as a number in binary.
833 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
834 /// negative values are formatted as the two’s complement representation.
836 /// The alternate flag, `#`, adds a `0b` in front of the output.
838 /// For more information on formatters, see [the module-level documentation][module].
840 /// [module]: ../../std/fmt/index.html
844 /// Basic usage with [`i32`]:
847 /// let x = 42; // 42 is '101010' in binary
849 /// assert_eq!(format!("{x:b}"), "101010");
850 /// assert_eq!(format!("{x:#b}"), "0b101010");
852 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
855 /// Implementing `Binary` on a type:
860 /// struct Length(i32);
862 /// impl fmt::Binary for Length {
863 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
864 /// let val = self.0;
866 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
870 /// let l = Length(107);
872 /// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
875 /// format!("l as binary is: {l:#032b}"),
876 /// "l as binary is: 0b000000000000000000000001101011"
879 #[stable(feature = "rust1", since = "1.0.0")]
881 /// Formats the value using the given formatter.
882 #[stable(feature = "rust1", since = "1.0.0")]
883 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
888 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
891 /// For primitive signed integers (`i8` to `i128`, and `isize`),
892 /// negative values are formatted as the two’s complement representation.
894 /// The alternate flag, `#`, adds a `0x` in front of the output.
896 /// For more information on formatters, see [the module-level documentation][module].
898 /// [module]: ../../std/fmt/index.html
902 /// Basic usage with `i32`:
905 /// let x = 42; // 42 is '2a' in hex
907 /// assert_eq!(format!("{x:x}"), "2a");
908 /// assert_eq!(format!("{x:#x}"), "0x2a");
910 /// assert_eq!(format!("{:x}", -16), "fffffff0");
913 /// Implementing `LowerHex` on a type:
918 /// struct Length(i32);
920 /// impl fmt::LowerHex for Length {
921 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
922 /// let val = self.0;
924 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
928 /// let l = Length(9);
930 /// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
932 /// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
934 #[stable(feature = "rust1", since = "1.0.0")]
936 /// Formats the value using the given formatter.
937 #[stable(feature = "rust1", since = "1.0.0")]
938 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
943 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
946 /// For primitive signed integers (`i8` to `i128`, and `isize`),
947 /// negative values are formatted as the two’s complement representation.
949 /// The alternate flag, `#`, adds a `0x` in front of the output.
951 /// For more information on formatters, see [the module-level documentation][module].
953 /// [module]: ../../std/fmt/index.html
957 /// Basic usage with `i32`:
960 /// let x = 42; // 42 is '2A' in hex
962 /// assert_eq!(format!("{x:X}"), "2A");
963 /// assert_eq!(format!("{x:#X}"), "0x2A");
965 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
968 /// Implementing `UpperHex` on a type:
973 /// struct Length(i32);
975 /// impl fmt::UpperHex for Length {
976 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
977 /// let val = self.0;
979 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
983 /// let l = Length(i32::MAX);
985 /// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
987 /// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
989 #[stable(feature = "rust1", since = "1.0.0")]
991 /// Formats the value using the given formatter.
992 #[stable(feature = "rust1", since = "1.0.0")]
993 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
998 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
1001 /// For more information on formatters, see [the module-level documentation][module].
1003 /// [module]: ../../std/fmt/index.html
1007 /// Basic usage with `&i32`:
1012 /// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
1015 /// Implementing `Pointer` on a type:
1020 /// struct Length(i32);
1022 /// impl fmt::Pointer for Length {
1023 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1024 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1026 /// let ptr = self as *const Self;
1027 /// fmt::Pointer::fmt(&ptr, f)
1031 /// let l = Length(42);
1033 /// println!("l is in memory here: {l:p}");
1035 /// let l_ptr = format!("{l:018p}");
1036 /// assert_eq!(l_ptr.len(), 18);
1037 /// assert_eq!(&l_ptr[..2], "0x");
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 #[rustc_diagnostic_item = "Pointer"]
1042 /// Formats the value using the given formatter.
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 #[rustc_diagnostic_item = "pointer_trait_fmt"]
1045 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1050 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1052 /// For more information on formatters, see [the module-level documentation][module].
1054 /// [module]: ../../std/fmt/index.html
1058 /// Basic usage with `f64`:
1061 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1063 /// assert_eq!(format!("{x:e}"), "4.2e1");
1066 /// Implementing `LowerExp` on a type:
1071 /// struct Length(i32);
1073 /// impl fmt::LowerExp for Length {
1074 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1075 /// let val = f64::from(self.0);
1076 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1080 /// let l = Length(100);
1083 /// format!("l in scientific notation is: {l:e}"),
1084 /// "l in scientific notation is: 1e2"
1088 /// format!("l in scientific notation is: {l:05e}"),
1089 /// "l in scientific notation is: 001e2"
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 pub trait LowerExp {
1094 /// Formats the value using the given formatter.
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1101 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1103 /// For more information on formatters, see [the module-level documentation][module].
1105 /// [module]: ../../std/fmt/index.html
1109 /// Basic usage with `f64`:
1112 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1114 /// assert_eq!(format!("{x:E}"), "4.2E1");
1117 /// Implementing `UpperExp` on a type:
1122 /// struct Length(i32);
1124 /// impl fmt::UpperExp for Length {
1125 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1126 /// let val = f64::from(self.0);
1127 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1131 /// let l = Length(100);
1134 /// format!("l in scientific notation is: {l:E}"),
1135 /// "l in scientific notation is: 1E2"
1139 /// format!("l in scientific notation is: {l:05E}"),
1140 /// "l in scientific notation is: 001E2"
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 pub trait UpperExp {
1145 /// Formats the value using the given formatter.
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1150 /// The `write` function takes an output stream, and an `Arguments` struct
1151 /// that can be precompiled with the `format_args!` macro.
1153 /// The arguments will be formatted according to the specified format string
1154 /// into the output stream provided.
1163 /// let mut output = String::new();
1164 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1165 /// .expect("Error occurred while trying to write in String");
1166 /// assert_eq!(output, "Hello world!");
1169 /// Please note that using [`write!`] might be preferable. Example:
1172 /// use std::fmt::Write;
1174 /// let mut output = String::new();
1175 /// write!(&mut output, "Hello {}!", "world")
1176 /// .expect("Error occurred while trying to write in String");
1177 /// assert_eq!(output, "Hello world!");
1180 /// [`write!`]: crate::write!
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1183 let mut formatter = Formatter::new(output);
1188 // We can use default formatting parameters for all arguments.
1189 for (i, arg) in args.args.iter().enumerate() {
1190 // SAFETY: args.args and args.pieces come from the same Arguments,
1191 // which guarantees the indexes are always within bounds.
1192 let piece = unsafe { args.pieces.get_unchecked(i) };
1193 if !piece.is_empty() {
1194 formatter.buf.write_str(*piece)?;
1196 (arg.formatter)(arg.value, &mut formatter)?;
1201 // Every spec has a corresponding argument that is preceded by
1203 for (i, arg) in fmt.iter().enumerate() {
1204 // SAFETY: fmt and args.pieces come from the same Arguments,
1205 // which guarantees the indexes are always within bounds.
1206 let piece = unsafe { args.pieces.get_unchecked(i) };
1207 if !piece.is_empty() {
1208 formatter.buf.write_str(*piece)?;
1210 // SAFETY: arg and args.args come from the same Arguments,
1211 // which guarantees the indexes are always within bounds.
1212 unsafe { run(&mut formatter, arg, args.args) }?;
1218 // There can be only one trailing string piece left.
1219 if let Some(piece) = args.pieces.get(idx) {
1220 formatter.buf.write_str(*piece)?;
1226 unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1227 fmt.fill = arg.format.fill;
1228 fmt.align = arg.format.align;
1229 fmt.flags = arg.format.flags;
1230 // SAFETY: arg and args come from the same Arguments,
1231 // which guarantees the indexes are always within bounds.
1233 fmt.width = getcount(args, &arg.format.width);
1234 fmt.precision = getcount(args, &arg.format.precision);
1237 // Extract the correct argument
1238 debug_assert!(arg.position < args.len());
1239 // SAFETY: arg and args come from the same Arguments,
1240 // which guarantees its index is always within bounds.
1241 let value = unsafe { args.get_unchecked(arg.position) };
1243 // Then actually do some printing
1244 (value.formatter)(value.value, fmt)
1247 unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1249 rt::v1::Count::Is(n) => Some(n),
1250 rt::v1::Count::Implied => None,
1251 rt::v1::Count::Param(i) => {
1252 debug_assert!(i < args.len());
1253 // SAFETY: cnt and args come from the same Arguments,
1254 // which guarantees this index is always within bounds.
1255 unsafe { args.get_unchecked(i).as_usize() }
1260 /// Padding after the end of something. Returned by `Formatter::padding`.
1261 #[must_use = "don't forget to write the post padding"]
1262 pub(crate) struct PostPadding {
1268 fn new(fill: char, padding: usize) -> PostPadding {
1269 PostPadding { fill, padding }
1272 /// Write this post padding.
1273 pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1274 for _ in 0..self.padding {
1275 f.buf.write_char(self.fill)?;
1281 impl<'a> Formatter<'a> {
1282 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1285 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1288 // We want to change this
1289 buf: wrap(self.buf),
1291 // And preserve these
1296 precision: self.precision,
1300 // Helper methods used for padding and processing formatting arguments that
1301 // all formatting traits can use.
1303 /// Performs the correct padding for an integer which has already been
1304 /// emitted into a str. The str should *not* contain the sign for the
1305 /// integer, that will be added by this method.
1309 /// * is_nonnegative - whether the original integer was either positive or zero.
1310 /// * prefix - if the '#' character (Alternate) is provided, this
1311 /// is the prefix to put in front of the number.
1312 /// * buf - the byte array that the number has been formatted into
1314 /// This function will correctly account for the flags provided as well as
1315 /// the minimum width. It will not take precision into account.
1322 /// struct Foo { nb: i32 }
1325 /// fn new(nb: i32) -> Foo {
1332 /// impl fmt::Display for Foo {
1333 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1334 /// // We need to remove "-" from the number output.
1335 /// let tmp = self.nb.abs().to_string();
1337 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1341 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1342 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1343 /// assert_eq!(&format!("{}", Foo::new(0)), "0");
1344 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1345 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1349 let mut width = buf.len();
1351 let mut sign = None;
1352 if !is_nonnegative {
1355 } else if self.sign_plus() {
1360 let prefix = if self.alternate() {
1361 width += prefix.chars().count();
1367 // Writes the sign if it exists, and then the prefix if it was requested
1369 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1370 if let Some(c) = sign {
1371 f.buf.write_char(c)?;
1373 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1376 // The `width` field is more of a `min-width` parameter at this point.
1378 // If there's no minimum length requirements then we can just
1381 write_prefix(self, sign, prefix)?;
1382 self.buf.write_str(buf)
1384 // Check if we're over the minimum width, if so then we can also
1385 // just write the bytes.
1386 Some(min) if width >= min => {
1387 write_prefix(self, sign, prefix)?;
1388 self.buf.write_str(buf)
1390 // The sign and prefix goes before the padding if the fill character
1392 Some(min) if self.sign_aware_zero_pad() => {
1393 let old_fill = crate::mem::replace(&mut self.fill, '0');
1394 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1395 write_prefix(self, sign, prefix)?;
1396 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1397 self.buf.write_str(buf)?;
1398 post_padding.write(self)?;
1399 self.fill = old_fill;
1400 self.align = old_align;
1403 // Otherwise, the sign and prefix goes after the padding
1405 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1406 write_prefix(self, sign, prefix)?;
1407 self.buf.write_str(buf)?;
1408 post_padding.write(self)
1413 /// This function takes a string slice and emits it to the internal buffer
1414 /// after applying the relevant formatting flags specified. The flags
1415 /// recognized for generic strings are:
1417 /// * width - the minimum width of what to emit
1418 /// * fill/align - what to emit and where to emit it if the string
1419 /// provided needs to be padded
1420 /// * precision - the maximum length to emit, the string is truncated if it
1421 /// is longer than this length
1423 /// Notably this function ignores the `flag` parameters.
1432 /// impl fmt::Display for Foo {
1433 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1434 /// formatter.pad("Foo")
1438 /// assert_eq!(&format!("{Foo:<4}"), "Foo ");
1439 /// assert_eq!(&format!("{Foo:0>4}"), "0Foo");
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 pub fn pad(&mut self, s: &str) -> Result {
1443 // Make sure there's a fast path up front
1444 if self.width.is_none() && self.precision.is_none() {
1445 return self.buf.write_str(s);
1447 // The `precision` field can be interpreted as a `max-width` for the
1448 // string being formatted.
1449 let s = if let Some(max) = self.precision {
1450 // If our string is longer that the precision, then we must have
1451 // truncation. However other flags like `fill`, `width` and `align`
1452 // must act as always.
1453 if let Some((i, _)) = s.char_indices().nth(max) {
1454 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1455 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1456 // `unsafe` and otherwise don't emit any panic-related code
1458 s.get(..i).unwrap_or(s)
1465 // The `width` field is more of a `min-width` parameter at this point.
1467 // If we're under the maximum length, and there's no minimum length
1468 // requirements, then we can just emit the string
1469 None => self.buf.write_str(s),
1471 let chars_count = s.chars().count();
1472 // If we're under the maximum width, check if we're over the minimum
1473 // width, if so it's as easy as just emitting the string.
1474 if chars_count >= width {
1475 self.buf.write_str(s)
1477 // If we're under both the maximum and the minimum width, then fill
1478 // up the minimum width with the specified string + some alignment.
1480 let align = rt::v1::Alignment::Left;
1481 let post_padding = self.padding(width - chars_count, align)?;
1482 self.buf.write_str(s)?;
1483 post_padding.write(self)
1489 /// Write the pre-padding and return the unwritten post-padding. Callers are
1490 /// responsible for ensuring post-padding is written after the thing that is
1492 pub(crate) fn padding(
1495 default: rt::v1::Alignment,
1496 ) -> result::Result<PostPadding, Error> {
1497 let align = match self.align {
1498 rt::v1::Alignment::Unknown => default,
1502 let (pre_pad, post_pad) = match align {
1503 rt::v1::Alignment::Left => (0, padding),
1504 rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1505 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1508 for _ in 0..pre_pad {
1509 self.buf.write_char(self.fill)?;
1512 Ok(PostPadding::new(self.fill, post_pad))
1515 /// Takes the formatted parts and applies the padding.
1516 /// Assumes that the caller already has rendered the parts with required precision,
1517 /// so that `self.precision` can be ignored.
1518 fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1519 if let Some(mut width) = self.width {
1520 // for the sign-aware zero padding, we render the sign first and
1521 // behave as if we had no sign from the beginning.
1522 let mut formatted = formatted.clone();
1523 let old_fill = self.fill;
1524 let old_align = self.align;
1525 let mut align = old_align;
1526 if self.sign_aware_zero_pad() {
1527 // a sign always goes first
1528 let sign = formatted.sign;
1529 self.buf.write_str(sign)?;
1531 // remove the sign from the formatted parts
1532 formatted.sign = "";
1533 width = width.saturating_sub(sign.len());
1534 align = rt::v1::Alignment::Right;
1536 self.align = rt::v1::Alignment::Right;
1539 // remaining parts go through the ordinary padding process.
1540 let len = formatted.len();
1541 let ret = if width <= len {
1543 self.write_formatted_parts(&formatted)
1545 let post_padding = self.padding(width - len, align)?;
1546 self.write_formatted_parts(&formatted)?;
1547 post_padding.write(self)
1549 self.fill = old_fill;
1550 self.align = old_align;
1553 // this is the common case and we take a shortcut
1554 self.write_formatted_parts(formatted)
1558 fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1559 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1560 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1561 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1562 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1563 // It's also probably safe in practice to use for `numfmt::Part::Copy(buf)`
1564 // since `buf` should be plain ASCII, but it's possible for someone to pass
1565 // in a bad value for `buf` into `numfmt::to_shortest_str` since it is a
1567 // FIXME: Determine whether this could result in UB.
1568 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1571 if !formatted.sign.is_empty() {
1572 self.buf.write_str(formatted.sign)?;
1574 for part in formatted.parts {
1576 numfmt::Part::Zero(mut nzeroes) => {
1577 const ZEROES: &str = // 64 zeroes
1578 "0000000000000000000000000000000000000000000000000000000000000000";
1579 while nzeroes > ZEROES.len() {
1580 self.buf.write_str(ZEROES)?;
1581 nzeroes -= ZEROES.len();
1584 self.buf.write_str(&ZEROES[..nzeroes])?;
1587 numfmt::Part::Num(mut v) => {
1589 let len = part.len();
1590 for c in s[..len].iter_mut().rev() {
1591 *c = b'0' + (v % 10) as u8;
1594 write_bytes(self.buf, &s[..len])?;
1596 numfmt::Part::Copy(buf) => {
1597 write_bytes(self.buf, buf)?;
1604 /// Writes some data to the underlying buffer contained within this
1614 /// impl fmt::Display for Foo {
1615 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1616 /// formatter.write_str("Foo")
1617 /// // This is equivalent to:
1618 /// // write!(formatter, "Foo")
1622 /// assert_eq!(&format!("{Foo}"), "Foo");
1623 /// assert_eq!(&format!("{Foo:0>8}"), "Foo");
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 pub fn write_str(&mut self, data: &str) -> Result {
1627 self.buf.write_str(data)
1630 /// Writes some formatted information into this instance.
1637 /// struct Foo(i32);
1639 /// impl fmt::Display for Foo {
1640 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1641 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1645 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1646 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1648 #[stable(feature = "rust1", since = "1.0.0")]
1649 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1650 write(self.buf, fmt)
1653 /// Flags for formatting
1655 #[stable(feature = "rust1", since = "1.0.0")]
1658 note = "use the `sign_plus`, `sign_minus`, `alternate`, \
1659 or `sign_aware_zero_pad` methods instead"
1661 pub fn flags(&self) -> u32 {
1665 /// Character used as 'fill' whenever there is alignment.
1674 /// impl fmt::Display for Foo {
1675 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1676 /// let c = formatter.fill();
1677 /// if let Some(width) = formatter.width() {
1678 /// for _ in 0..width {
1679 /// write!(formatter, "{c}")?;
1683 /// write!(formatter, "{c}")
1688 /// // We set alignment to the right with ">".
1689 /// assert_eq!(&format!("{Foo:G>3}"), "GGG");
1690 /// assert_eq!(&format!("{Foo:t>6}"), "tttttt");
1693 #[stable(feature = "fmt_flags", since = "1.5.0")]
1694 pub fn fill(&self) -> char {
1698 /// Flag indicating what form of alignment was requested.
1703 /// extern crate core;
1705 /// use std::fmt::{self, Alignment};
1709 /// impl fmt::Display for Foo {
1710 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1711 /// let s = if let Some(s) = formatter.align() {
1713 /// Alignment::Left => "left",
1714 /// Alignment::Right => "right",
1715 /// Alignment::Center => "center",
1720 /// write!(formatter, "{s}")
1724 /// assert_eq!(&format!("{Foo:<}"), "left");
1725 /// assert_eq!(&format!("{Foo:>}"), "right");
1726 /// assert_eq!(&format!("{Foo:^}"), "center");
1727 /// assert_eq!(&format!("{Foo}"), "into the void");
1730 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1731 pub fn align(&self) -> Option<Alignment> {
1733 rt::v1::Alignment::Left => Some(Alignment::Left),
1734 rt::v1::Alignment::Right => Some(Alignment::Right),
1735 rt::v1::Alignment::Center => Some(Alignment::Center),
1736 rt::v1::Alignment::Unknown => None,
1740 /// Optionally specified integer width that the output should be.
1747 /// struct Foo(i32);
1749 /// impl fmt::Display for Foo {
1750 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1751 /// if let Some(width) = formatter.width() {
1752 /// // If we received a width, we use it
1753 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1755 /// // Otherwise we do nothing special
1756 /// write!(formatter, "Foo({})", self.0)
1761 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1762 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1765 #[stable(feature = "fmt_flags", since = "1.5.0")]
1766 pub fn width(&self) -> Option<usize> {
1770 /// Optionally specified precision for numeric types. Alternatively, the
1771 /// maximum width for string types.
1778 /// struct Foo(f32);
1780 /// impl fmt::Display for Foo {
1781 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1782 /// if let Some(precision) = formatter.precision() {
1783 /// // If we received a precision, we use it.
1784 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1786 /// // Otherwise we default to 2.
1787 /// write!(formatter, "Foo({:.2})", self.0)
1792 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1793 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1796 #[stable(feature = "fmt_flags", since = "1.5.0")]
1797 pub fn precision(&self) -> Option<usize> {
1801 /// Determines if the `+` flag was specified.
1808 /// struct Foo(i32);
1810 /// impl fmt::Display for Foo {
1811 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1812 /// if formatter.sign_plus() {
1813 /// write!(formatter,
1815 /// if self.0 < 0 { '-' } else { '+' },
1818 /// write!(formatter, "Foo({})", self.0)
1823 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1824 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1827 #[stable(feature = "fmt_flags", since = "1.5.0")]
1828 pub fn sign_plus(&self) -> bool {
1829 self.flags & (1 << FlagV1::SignPlus as u32) != 0
1832 /// Determines if the `-` flag was specified.
1839 /// struct Foo(i32);
1841 /// impl fmt::Display for Foo {
1842 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1843 /// if formatter.sign_minus() {
1844 /// // You want a minus sign? Have one!
1845 /// write!(formatter, "-Foo({})", self.0)
1847 /// write!(formatter, "Foo({})", self.0)
1852 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1853 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1856 #[stable(feature = "fmt_flags", since = "1.5.0")]
1857 pub fn sign_minus(&self) -> bool {
1858 self.flags & (1 << FlagV1::SignMinus as u32) != 0
1861 /// Determines if the `#` flag was specified.
1868 /// struct Foo(i32);
1870 /// impl fmt::Display for Foo {
1871 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1872 /// if formatter.alternate() {
1873 /// write!(formatter, "Foo({})", self.0)
1875 /// write!(formatter, "{}", self.0)
1880 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1881 /// assert_eq!(&format!("{}", Foo(23)), "23");
1884 #[stable(feature = "fmt_flags", since = "1.5.0")]
1885 pub fn alternate(&self) -> bool {
1886 self.flags & (1 << FlagV1::Alternate as u32) != 0
1889 /// Determines if the `0` flag was specified.
1896 /// struct Foo(i32);
1898 /// impl fmt::Display for Foo {
1899 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1900 /// assert!(formatter.sign_aware_zero_pad());
1901 /// assert_eq!(formatter.width(), Some(4));
1902 /// // We ignore the formatter's options.
1903 /// write!(formatter, "{}", self.0)
1907 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1910 #[stable(feature = "fmt_flags", since = "1.5.0")]
1911 pub fn sign_aware_zero_pad(&self) -> bool {
1912 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1915 // FIXME: Decide what public API we want for these two flags.
1916 // https://github.com/rust-lang/rust/issues/48584
1917 fn debug_lower_hex(&self) -> bool {
1918 self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1921 fn debug_upper_hex(&self) -> bool {
1922 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1925 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1926 /// [`fmt::Debug`] implementations for structs.
1928 /// [`fmt::Debug`]: self::Debug
1934 /// use std::net::Ipv4Addr;
1942 /// impl fmt::Debug for Foo {
1943 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1944 /// fmt.debug_struct("Foo")
1945 /// .field("bar", &self.bar)
1946 /// .field("baz", &self.baz)
1947 /// .field("addr", &format_args!("{}", self.addr))
1953 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1954 /// format!("{:?}", Foo {
1956 /// baz: "Hello World".to_string(),
1957 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1961 #[stable(feature = "debug_builders", since = "1.2.0")]
1962 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1963 builders::debug_struct_new(self, name)
1966 /// Creates a `DebugTuple` builder designed to assist with creation of
1967 /// `fmt::Debug` implementations for tuple structs.
1973 /// use std::marker::PhantomData;
1975 /// struct Foo<T>(i32, String, PhantomData<T>);
1977 /// impl<T> fmt::Debug for Foo<T> {
1978 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1979 /// fmt.debug_tuple("Foo")
1982 /// .field(&format_args!("_"))
1988 /// "Foo(10, \"Hello\", _)",
1989 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1992 #[stable(feature = "debug_builders", since = "1.2.0")]
1993 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1994 builders::debug_tuple_new(self, name)
1997 /// Creates a `DebugList` builder designed to assist with creation of
1998 /// `fmt::Debug` implementations for list-like structures.
2005 /// struct Foo(Vec<i32>);
2007 /// impl fmt::Debug for Foo {
2008 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2009 /// fmt.debug_list().entries(self.0.iter()).finish()
2013 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2015 #[stable(feature = "debug_builders", since = "1.2.0")]
2016 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2017 builders::debug_list_new(self)
2020 /// Creates a `DebugSet` builder designed to assist with creation of
2021 /// `fmt::Debug` implementations for set-like structures.
2028 /// struct Foo(Vec<i32>);
2030 /// impl fmt::Debug for Foo {
2031 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2032 /// fmt.debug_set().entries(self.0.iter()).finish()
2036 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2039 /// [`format_args!`]: crate::format_args
2041 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2042 /// to build a list of match arms:
2047 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
2048 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
2050 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2052 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
2054 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2055 /// L::fmt(&(self.0).0, fmt)?;
2056 /// fmt.write_str(" => ")?;
2057 /// R::fmt(&(self.0).1, fmt)
2061 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2063 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
2065 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2067 /// .entries(self.0.iter().map(Arm))
2068 /// .entry(&Arm(&(format_args!("_"), &self.1)))
2073 #[stable(feature = "debug_builders", since = "1.2.0")]
2074 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2075 builders::debug_set_new(self)
2078 /// Creates a `DebugMap` builder designed to assist with creation of
2079 /// `fmt::Debug` implementations for map-like structures.
2086 /// struct Foo(Vec<(String, i32)>);
2088 /// impl fmt::Debug for Foo {
2089 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2090 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2095 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2096 /// r#"{"A": 10, "B": 11}"#
2099 #[stable(feature = "debug_builders", since = "1.2.0")]
2100 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2101 builders::debug_map_new(self)
2105 #[stable(since = "1.2.0", feature = "formatter_write")]
2106 impl Write for Formatter<'_> {
2107 fn write_str(&mut self, s: &str) -> Result {
2108 self.buf.write_str(s)
2111 fn write_char(&mut self, c: char) -> Result {
2112 self.buf.write_char(c)
2115 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2116 write(self.buf, args)
2120 #[stable(feature = "rust1", since = "1.0.0")]
2121 impl Display for Error {
2122 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2123 Display::fmt("an error occurred when formatting an argument", f)
2127 // Implementations of the core formatting traits
2129 macro_rules! fmt_refs {
2130 ($($tr:ident),*) => {
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 impl<T: ?Sized + $tr> $tr for &T {
2134 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 impl<T: ?Sized + $tr> $tr for &mut T {
2138 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2144 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2146 #[unstable(feature = "never_type", issue = "35121")]
2148 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2153 #[unstable(feature = "never_type", issue = "35121")]
2154 impl Display for ! {
2155 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 impl Debug for bool {
2163 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2164 Display::fmt(self, f)
2168 #[stable(feature = "rust1", since = "1.0.0")]
2169 impl Display for bool {
2170 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2171 Display::fmt(if *self { "true" } else { "false" }, f)
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 impl Debug for str {
2177 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2180 for (i, c) in self.char_indices() {
2181 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2182 escape_grapheme_extended: true,
2183 escape_single_quote: false,
2184 escape_double_quote: true,
2186 // If char needs escaping, flush backlog so far and write, else skip
2188 f.write_str(&self[from..i])?;
2192 from = i + c.len_utf8();
2195 f.write_str(&self[from..])?;
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 impl Display for str {
2202 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2207 #[stable(feature = "rust1", since = "1.0.0")]
2208 impl Debug for char {
2209 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2210 f.write_char('\'')?;
2211 for c in self.escape_debug_ext(EscapeDebugExtArgs {
2212 escape_grapheme_extended: true,
2213 escape_single_quote: true,
2214 escape_double_quote: false,
2222 #[stable(feature = "rust1", since = "1.0.0")]
2223 impl Display for char {
2224 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2225 if f.width.is_none() && f.precision.is_none() {
2228 f.pad(self.encode_utf8(&mut [0; 4]))
2233 #[stable(feature = "rust1", since = "1.0.0")]
2234 impl<T: ?Sized> Pointer for *const T {
2235 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2236 // Cast is needed here because `.addr()` requires `T: Sized`.
2237 pointer_fmt_inner((*self as *const ()).addr(), f)
2241 /// Since the formatting will be identical for all pointer types, use a non-monomorphized
2242 /// implementation for the actual formatting to reduce the amount of codegen work needed.
2244 /// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
2245 /// `fn(...) -> ...` without using [problematic] "Oxford Casts".
2247 /// [problematic]: https://github.com/rust-lang/rust/issues/95489
2248 pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
2249 let old_width = f.width;
2250 let old_flags = f.flags;
2252 // The alternate flag is already treated by LowerHex as being special-
2253 // it denotes whether to prefix with 0x. We use it to work out whether
2254 // or not to zero extend, and then unconditionally set it to get the
2257 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2259 if f.width.is_none() {
2260 f.width = Some((usize::BITS / 4) as usize + 2);
2263 f.flags |= 1 << (FlagV1::Alternate as u32);
2265 let ret = LowerHex::fmt(&ptr_addr, f);
2267 f.width = old_width;
2268 f.flags = old_flags;
2273 #[stable(feature = "rust1", since = "1.0.0")]
2274 impl<T: ?Sized> Pointer for *mut T {
2275 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2276 Pointer::fmt(&(*self as *const T), f)
2280 #[stable(feature = "rust1", since = "1.0.0")]
2281 impl<T: ?Sized> Pointer for &T {
2282 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2283 Pointer::fmt(&(*self as *const T), f)
2287 #[stable(feature = "rust1", since = "1.0.0")]
2288 impl<T: ?Sized> Pointer for &mut T {
2289 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2290 Pointer::fmt(&(&**self as *const T), f)
2294 // Implementation of Display/Debug for various core types
2296 #[stable(feature = "rust1", since = "1.0.0")]
2297 impl<T: ?Sized> Debug for *const T {
2298 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2299 Pointer::fmt(self, f)
2302 #[stable(feature = "rust1", since = "1.0.0")]
2303 impl<T: ?Sized> Debug for *mut T {
2304 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2305 Pointer::fmt(self, f)
2310 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2313 macro_rules! tuple {
2315 ( $($name:ident,)+ ) => (
2318 #[stable(feature = "rust1", since = "1.0.0")]
2319 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2320 #[allow(non_snake_case, unused_assignments)]
2321 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2322 let mut builder = f.debug_tuple("");
2323 let ($(ref $name,)+) = *self;
2325 builder.field(&$name);
2332 peel! { $($name,)+ }
2336 macro_rules! maybe_tuple_doc {
2337 ($a:ident @ #[$meta:meta] $item:item) => {
2338 #[doc = "This trait is implemented for tuples up to twelve items long."]
2342 ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
2349 macro_rules! last_type {
2350 ($a:ident,) => { $a };
2351 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2354 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 impl<T: Debug> Debug for [T] {
2358 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2359 f.debug_list().entries(self.iter()).finish()
2363 #[stable(feature = "rust1", since = "1.0.0")]
2366 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2370 #[stable(feature = "rust1", since = "1.0.0")]
2371 impl<T: ?Sized> Debug for PhantomData<T> {
2372 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2373 f.debug_struct("PhantomData").finish()
2377 #[stable(feature = "rust1", since = "1.0.0")]
2378 impl<T: Copy + Debug> Debug for Cell<T> {
2379 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2380 f.debug_struct("Cell").field("value", &self.get()).finish()
2384 #[stable(feature = "rust1", since = "1.0.0")]
2385 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2386 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2387 match self.try_borrow() {
2388 Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2390 // The RefCell is mutably borrowed so we can't look at its value
2391 // here. Show a placeholder instead.
2392 struct BorrowedPlaceholder;
2394 impl Debug for BorrowedPlaceholder {
2395 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2396 f.write_str("<borrowed>")
2400 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2406 #[stable(feature = "rust1", since = "1.0.0")]
2407 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2408 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2409 Debug::fmt(&**self, f)
2413 #[stable(feature = "rust1", since = "1.0.0")]
2414 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2415 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2416 Debug::fmt(&*(self.deref()), f)
2420 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2421 impl<T: ?Sized> Debug for UnsafeCell<T> {
2422 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2423 f.debug_struct("UnsafeCell").finish_non_exhaustive()
2427 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2428 impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
2429 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2430 f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
2434 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2435 // it's a lot easier than creating all of the rt::Piece structures here.
2436 // There are also tests in the alloc crate, for those that need allocations.