1 //! Utilities for formatting and printing strings.
3 #![stable(feature = "rust1", since = "1.0.0")]
5 use crate::cell::{Cell, Ref, RefCell, RefMut, UnsafeCell};
6 use crate::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 /// Possible alignments returned by `Formatter::align`
25 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
26 /// Indication that contents should be left-aligned.
28 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
29 /// Indication that contents should be right-aligned.
31 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
32 /// Indication that contents should be center-aligned.
36 #[stable(feature = "debug_builders", since = "1.2.0")]
37 pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
39 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
45 /// The type returned by formatter methods.
59 /// impl fmt::Display for Triangle {
60 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
65 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
67 /// assert_eq!(format!("{}", pythagorean_triple), "(3, 4, 5)");
69 #[stable(feature = "rust1", since = "1.0.0")]
70 pub type Result = result::Result<(), Error>;
72 /// The error type which is returned from formatting a message into a stream.
74 /// This type does not support transmission of an error other than that an error
75 /// occurred. Any extra information must be arranged to be transmitted through
78 /// An important thing to remember is that the type `fmt::Error` should not be
79 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
82 /// [`std::io::Error`]: ../../std/io/struct.Error.html
83 /// [`std::error::Error`]: ../../std/error/trait.Error.html
88 /// use std::fmt::{self, write};
90 /// let mut output = String::new();
91 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
92 /// panic!("An error occurred");
95 #[stable(feature = "rust1", since = "1.0.0")]
96 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
99 /// A trait for writing or formatting into Unicode-accepting buffers or streams.
101 /// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
102 /// want to accept Unicode and you don't need flushing, you should implement this trait;
103 /// otherwise you should implement [`std::io::Write`].
105 /// [`std::io::Write`]: ../../std/io/trait.Write.html
106 /// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
107 #[stable(feature = "rust1", since = "1.0.0")]
109 /// Writes a string slice into this writer, returning whether the write
112 /// This method can only succeed if the entire string slice was successfully
113 /// written, and this method will not return until all data has been
114 /// written or an error occurs.
118 /// This function will return an instance of [`Error`] on error.
123 /// use std::fmt::{Error, Write};
125 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
129 /// let mut buf = String::new();
130 /// writer(&mut buf, "hola").unwrap();
131 /// assert_eq!(&buf, "hola");
133 #[stable(feature = "rust1", since = "1.0.0")]
134 fn write_str(&mut self, s: &str) -> Result;
136 /// Writes a [`char`] into this writer, returning whether the write succeeded.
138 /// A single [`char`] may be encoded as more than one byte.
139 /// This method can only succeed if the entire byte sequence was successfully
140 /// written, and this method will not return until all data has been
141 /// written or an error occurs.
145 /// This function will return an instance of [`Error`] on error.
150 /// use std::fmt::{Error, Write};
152 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
156 /// let mut buf = String::new();
157 /// writer(&mut buf, 'a').unwrap();
158 /// writer(&mut buf, 'b').unwrap();
159 /// assert_eq!(&buf, "ab");
161 #[stable(feature = "fmt_write_char", since = "1.1.0")]
162 fn write_char(&mut self, c: char) -> Result {
163 self.write_str(c.encode_utf8(&mut [0; 4]))
166 /// Glue for usage of the [`write!`] macro with implementors of this trait.
168 /// This method should generally not be invoked manually, but rather through
169 /// the [`write!`] macro itself.
174 /// use std::fmt::{Error, Write};
176 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
177 /// f.write_fmt(format_args!("{}", s))
180 /// let mut buf = String::new();
181 /// writer(&mut buf, "world").unwrap();
182 /// assert_eq!(&buf, "world");
184 #[stable(feature = "rust1", since = "1.0.0")]
185 fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
186 write(&mut self, args)
190 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
191 impl<W: Write + ?Sized> Write for &mut W {
192 fn write_str(&mut self, s: &str) -> Result {
193 (**self).write_str(s)
196 fn write_char(&mut self, c: char) -> Result {
197 (**self).write_char(c)
200 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
201 (**self).write_fmt(args)
205 /// Configuration for formatting.
207 /// A `Formatter` represents various options related to formatting. Users do not
208 /// construct `Formatter`s directly; a mutable reference to one is passed to
209 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
211 /// To interact with a `Formatter`, you'll call various methods to change the
212 /// various options related to formatting. For examples, please see the
213 /// documentation of the methods defined on `Formatter` below.
214 #[allow(missing_debug_implementations)]
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub struct Formatter<'a> {
219 align: rt::v1::Alignment,
220 width: Option<usize>,
221 precision: Option<usize>,
223 buf: &'a mut (dyn Write + 'a),
226 impl<'a> Formatter<'a> {
227 /// Creates a new formatter with default settings.
229 /// This can be used as a micro-optimization in cases where a full `Arguments`
230 /// structure (as created by `format_args!`) is not necessary; `Arguments`
231 /// is a little more expensive to use in simple formatting scenarios.
233 /// Currently not intended for use outside of the standard library.
234 #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
236 pub fn new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
240 align: rt::v1::Alignment::Unknown,
248 // NB. Argument is essentially an optimized partially applied formatting function,
249 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
255 /// This struct represents the generic "argument" which is taken by the Xprintf
256 /// family of functions. It contains a function to format the given value. At
257 /// compile time it is ensured that the function and the value have the correct
258 /// types, and then this struct is used to canonicalize arguments to one type.
259 #[derive(Copy, Clone)]
260 #[allow(missing_debug_implementations)]
261 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
263 pub struct ArgumentV1<'a> {
265 formatter: fn(&Opaque, &mut Formatter<'_>) -> Result,
268 /// This struct represents the unsafety of constructing an `Arguments`.
269 /// It exists, rather than an unsafe function, in order to simplify the expansion
270 /// of `format_args!(..)` and reduce the scope of the `unsafe` block.
271 #[allow(missing_debug_implementations)]
273 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
274 pub struct UnsafeArg {
279 /// See documentation where `UnsafeArg` is required to know when it is safe to
280 /// create and use `UnsafeArg`.
282 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
284 pub unsafe fn new() -> Self {
285 Self { _private: () }
289 // This guarantees a single stable value for the function pointer associated with
290 // indices/counts in the formatting infrastructure.
292 // Note that a function defined as such would not be correct as functions are
293 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
294 // address is not considered important to LLVM and as such the as_usize cast
295 // could have been miscompiled. In practice, we never call as_usize on non-usize
296 // containing data (as a matter of static generation of the formatting
297 // arguments), so this is merely an additional check.
299 // We primarily want to ensure that the function pointer at `USIZE_MARKER` has
300 // an address corresponding *only* to functions that also take `&usize` as their
301 // first argument. The read_volatile here ensures that we can safely ready out a
302 // usize from the passed reference and that this address does not point at a
303 // non-usize taking function.
304 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
305 static USIZE_MARKER: fn(&usize, &mut Formatter<'_>) -> Result = |ptr, _| {
306 // SAFETY: ptr is a reference
307 let _v: usize = unsafe { crate::ptr::read_volatile(ptr) };
311 impl<'a> ArgumentV1<'a> {
313 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
314 pub fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
315 // SAFETY: `mem::transmute(x)` is safe because
316 // 1. `&'b T` keeps the lifetime it originated with `'b`
317 // (so as to not have an unbounded lifetime)
318 // 2. `&'b T` and `&'b Opaque` have the same memory layout
319 // (when `T` is `Sized`, as it is here)
320 // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
321 // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
322 // (as long as `T` is `Sized`)
323 unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) } }
327 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
328 pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
329 ArgumentV1::new(x, USIZE_MARKER)
332 fn as_usize(&self) -> Option<usize> {
333 if self.formatter as usize == USIZE_MARKER as usize {
334 // SAFETY: The `formatter` field is only set to USIZE_MARKER if
335 // the value is a usize, so this is safe
336 Some(unsafe { *(self.value as *const _ as *const usize) })
343 // flags available in the v1 format of format_args
344 #[derive(Copy, Clone)]
354 impl<'a> Arguments<'a> {
355 /// When using the format_args!() macro, this function is used to generate the
356 /// Arguments structure.
359 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
360 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
361 pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
362 if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
363 panic!("invalid args");
365 Arguments { pieces, fmt: None, args }
368 /// This function is used to specify nonstandard formatting parameters.
370 /// An `UnsafeArg` is required because the following invariants must be held
371 /// in order for this function to be safe:
372 /// 1. The `pieces` slice must be at least as long as `fmt`.
373 /// 2. Every [`rt::v1::Argument::position`] value within `fmt` must be a
374 /// valid index of `args`.
375 /// 3. Every [`Count::Param`] within `fmt` must contain a valid index of
379 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
380 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
381 pub const fn new_v1_formatted(
382 pieces: &'a [&'static str],
383 args: &'a [ArgumentV1<'a>],
384 fmt: &'a [rt::v1::Argument],
385 _unsafe_arg: UnsafeArg,
387 Arguments { pieces, fmt: Some(fmt), args }
390 /// Estimates the length of the formatted text.
392 /// This is intended to be used for setting initial `String` capacity
393 /// when using `format!`. Note: this is neither the lower nor upper bound.
396 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
397 pub fn estimated_capacity(&self) -> usize {
398 let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
400 if self.args.is_empty() {
402 } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
403 // If the format string starts with an argument,
404 // don't preallocate anything, unless length
405 // of pieces is significant.
408 // There are some arguments, so any additional push
409 // will reallocate the string. To avoid that,
410 // we're "pre-doubling" the capacity here.
411 pieces_length.checked_mul(2).unwrap_or(0)
416 /// This structure represents a safely precompiled version of a format string
417 /// and its arguments. This cannot be generated at runtime because it cannot
418 /// safely be done, so no constructors are given and the fields are private
419 /// to prevent modification.
421 /// The [`format_args!`] macro will safely create an instance of this structure.
422 /// The macro validates the format string at compile-time so usage of the
423 /// [`write()`] and [`format()`] functions can be safely performed.
425 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
426 /// and `Display` contexts as seen below. The example also shows that `Debug`
427 /// and `Display` format to the same thing: the interpolated format string
428 /// in `format_args!`.
431 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
432 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
433 /// assert_eq!("1 foo 2", display);
434 /// assert_eq!(display, debug);
437 /// [`format()`]: ../../std/fmt/fn.format.html
438 #[stable(feature = "rust1", since = "1.0.0")]
439 #[derive(Copy, Clone)]
440 pub struct Arguments<'a> {
441 // Format string pieces to print.
442 pieces: &'a [&'static str],
444 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
445 fmt: Option<&'a [rt::v1::Argument]>,
447 // Dynamic arguments for interpolation, to be interleaved with string
448 // pieces. (Every argument is preceded by a string piece.)
449 args: &'a [ArgumentV1<'a>],
452 impl<'a> Arguments<'a> {
453 /// Get the formatted string, if it has no arguments to be formatted.
455 /// This can be used to avoid allocations in the most trivial case.
460 /// use std::fmt::Arguments;
462 /// fn write_str(_: &str) { /* ... */ }
464 /// fn write_fmt(args: &Arguments) {
465 /// if let Some(s) = args.as_str() {
468 /// write_str(&args.to_string());
474 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
475 /// assert_eq!(format_args!("").as_str(), Some(""));
476 /// assert_eq!(format_args!("{}", 1).as_str(), None);
478 #[stable(feature = "fmt_as_str", since = "1.52.0")]
479 #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "none")]
482 pub const fn as_str(&self) -> Option<&'static str> {
483 match (self.pieces, self.args) {
484 ([], []) => Some(""),
485 ([s], []) => Some(s),
491 #[stable(feature = "rust1", since = "1.0.0")]
492 impl Debug for Arguments<'_> {
493 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
494 Display::fmt(self, fmt)
498 #[stable(feature = "rust1", since = "1.0.0")]
499 impl Display for Arguments<'_> {
500 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
501 write(fmt.buf, *self)
507 /// `Debug` should format the output in a programmer-facing, debugging context.
509 /// Generally speaking, you should just `derive` a `Debug` implementation.
511 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
513 /// For more information on formatters, see [the module-level documentation][module].
515 /// [module]: ../../std/fmt/index.html
517 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
518 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
519 /// comma-separated list of each field's name and `Debug` value, then `}`. For
520 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
521 /// `Debug` values of the fields, then `)`.
525 /// Derived `Debug` formats are not stable, and so may change with future Rust
526 /// versions. Additionally, `Debug` implementations of types provided by the
527 /// standard library (`libstd`, `libcore`, `liballoc`, etc.) are not stable, and
528 /// may also change with future Rust versions.
532 /// Deriving an implementation:
541 /// let origin = Point { x: 0, y: 0 };
543 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
546 /// Manually implementing:
556 /// impl fmt::Debug for Point {
557 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
558 /// f.debug_struct("Point")
559 /// .field("x", &self.x)
560 /// .field("y", &self.y)
565 /// let origin = Point { x: 0, y: 0 };
567 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
570 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
571 /// implementations, such as [`debug_struct`].
573 /// [`debug_struct`]: Formatter::debug_struct
575 /// Types that do not wish to use the standard suite of debug representations
576 /// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
577 /// `debut_list`, `debug_set`, `debug_map`) can do something totally custom by
578 /// manually writing an arbitrary representation to the `Formatter`.
587 /// impl fmt::Debug for Point {
588 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589 /// write!(f, "Point [{} {}]", self.x, self.y)
594 /// `Debug` implementations using either `derive` or the debug builder API
595 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
597 /// Pretty-printing with `#?`:
606 /// let origin = Point { x: 0, y: 0 };
608 /// assert_eq!(format!("The origin is: {:#?}", origin),
609 /// "The origin is: Point {
615 #[stable(feature = "rust1", since = "1.0.0")]
616 #[rustc_on_unimplemented(
619 label = "`{Self}` cannot be formatted using `{{:?}}`",
620 note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
622 message = "`{Self}` doesn't implement `{Debug}`",
623 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
625 #[doc(alias = "{:?}")]
626 #[rustc_diagnostic_item = "Debug"]
627 #[rustc_trivial_field_reads]
629 /// Formats the value using the given formatter.
636 /// struct Position {
641 /// impl fmt::Debug for Position {
642 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643 /// f.debug_tuple("")
644 /// .field(&self.longitude)
645 /// .field(&self.latitude)
650 /// let position = Position { longitude: 1.987, latitude: 2.983 };
651 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
653 /// assert_eq!(format!("{:#?}", position), "(
658 #[stable(feature = "rust1", since = "1.0.0")]
659 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
662 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
663 pub(crate) mod macros {
664 /// Derive macro generating an impl of the trait `Debug`.
665 #[rustc_builtin_macro]
666 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
667 #[allow_internal_unstable(core_intrinsics)]
668 pub macro Debug($item:item) {
669 /* compiler built-in */
672 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
674 pub use macros::Debug;
676 /// Format trait for an empty format, `{}`.
678 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
679 /// output, and so cannot be derived.
681 /// For more information on formatters, see [the module-level documentation][module].
683 /// [module]: ../../std/fmt/index.html
687 /// Implementing `Display` on a type:
697 /// impl fmt::Display for Point {
698 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699 /// write!(f, "({}, {})", self.x, self.y)
703 /// let origin = Point { x: 0, y: 0 };
705 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
707 #[rustc_on_unimplemented(
709 _Self = "std::path::Path",
710 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
711 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
712 as they may contain non-Unicode data"
714 message = "`{Self}` doesn't implement `{Display}`",
715 label = "`{Self}` cannot be formatted with the default formatter",
716 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
719 #[rustc_diagnostic_item = "Display"]
720 #[stable(feature = "rust1", since = "1.0.0")]
722 /// Formats the value using the given formatter.
729 /// struct Position {
734 /// impl fmt::Display for Position {
735 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736 /// write!(f, "({}, {})", self.longitude, self.latitude)
740 /// assert_eq!("(1.987, 2.983)",
741 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
743 #[stable(feature = "rust1", since = "1.0.0")]
744 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
749 /// The `Octal` trait should format its output as a number in base-8.
751 /// For primitive signed integers (`i8` to `i128`, and `isize`),
752 /// negative values are formatted as the two’s complement representation.
754 /// The alternate flag, `#`, adds a `0o` in front of the output.
756 /// For more information on formatters, see [the module-level documentation][module].
758 /// [module]: ../../std/fmt/index.html
762 /// Basic usage with `i32`:
765 /// let x = 42; // 42 is '52' in octal
767 /// assert_eq!(format!("{:o}", x), "52");
768 /// assert_eq!(format!("{:#o}", x), "0o52");
770 /// assert_eq!(format!("{:o}", -16), "37777777760");
773 /// Implementing `Octal` on a type:
778 /// struct Length(i32);
780 /// impl fmt::Octal for Length {
781 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
782 /// let val = self.0;
784 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
788 /// let l = Length(9);
790 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
792 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
794 #[stable(feature = "rust1", since = "1.0.0")]
796 /// Formats the value using the given formatter.
797 #[stable(feature = "rust1", since = "1.0.0")]
798 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
803 /// The `Binary` trait should format its output as a number in binary.
805 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
806 /// negative values are formatted as the two’s complement representation.
808 /// The alternate flag, `#`, adds a `0b` in front of the output.
810 /// For more information on formatters, see [the module-level documentation][module].
812 /// [module]: ../../std/fmt/index.html
816 /// Basic usage with [`i32`]:
819 /// let x = 42; // 42 is '101010' in binary
821 /// assert_eq!(format!("{:b}", x), "101010");
822 /// assert_eq!(format!("{:#b}", x), "0b101010");
824 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
827 /// Implementing `Binary` on a type:
832 /// struct Length(i32);
834 /// impl fmt::Binary for Length {
835 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
836 /// let val = self.0;
838 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
842 /// let l = Length(107);
844 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
847 /// format!("l as binary is: {:#032b}", l),
848 /// "l as binary is: 0b000000000000000000000001101011"
851 #[stable(feature = "rust1", since = "1.0.0")]
853 /// Formats the value using the given formatter.
854 #[stable(feature = "rust1", since = "1.0.0")]
855 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
860 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
863 /// For primitive signed integers (`i8` to `i128`, and `isize`),
864 /// negative values are formatted as the two’s complement representation.
866 /// The alternate flag, `#`, adds a `0x` in front of the output.
868 /// For more information on formatters, see [the module-level documentation][module].
870 /// [module]: ../../std/fmt/index.html
874 /// Basic usage with `i32`:
877 /// let x = 42; // 42 is '2a' in hex
879 /// assert_eq!(format!("{:x}", x), "2a");
880 /// assert_eq!(format!("{:#x}", x), "0x2a");
882 /// assert_eq!(format!("{:x}", -16), "fffffff0");
885 /// Implementing `LowerHex` on a type:
890 /// struct Length(i32);
892 /// impl fmt::LowerHex for Length {
893 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
894 /// let val = self.0;
896 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
900 /// let l = Length(9);
902 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
904 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
906 #[stable(feature = "rust1", since = "1.0.0")]
908 /// Formats the value using the given formatter.
909 #[stable(feature = "rust1", since = "1.0.0")]
910 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
915 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
918 /// For primitive signed integers (`i8` to `i128`, and `isize`),
919 /// negative values are formatted as the two’s complement representation.
921 /// The alternate flag, `#`, adds a `0x` in front of the output.
923 /// For more information on formatters, see [the module-level documentation][module].
925 /// [module]: ../../std/fmt/index.html
929 /// Basic usage with `i32`:
932 /// let x = 42; // 42 is '2A' in hex
934 /// assert_eq!(format!("{:X}", x), "2A");
935 /// assert_eq!(format!("{:#X}", x), "0x2A");
937 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
940 /// Implementing `UpperHex` on a type:
945 /// struct Length(i32);
947 /// impl fmt::UpperHex for Length {
948 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
949 /// let val = self.0;
951 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
955 /// let l = Length(i32::MAX);
957 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
959 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
961 #[stable(feature = "rust1", since = "1.0.0")]
963 /// Formats the value using the given formatter.
964 #[stable(feature = "rust1", since = "1.0.0")]
965 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
970 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
973 /// For more information on formatters, see [the module-level documentation][module].
975 /// [module]: ../../std/fmt/index.html
979 /// Basic usage with `&i32`:
984 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
987 /// Implementing `Pointer` on a type:
992 /// struct Length(i32);
994 /// impl fmt::Pointer for Length {
995 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
996 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
998 /// let ptr = self as *const Self;
999 /// fmt::Pointer::fmt(&ptr, f)
1003 /// let l = Length(42);
1005 /// println!("l is in memory here: {:p}", l);
1007 /// let l_ptr = format!("{:018p}", l);
1008 /// assert_eq!(l_ptr.len(), 18);
1009 /// assert_eq!(&l_ptr[..2], "0x");
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 #[rustc_diagnostic_item = "Pointer"]
1014 /// Formats the value using the given formatter.
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 #[rustc_diagnostic_item = "pointer_trait_fmt"]
1017 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1022 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1024 /// For more information on formatters, see [the module-level documentation][module].
1026 /// [module]: ../../std/fmt/index.html
1030 /// Basic usage with `f64`:
1033 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1035 /// assert_eq!(format!("{:e}", x), "4.2e1");
1038 /// Implementing `LowerExp` on a type:
1043 /// struct Length(i32);
1045 /// impl fmt::LowerExp for Length {
1046 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1047 /// let val = f64::from(self.0);
1048 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1052 /// let l = Length(100);
1055 /// format!("l in scientific notation is: {:e}", l),
1056 /// "l in scientific notation is: 1e2"
1060 /// format!("l in scientific notation is: {:05e}", l),
1061 /// "l in scientific notation is: 001e2"
1064 #[stable(feature = "rust1", since = "1.0.0")]
1065 pub trait LowerExp {
1066 /// Formats the value using the given formatter.
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1073 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1075 /// For more information on formatters, see [the module-level documentation][module].
1077 /// [module]: ../../std/fmt/index.html
1081 /// Basic usage with `f64`:
1084 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1086 /// assert_eq!(format!("{:E}", x), "4.2E1");
1089 /// Implementing `UpperExp` on a type:
1094 /// struct Length(i32);
1096 /// impl fmt::UpperExp for Length {
1097 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1098 /// let val = f64::from(self.0);
1099 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1103 /// let l = Length(100);
1106 /// format!("l in scientific notation is: {:E}", l),
1107 /// "l in scientific notation is: 1E2"
1111 /// format!("l in scientific notation is: {:05E}", l),
1112 /// "l in scientific notation is: 001E2"
1115 #[stable(feature = "rust1", since = "1.0.0")]
1116 pub trait UpperExp {
1117 /// Formats the value using the given formatter.
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1122 /// The `write` function takes an output stream, and an `Arguments` struct
1123 /// that can be precompiled with the `format_args!` macro.
1125 /// The arguments will be formatted according to the specified format string
1126 /// into the output stream provided.
1135 /// let mut output = String::new();
1136 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1137 /// .expect("Error occurred while trying to write in String");
1138 /// assert_eq!(output, "Hello world!");
1141 /// Please note that using [`write!`] might be preferable. Example:
1144 /// use std::fmt::Write;
1146 /// let mut output = String::new();
1147 /// write!(&mut output, "Hello {}!", "world")
1148 /// .expect("Error occurred while trying to write in String");
1149 /// assert_eq!(output, "Hello world!");
1152 /// [`write!`]: crate::write!
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1155 let mut formatter = Formatter::new(output);
1160 // We can use default formatting parameters for all arguments.
1161 for (i, arg) in args.args.iter().enumerate() {
1162 // SAFETY: args.args and args.pieces come from the same Arguments,
1163 // which guarantees the indexes are always within bounds.
1164 let piece = unsafe { args.pieces.get_unchecked(i) };
1165 if !piece.is_empty() {
1166 formatter.buf.write_str(*piece)?;
1168 (arg.formatter)(arg.value, &mut formatter)?;
1173 // Every spec has a corresponding argument that is preceded by
1175 for (i, arg) in fmt.iter().enumerate() {
1176 // SAFETY: fmt and args.pieces come from the same Arguments,
1177 // which guarantees the indexes are always within bounds.
1178 let piece = unsafe { args.pieces.get_unchecked(i) };
1179 if !piece.is_empty() {
1180 formatter.buf.write_str(*piece)?;
1182 // SAFETY: arg and args.args come from the same Arguments,
1183 // which guarantees the indexes are always within bounds.
1184 unsafe { run(&mut formatter, arg, args.args) }?;
1190 // There can be only one trailing string piece left.
1191 if let Some(piece) = args.pieces.get(idx) {
1192 formatter.buf.write_str(*piece)?;
1198 unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1199 fmt.fill = arg.format.fill;
1200 fmt.align = arg.format.align;
1201 fmt.flags = arg.format.flags;
1202 // SAFETY: arg and args come from the same Arguments,
1203 // which guarantees the indexes are always within bounds.
1205 fmt.width = getcount(args, &arg.format.width);
1206 fmt.precision = getcount(args, &arg.format.precision);
1209 // Extract the correct argument
1210 debug_assert!(arg.position < args.len());
1211 // SAFETY: arg and args come from the same Arguments,
1212 // which guarantees its index is always within bounds.
1213 let value = unsafe { args.get_unchecked(arg.position) };
1215 // Then actually do some printing
1216 (value.formatter)(value.value, fmt)
1219 unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1221 rt::v1::Count::Is(n) => Some(n),
1222 rt::v1::Count::Implied => None,
1223 rt::v1::Count::Param(i) => {
1224 debug_assert!(i < args.len());
1225 // SAFETY: cnt and args come from the same Arguments,
1226 // which guarantees this index is always within bounds.
1227 unsafe { args.get_unchecked(i).as_usize() }
1232 /// Padding after the end of something. Returned by `Formatter::padding`.
1233 #[must_use = "don't forget to write the post padding"]
1234 pub(crate) struct PostPadding {
1240 fn new(fill: char, padding: usize) -> PostPadding {
1241 PostPadding { fill, padding }
1244 /// Write this post padding.
1245 pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1246 for _ in 0..self.padding {
1247 f.buf.write_char(self.fill)?;
1253 impl<'a> Formatter<'a> {
1254 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1257 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1260 // We want to change this
1261 buf: wrap(self.buf),
1263 // And preserve these
1268 precision: self.precision,
1272 // Helper methods used for padding and processing formatting arguments that
1273 // all formatting traits can use.
1275 /// Performs the correct padding for an integer which has already been
1276 /// emitted into a str. The str should *not* contain the sign for the
1277 /// integer, that will be added by this method.
1281 /// * is_nonnegative - whether the original integer was either positive or zero.
1282 /// * prefix - if the '#' character (Alternate) is provided, this
1283 /// is the prefix to put in front of the number.
1284 /// * buf - the byte array that the number has been formatted into
1286 /// This function will correctly account for the flags provided as well as
1287 /// the minimum width. It will not take precision into account.
1294 /// struct Foo { nb: i32 }
1297 /// fn new(nb: i32) -> Foo {
1304 /// impl fmt::Display for Foo {
1305 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1306 /// // We need to remove "-" from the number output.
1307 /// let tmp = self.nb.abs().to_string();
1309 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1313 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1314 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1315 /// assert_eq!(&format!("{}", Foo::new(0)), "0");
1316 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1317 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1321 let mut width = buf.len();
1323 let mut sign = None;
1324 if !is_nonnegative {
1327 } else if self.sign_plus() {
1332 let prefix = if self.alternate() {
1333 width += prefix.chars().count();
1339 // Writes the sign if it exists, and then the prefix if it was requested
1341 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1342 if let Some(c) = sign {
1343 f.buf.write_char(c)?;
1345 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1348 // The `width` field is more of a `min-width` parameter at this point.
1350 // If there's no minimum length requirements then we can just
1353 write_prefix(self, sign, prefix)?;
1354 self.buf.write_str(buf)
1356 // Check if we're over the minimum width, if so then we can also
1357 // just write the bytes.
1358 Some(min) if width >= min => {
1359 write_prefix(self, sign, prefix)?;
1360 self.buf.write_str(buf)
1362 // The sign and prefix goes before the padding if the fill character
1364 Some(min) if self.sign_aware_zero_pad() => {
1365 let old_fill = crate::mem::replace(&mut self.fill, '0');
1366 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1367 write_prefix(self, sign, prefix)?;
1368 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1369 self.buf.write_str(buf)?;
1370 post_padding.write(self)?;
1371 self.fill = old_fill;
1372 self.align = old_align;
1375 // Otherwise, the sign and prefix goes after the padding
1377 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1378 write_prefix(self, sign, prefix)?;
1379 self.buf.write_str(buf)?;
1380 post_padding.write(self)
1385 /// This function takes a string slice and emits it to the internal buffer
1386 /// after applying the relevant formatting flags specified. The flags
1387 /// recognized for generic strings are:
1389 /// * width - the minimum width of what to emit
1390 /// * fill/align - what to emit and where to emit it if the string
1391 /// provided needs to be padded
1392 /// * precision - the maximum length to emit, the string is truncated if it
1393 /// is longer than this length
1395 /// Notably this function ignores the `flag` parameters.
1404 /// impl fmt::Display for Foo {
1405 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1406 /// formatter.pad("Foo")
1410 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1411 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 pub fn pad(&mut self, s: &str) -> Result {
1415 // Make sure there's a fast path up front
1416 if self.width.is_none() && self.precision.is_none() {
1417 return self.buf.write_str(s);
1419 // The `precision` field can be interpreted as a `max-width` for the
1420 // string being formatted.
1421 let s = if let Some(max) = self.precision {
1422 // If our string is longer that the precision, then we must have
1423 // truncation. However other flags like `fill`, `width` and `align`
1424 // must act as always.
1425 if let Some((i, _)) = s.char_indices().nth(max) {
1426 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1427 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1428 // `unsafe` and otherwise don't emit any panic-related code
1430 s.get(..i).unwrap_or(s)
1437 // The `width` field is more of a `min-width` parameter at this point.
1439 // If we're under the maximum length, and there's no minimum length
1440 // requirements, then we can just emit the string
1441 None => self.buf.write_str(s),
1443 let chars_count = s.chars().count();
1444 // If we're under the maximum width, check if we're over the minimum
1445 // width, if so it's as easy as just emitting the string.
1446 if chars_count >= width {
1447 self.buf.write_str(s)
1449 // If we're under both the maximum and the minimum width, then fill
1450 // up the minimum width with the specified string + some alignment.
1452 let align = rt::v1::Alignment::Left;
1453 let post_padding = self.padding(width - chars_count, align)?;
1454 self.buf.write_str(s)?;
1455 post_padding.write(self)
1461 /// Write the pre-padding and return the unwritten post-padding. Callers are
1462 /// responsible for ensuring post-padding is written after the thing that is
1464 pub(crate) fn padding(
1467 default: rt::v1::Alignment,
1468 ) -> result::Result<PostPadding, Error> {
1469 let align = match self.align {
1470 rt::v1::Alignment::Unknown => default,
1474 let (pre_pad, post_pad) = match align {
1475 rt::v1::Alignment::Left => (0, padding),
1476 rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1477 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1480 for _ in 0..pre_pad {
1481 self.buf.write_char(self.fill)?;
1484 Ok(PostPadding::new(self.fill, post_pad))
1487 /// Takes the formatted parts and applies the padding.
1488 /// Assumes that the caller already has rendered the parts with required precision,
1489 /// so that `self.precision` can be ignored.
1490 fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1491 if let Some(mut width) = self.width {
1492 // for the sign-aware zero padding, we render the sign first and
1493 // behave as if we had no sign from the beginning.
1494 let mut formatted = formatted.clone();
1495 let old_fill = self.fill;
1496 let old_align = self.align;
1497 let mut align = old_align;
1498 if self.sign_aware_zero_pad() {
1499 // a sign always goes first
1500 let sign = formatted.sign;
1501 self.buf.write_str(sign)?;
1503 // remove the sign from the formatted parts
1504 formatted.sign = "";
1505 width = width.saturating_sub(sign.len());
1506 align = rt::v1::Alignment::Right;
1508 self.align = rt::v1::Alignment::Right;
1511 // remaining parts go through the ordinary padding process.
1512 let len = formatted.len();
1513 let ret = if width <= len {
1515 self.write_formatted_parts(&formatted)
1517 let post_padding = self.padding(width - len, align)?;
1518 self.write_formatted_parts(&formatted)?;
1519 post_padding.write(self)
1521 self.fill = old_fill;
1522 self.align = old_align;
1525 // this is the common case and we take a shortcut
1526 self.write_formatted_parts(formatted)
1530 fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1531 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1532 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1533 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1534 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1535 // It's also probably safe in practice to use for `numfmt::Part::Copy(buf)`
1536 // since `buf` should be plain ASCII, but it's possible for someone to pass
1537 // in a bad value for `buf` into `numfmt::to_shortest_str` since it is a
1539 // FIXME: Determine whether this could result in UB.
1540 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1543 if !formatted.sign.is_empty() {
1544 self.buf.write_str(formatted.sign)?;
1546 for part in formatted.parts {
1548 numfmt::Part::Zero(mut nzeroes) => {
1549 const ZEROES: &str = // 64 zeroes
1550 "0000000000000000000000000000000000000000000000000000000000000000";
1551 while nzeroes > ZEROES.len() {
1552 self.buf.write_str(ZEROES)?;
1553 nzeroes -= ZEROES.len();
1556 self.buf.write_str(&ZEROES[..nzeroes])?;
1559 numfmt::Part::Num(mut v) => {
1561 let len = part.len();
1562 for c in s[..len].iter_mut().rev() {
1563 *c = b'0' + (v % 10) as u8;
1566 write_bytes(self.buf, &s[..len])?;
1568 numfmt::Part::Copy(buf) => {
1569 write_bytes(self.buf, buf)?;
1576 /// Writes some data to the underlying buffer contained within this
1586 /// impl fmt::Display for Foo {
1587 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1588 /// formatter.write_str("Foo")
1589 /// // This is equivalent to:
1590 /// // write!(formatter, "Foo")
1594 /// assert_eq!(&format!("{}", Foo), "Foo");
1595 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 pub fn write_str(&mut self, data: &str) -> Result {
1599 self.buf.write_str(data)
1602 /// Writes some formatted information into this instance.
1609 /// struct Foo(i32);
1611 /// impl fmt::Display for Foo {
1612 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1613 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1617 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1618 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1622 write(self.buf, fmt)
1625 /// Flags for formatting
1627 #[stable(feature = "rust1", since = "1.0.0")]
1630 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1631 or `sign_aware_zero_pad` methods instead"
1633 pub fn flags(&self) -> u32 {
1637 /// Character used as 'fill' whenever there is alignment.
1646 /// impl fmt::Display for Foo {
1647 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1648 /// let c = formatter.fill();
1649 /// if let Some(width) = formatter.width() {
1650 /// for _ in 0..width {
1651 /// write!(formatter, "{}", c)?;
1655 /// write!(formatter, "{}", c)
1660 /// // We set alignment to the right with ">".
1661 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1662 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1665 #[stable(feature = "fmt_flags", since = "1.5.0")]
1666 pub fn fill(&self) -> char {
1670 /// Flag indicating what form of alignment was requested.
1675 /// extern crate core;
1677 /// use std::fmt::{self, Alignment};
1681 /// impl fmt::Display for Foo {
1682 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1683 /// let s = if let Some(s) = formatter.align() {
1685 /// Alignment::Left => "left",
1686 /// Alignment::Right => "right",
1687 /// Alignment::Center => "center",
1692 /// write!(formatter, "{}", s)
1696 /// assert_eq!(&format!("{:<}", Foo), "left");
1697 /// assert_eq!(&format!("{:>}", Foo), "right");
1698 /// assert_eq!(&format!("{:^}", Foo), "center");
1699 /// assert_eq!(&format!("{}", Foo), "into the void");
1702 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1703 pub fn align(&self) -> Option<Alignment> {
1705 rt::v1::Alignment::Left => Some(Alignment::Left),
1706 rt::v1::Alignment::Right => Some(Alignment::Right),
1707 rt::v1::Alignment::Center => Some(Alignment::Center),
1708 rt::v1::Alignment::Unknown => None,
1712 /// Optionally specified integer width that the output should be.
1719 /// struct Foo(i32);
1721 /// impl fmt::Display for Foo {
1722 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1723 /// if let Some(width) = formatter.width() {
1724 /// // If we received a width, we use it
1725 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1727 /// // Otherwise we do nothing special
1728 /// write!(formatter, "Foo({})", self.0)
1733 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1734 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1737 #[stable(feature = "fmt_flags", since = "1.5.0")]
1738 pub fn width(&self) -> Option<usize> {
1742 /// Optionally specified precision for numeric types. Alternatively, the
1743 /// maximum width for string types.
1750 /// struct Foo(f32);
1752 /// impl fmt::Display for Foo {
1753 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1754 /// if let Some(precision) = formatter.precision() {
1755 /// // If we received a precision, we use it.
1756 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1758 /// // Otherwise we default to 2.
1759 /// write!(formatter, "Foo({:.2})", self.0)
1764 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1765 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1768 #[stable(feature = "fmt_flags", since = "1.5.0")]
1769 pub fn precision(&self) -> Option<usize> {
1773 /// Determines if the `+` flag was specified.
1780 /// struct Foo(i32);
1782 /// impl fmt::Display for Foo {
1783 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1784 /// if formatter.sign_plus() {
1785 /// write!(formatter,
1787 /// if self.0 < 0 { '-' } else { '+' },
1790 /// write!(formatter, "Foo({})", self.0)
1795 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1796 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1799 #[stable(feature = "fmt_flags", since = "1.5.0")]
1800 pub fn sign_plus(&self) -> bool {
1801 self.flags & (1 << FlagV1::SignPlus as u32) != 0
1804 /// Determines if the `-` flag was specified.
1811 /// struct Foo(i32);
1813 /// impl fmt::Display for Foo {
1814 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1815 /// if formatter.sign_minus() {
1816 /// // You want a minus sign? Have one!
1817 /// write!(formatter, "-Foo({})", self.0)
1819 /// write!(formatter, "Foo({})", self.0)
1824 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1825 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1828 #[stable(feature = "fmt_flags", since = "1.5.0")]
1829 pub fn sign_minus(&self) -> bool {
1830 self.flags & (1 << FlagV1::SignMinus as u32) != 0
1833 /// Determines if the `#` flag was specified.
1840 /// struct Foo(i32);
1842 /// impl fmt::Display for Foo {
1843 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1844 /// if formatter.alternate() {
1845 /// write!(formatter, "Foo({})", self.0)
1847 /// write!(formatter, "{}", self.0)
1852 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1853 /// assert_eq!(&format!("{}", Foo(23)), "23");
1856 #[stable(feature = "fmt_flags", since = "1.5.0")]
1857 pub fn alternate(&self) -> bool {
1858 self.flags & (1 << FlagV1::Alternate as u32) != 0
1861 /// Determines if the `0` flag was specified.
1868 /// struct Foo(i32);
1870 /// impl fmt::Display for Foo {
1871 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1872 /// assert!(formatter.sign_aware_zero_pad());
1873 /// assert_eq!(formatter.width(), Some(4));
1874 /// // We ignore the formatter's options.
1875 /// write!(formatter, "{}", self.0)
1879 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1882 #[stable(feature = "fmt_flags", since = "1.5.0")]
1883 pub fn sign_aware_zero_pad(&self) -> bool {
1884 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1887 // FIXME: Decide what public API we want for these two flags.
1888 // https://github.com/rust-lang/rust/issues/48584
1889 fn debug_lower_hex(&self) -> bool {
1890 self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1893 fn debug_upper_hex(&self) -> bool {
1894 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1897 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1898 /// [`fmt::Debug`] implementations for structs.
1900 /// [`fmt::Debug`]: self::Debug
1906 /// use std::net::Ipv4Addr;
1914 /// impl fmt::Debug for Foo {
1915 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1916 /// fmt.debug_struct("Foo")
1917 /// .field("bar", &self.bar)
1918 /// .field("baz", &self.baz)
1919 /// .field("addr", &format_args!("{}", self.addr))
1925 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1926 /// format!("{:?}", Foo {
1928 /// baz: "Hello World".to_string(),
1929 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1933 #[stable(feature = "debug_builders", since = "1.2.0")]
1934 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1935 builders::debug_struct_new(self, name)
1938 /// Creates a `DebugTuple` builder designed to assist with creation of
1939 /// `fmt::Debug` implementations for tuple structs.
1945 /// use std::marker::PhantomData;
1947 /// struct Foo<T>(i32, String, PhantomData<T>);
1949 /// impl<T> fmt::Debug for Foo<T> {
1950 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1951 /// fmt.debug_tuple("Foo")
1954 /// .field(&format_args!("_"))
1960 /// "Foo(10, \"Hello\", _)",
1961 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1964 #[stable(feature = "debug_builders", since = "1.2.0")]
1965 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1966 builders::debug_tuple_new(self, name)
1969 /// Creates a `DebugList` builder designed to assist with creation of
1970 /// `fmt::Debug` implementations for list-like structures.
1977 /// struct Foo(Vec<i32>);
1979 /// impl fmt::Debug for Foo {
1980 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1981 /// fmt.debug_list().entries(self.0.iter()).finish()
1985 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
1987 #[stable(feature = "debug_builders", since = "1.2.0")]
1988 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1989 builders::debug_list_new(self)
1992 /// Creates a `DebugSet` builder designed to assist with creation of
1993 /// `fmt::Debug` implementations for set-like structures.
2000 /// struct Foo(Vec<i32>);
2002 /// impl fmt::Debug for Foo {
2003 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2004 /// fmt.debug_set().entries(self.0.iter()).finish()
2008 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2011 /// [`format_args!`]: crate::format_args
2013 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2014 /// to build a list of match arms:
2019 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
2020 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
2022 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2024 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
2026 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2027 /// L::fmt(&(self.0).0, fmt)?;
2028 /// fmt.write_str(" => ")?;
2029 /// R::fmt(&(self.0).1, fmt)
2033 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2035 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
2037 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2039 /// .entries(self.0.iter().map(Arm))
2040 /// .entry(&Arm(&(format_args!("_"), &self.1)))
2045 #[stable(feature = "debug_builders", since = "1.2.0")]
2046 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2047 builders::debug_set_new(self)
2050 /// Creates a `DebugMap` builder designed to assist with creation of
2051 /// `fmt::Debug` implementations for map-like structures.
2058 /// struct Foo(Vec<(String, i32)>);
2060 /// impl fmt::Debug for Foo {
2061 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2062 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2067 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2068 /// r#"{"A": 10, "B": 11}"#
2071 #[stable(feature = "debug_builders", since = "1.2.0")]
2072 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2073 builders::debug_map_new(self)
2077 #[stable(since = "1.2.0", feature = "formatter_write")]
2078 impl Write for Formatter<'_> {
2079 fn write_str(&mut self, s: &str) -> Result {
2080 self.buf.write_str(s)
2083 fn write_char(&mut self, c: char) -> Result {
2084 self.buf.write_char(c)
2087 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2088 write(self.buf, args)
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 impl Display for Error {
2094 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2095 Display::fmt("an error occurred when formatting an argument", f)
2099 // Implementations of the core formatting traits
2101 macro_rules! fmt_refs {
2102 ($($tr:ident),*) => {
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 impl<T: ?Sized + $tr> $tr for &T {
2106 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2108 #[stable(feature = "rust1", since = "1.0.0")]
2109 impl<T: ?Sized + $tr> $tr for &mut T {
2110 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2116 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2118 #[unstable(feature = "never_type", issue = "35121")]
2120 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2125 #[unstable(feature = "never_type", issue = "35121")]
2126 impl Display for ! {
2127 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 impl Debug for bool {
2135 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2136 Display::fmt(self, f)
2140 #[stable(feature = "rust1", since = "1.0.0")]
2141 impl Display for bool {
2142 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2143 Display::fmt(if *self { "true" } else { "false" }, f)
2147 #[stable(feature = "rust1", since = "1.0.0")]
2148 impl Debug for str {
2149 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2152 for (i, c) in self.char_indices() {
2153 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2154 escape_grapheme_extended: true,
2155 escape_single_quote: false,
2156 escape_double_quote: true,
2158 // If char needs escaping, flush backlog so far and write, else skip
2160 f.write_str(&self[from..i])?;
2164 from = i + c.len_utf8();
2167 f.write_str(&self[from..])?;
2172 #[stable(feature = "rust1", since = "1.0.0")]
2173 impl Display for str {
2174 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2179 #[stable(feature = "rust1", since = "1.0.0")]
2180 impl Debug for char {
2181 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2182 f.write_char('\'')?;
2183 for c in self.escape_debug_ext(EscapeDebugExtArgs {
2184 escape_grapheme_extended: true,
2185 escape_single_quote: true,
2186 escape_double_quote: false,
2194 #[stable(feature = "rust1", since = "1.0.0")]
2195 impl Display for char {
2196 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2197 if f.width.is_none() && f.precision.is_none() {
2200 f.pad(self.encode_utf8(&mut [0; 4]))
2205 #[stable(feature = "rust1", since = "1.0.0")]
2206 impl<T: ?Sized> Pointer for *const T {
2207 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2208 /// Since the formatting will be identical for all pointer types, use a non-monomorphized
2209 /// implementation for the actual formatting to reduce the amount of codegen work needed
2210 fn inner(ptr: *const (), f: &mut Formatter<'_>) -> Result {
2211 let old_width = f.width;
2212 let old_flags = f.flags;
2214 // The alternate flag is already treated by LowerHex as being special-
2215 // it denotes whether to prefix with 0x. We use it to work out whether
2216 // or not to zero extend, and then unconditionally set it to get the
2219 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2221 if f.width.is_none() {
2222 f.width = Some((usize::BITS / 4) as usize + 2);
2225 f.flags |= 1 << (FlagV1::Alternate as u32);
2227 let ret = LowerHex::fmt(&(ptr as usize), f);
2229 f.width = old_width;
2230 f.flags = old_flags;
2235 inner(*self as *const (), f)
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 impl<T: ?Sized> Pointer for *mut T {
2241 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2242 Pointer::fmt(&(*self as *const T), f)
2246 #[stable(feature = "rust1", since = "1.0.0")]
2247 impl<T: ?Sized> Pointer for &T {
2248 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2249 Pointer::fmt(&(*self as *const T), f)
2253 #[stable(feature = "rust1", since = "1.0.0")]
2254 impl<T: ?Sized> Pointer for &mut T {
2255 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2256 Pointer::fmt(&(&**self as *const T), f)
2260 // Implementation of Display/Debug for various core types
2262 #[stable(feature = "rust1", since = "1.0.0")]
2263 impl<T: ?Sized> Debug for *const T {
2264 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2265 Pointer::fmt(self, f)
2268 #[stable(feature = "rust1", since = "1.0.0")]
2269 impl<T: ?Sized> Debug for *mut T {
2270 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2271 Pointer::fmt(self, f)
2276 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2279 macro_rules! tuple {
2281 ( $($name:ident,)+ ) => (
2282 #[stable(feature = "rust1", since = "1.0.0")]
2283 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2284 #[allow(non_snake_case, unused_assignments)]
2285 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2286 let mut builder = f.debug_tuple("");
2287 let ($(ref $name,)+) = *self;
2289 builder.field(&$name);
2295 peel! { $($name,)+ }
2299 macro_rules! last_type {
2300 ($a:ident,) => { $a };
2301 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2304 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2306 #[stable(feature = "rust1", since = "1.0.0")]
2307 impl<T: Debug> Debug for [T] {
2308 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2309 f.debug_list().entries(self.iter()).finish()
2313 #[stable(feature = "rust1", since = "1.0.0")]
2316 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2320 #[stable(feature = "rust1", since = "1.0.0")]
2321 impl<T: ?Sized> Debug for PhantomData<T> {
2322 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2323 f.debug_struct("PhantomData").finish()
2327 #[stable(feature = "rust1", since = "1.0.0")]
2328 impl<T: Copy + Debug> Debug for Cell<T> {
2329 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2330 f.debug_struct("Cell").field("value", &self.get()).finish()
2334 #[stable(feature = "rust1", since = "1.0.0")]
2335 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2336 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2337 match self.try_borrow() {
2338 Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2340 // The RefCell is mutably borrowed so we can't look at its value
2341 // here. Show a placeholder instead.
2342 struct BorrowedPlaceholder;
2344 impl Debug for BorrowedPlaceholder {
2345 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2346 f.write_str("<borrowed>")
2350 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2358 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2359 Debug::fmt(&**self, f)
2363 #[stable(feature = "rust1", since = "1.0.0")]
2364 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2365 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2366 Debug::fmt(&*(self.deref()), f)
2370 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2371 impl<T: ?Sized> Debug for UnsafeCell<T> {
2372 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2373 f.debug_struct("UnsafeCell").finish_non_exhaustive()
2377 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2378 // it's a lot easier than creating all of the rt::Piece structures here.
2379 // There are also tests in the alloc crate, for those that need allocations.