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 macro_rules! arg_new {
312 ($f: ident, $t: ident) => {
314 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
316 pub fn $f<'b, T: $t>(x: &'b T) -> ArgumentV1<'_> {
317 Self::new(x, $t::fmt)
322 impl<'a> ArgumentV1<'a> {
324 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
326 pub fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
327 // SAFETY: `mem::transmute(x)` is safe because
328 // 1. `&'b T` keeps the lifetime it originated with `'b`
329 // (so as to not have an unbounded lifetime)
330 // 2. `&'b T` and `&'b Opaque` have the same memory layout
331 // (when `T` is `Sized`, as it is here)
332 // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
333 // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
334 // (as long as `T` is `Sized`)
335 unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) } }
338 arg_new!(new_display, Display);
339 arg_new!(new_debug, Debug);
340 arg_new!(new_octal, Octal);
341 arg_new!(new_lower_hex, LowerHex);
342 arg_new!(new_upper_hex, UpperHex);
343 arg_new!(new_pointer, Pointer);
344 arg_new!(new_binary, Binary);
345 arg_new!(new_lower_exp, LowerExp);
346 arg_new!(new_upper_exp, UpperExp);
349 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
350 pub fn from_usize(x: &usize) -> ArgumentV1<'_> {
351 ArgumentV1::new(x, USIZE_MARKER)
354 fn as_usize(&self) -> Option<usize> {
355 if self.formatter as usize == USIZE_MARKER as usize {
356 // SAFETY: The `formatter` field is only set to USIZE_MARKER if
357 // the value is a usize, so this is safe
358 Some(unsafe { *(self.value as *const _ as *const usize) })
365 // flags available in the v1 format of format_args
366 #[derive(Copy, Clone)]
376 impl<'a> Arguments<'a> {
377 /// When using the format_args!() macro, this function is used to generate the
378 /// Arguments structure.
381 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
382 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
383 pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
384 if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
385 panic!("invalid args");
387 Arguments { pieces, fmt: None, args }
390 /// This function is used to specify nonstandard formatting parameters.
392 /// An `UnsafeArg` is required because the following invariants must be held
393 /// in order for this function to be safe:
394 /// 1. The `pieces` slice must be at least as long as `fmt`.
395 /// 2. Every [`rt::v1::Argument::position`] value within `fmt` must be a
396 /// valid index of `args`.
397 /// 3. Every [`Count::Param`] within `fmt` must contain a valid index of
401 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
402 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
403 pub const fn new_v1_formatted(
404 pieces: &'a [&'static str],
405 args: &'a [ArgumentV1<'a>],
406 fmt: &'a [rt::v1::Argument],
407 _unsafe_arg: UnsafeArg,
409 Arguments { pieces, fmt: Some(fmt), args }
412 /// Estimates the length of the formatted text.
414 /// This is intended to be used for setting initial `String` capacity
415 /// when using `format!`. Note: this is neither the lower nor upper bound.
418 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
419 pub fn estimated_capacity(&self) -> usize {
420 let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
422 if self.args.is_empty() {
424 } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
425 // If the format string starts with an argument,
426 // don't preallocate anything, unless length
427 // of pieces is significant.
430 // There are some arguments, so any additional push
431 // will reallocate the string. To avoid that,
432 // we're "pre-doubling" the capacity here.
433 pieces_length.checked_mul(2).unwrap_or(0)
438 /// This structure represents a safely precompiled version of a format string
439 /// and its arguments. This cannot be generated at runtime because it cannot
440 /// safely be done, so no constructors are given and the fields are private
441 /// to prevent modification.
443 /// The [`format_args!`] macro will safely create an instance of this structure.
444 /// The macro validates the format string at compile-time so usage of the
445 /// [`write()`] and [`format()`] functions can be safely performed.
447 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
448 /// and `Display` contexts as seen below. The example also shows that `Debug`
449 /// and `Display` format to the same thing: the interpolated format string
450 /// in `format_args!`.
453 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
454 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
455 /// assert_eq!("1 foo 2", display);
456 /// assert_eq!(display, debug);
459 /// [`format()`]: ../../std/fmt/fn.format.html
460 #[stable(feature = "rust1", since = "1.0.0")]
461 #[derive(Copy, Clone)]
462 pub struct Arguments<'a> {
463 // Format string pieces to print.
464 pieces: &'a [&'static str],
466 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
467 fmt: Option<&'a [rt::v1::Argument]>,
469 // Dynamic arguments for interpolation, to be interleaved with string
470 // pieces. (Every argument is preceded by a string piece.)
471 args: &'a [ArgumentV1<'a>],
474 impl<'a> Arguments<'a> {
475 /// Get the formatted string, if it has no arguments to be formatted.
477 /// This can be used to avoid allocations in the most trivial case.
482 /// use std::fmt::Arguments;
484 /// fn write_str(_: &str) { /* ... */ }
486 /// fn write_fmt(args: &Arguments) {
487 /// if let Some(s) = args.as_str() {
490 /// write_str(&args.to_string());
496 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
497 /// assert_eq!(format_args!("").as_str(), Some(""));
498 /// assert_eq!(format_args!("{}", 1).as_str(), None);
500 #[stable(feature = "fmt_as_str", since = "1.52.0")]
501 #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "none")]
504 pub const fn as_str(&self) -> Option<&'static str> {
505 match (self.pieces, self.args) {
506 ([], []) => Some(""),
507 ([s], []) => Some(s),
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl Debug for Arguments<'_> {
515 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
516 Display::fmt(self, fmt)
520 #[stable(feature = "rust1", since = "1.0.0")]
521 impl Display for Arguments<'_> {
522 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
523 write(fmt.buf, *self)
529 /// `Debug` should format the output in a programmer-facing, debugging context.
531 /// Generally speaking, you should just `derive` a `Debug` implementation.
533 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
535 /// For more information on formatters, see [the module-level documentation][module].
537 /// [module]: ../../std/fmt/index.html
539 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
540 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
541 /// comma-separated list of each field's name and `Debug` value, then `}`. For
542 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
543 /// `Debug` values of the fields, then `)`.
547 /// Derived `Debug` formats are not stable, and so may change with future Rust
548 /// versions. Additionally, `Debug` implementations of types provided by the
549 /// standard library (`libstd`, `libcore`, `liballoc`, etc.) are not stable, and
550 /// may also change with future Rust versions.
554 /// Deriving an implementation:
563 /// let origin = Point { x: 0, y: 0 };
565 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
568 /// Manually implementing:
578 /// impl fmt::Debug for Point {
579 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
580 /// f.debug_struct("Point")
581 /// .field("x", &self.x)
582 /// .field("y", &self.y)
587 /// let origin = Point { x: 0, y: 0 };
589 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
592 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
593 /// implementations, such as [`debug_struct`].
595 /// [`debug_struct`]: Formatter::debug_struct
597 /// Types that do not wish to use the standard suite of debug representations
598 /// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
599 /// `debut_list`, `debug_set`, `debug_map`) can do something totally custom by
600 /// manually writing an arbitrary representation to the `Formatter`.
609 /// impl fmt::Debug for Point {
610 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
611 /// write!(f, "Point [{} {}]", self.x, self.y)
616 /// `Debug` implementations using either `derive` or the debug builder API
617 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
619 /// Pretty-printing with `#?`:
628 /// let origin = Point { x: 0, y: 0 };
630 /// assert_eq!(format!("The origin is: {:#?}", origin),
631 /// "The origin is: Point {
637 #[stable(feature = "rust1", since = "1.0.0")]
638 #[rustc_on_unimplemented(
641 label = "`{Self}` cannot be formatted using `{{:?}}`",
642 note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
644 message = "`{Self}` doesn't implement `{Debug}`",
645 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
647 #[doc(alias = "{:?}")]
648 #[rustc_diagnostic_item = "Debug"]
649 #[rustc_trivial_field_reads]
651 /// Formats the value using the given formatter.
658 /// struct Position {
663 /// impl fmt::Debug for Position {
664 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
665 /// f.debug_tuple("")
666 /// .field(&self.longitude)
667 /// .field(&self.latitude)
672 /// let position = Position { longitude: 1.987, latitude: 2.983 };
673 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
675 /// assert_eq!(format!("{:#?}", position), "(
680 #[stable(feature = "rust1", since = "1.0.0")]
681 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
684 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
685 pub(crate) mod macros {
686 /// Derive macro generating an impl of the trait `Debug`.
687 #[rustc_builtin_macro]
688 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
689 #[allow_internal_unstable(core_intrinsics)]
690 pub macro Debug($item:item) {
691 /* compiler built-in */
694 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
696 pub use macros::Debug;
698 /// Format trait for an empty format, `{}`.
700 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
701 /// output, and so cannot be derived.
703 /// For more information on formatters, see [the module-level documentation][module].
705 /// [module]: ../../std/fmt/index.html
709 /// Implementing `Display` on a type:
719 /// impl fmt::Display for Point {
720 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
721 /// write!(f, "({}, {})", self.x, self.y)
725 /// let origin = Point { x: 0, y: 0 };
727 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
729 #[rustc_on_unimplemented(
731 any(_Self = "std::path::Path", _Self = "std::path::PathBuf"),
732 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
733 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
734 as they may contain non-Unicode data"
736 message = "`{Self}` doesn't implement `{Display}`",
737 label = "`{Self}` cannot be formatted with the default formatter",
738 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
741 #[rustc_diagnostic_item = "Display"]
742 #[stable(feature = "rust1", since = "1.0.0")]
744 /// Formats the value using the given formatter.
751 /// struct Position {
756 /// impl fmt::Display for Position {
757 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
758 /// write!(f, "({}, {})", self.longitude, self.latitude)
762 /// assert_eq!("(1.987, 2.983)",
763 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
765 #[stable(feature = "rust1", since = "1.0.0")]
766 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
771 /// The `Octal` trait should format its output as a number in base-8.
773 /// For primitive signed integers (`i8` to `i128`, and `isize`),
774 /// negative values are formatted as the two’s complement representation.
776 /// The alternate flag, `#`, adds a `0o` in front of the output.
778 /// For more information on formatters, see [the module-level documentation][module].
780 /// [module]: ../../std/fmt/index.html
784 /// Basic usage with `i32`:
787 /// let x = 42; // 42 is '52' in octal
789 /// assert_eq!(format!("{:o}", x), "52");
790 /// assert_eq!(format!("{:#o}", x), "0o52");
792 /// assert_eq!(format!("{:o}", -16), "37777777760");
795 /// Implementing `Octal` on a type:
800 /// struct Length(i32);
802 /// impl fmt::Octal for Length {
803 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
804 /// let val = self.0;
806 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
810 /// let l = Length(9);
812 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
814 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
816 #[stable(feature = "rust1", since = "1.0.0")]
818 /// Formats the value using the given formatter.
819 #[stable(feature = "rust1", since = "1.0.0")]
820 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
825 /// The `Binary` trait should format its output as a number in binary.
827 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
828 /// negative values are formatted as the two’s complement representation.
830 /// The alternate flag, `#`, adds a `0b` in front of the output.
832 /// For more information on formatters, see [the module-level documentation][module].
834 /// [module]: ../../std/fmt/index.html
838 /// Basic usage with [`i32`]:
841 /// let x = 42; // 42 is '101010' in binary
843 /// assert_eq!(format!("{:b}", x), "101010");
844 /// assert_eq!(format!("{:#b}", x), "0b101010");
846 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
849 /// Implementing `Binary` on a type:
854 /// struct Length(i32);
856 /// impl fmt::Binary for Length {
857 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
858 /// let val = self.0;
860 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
864 /// let l = Length(107);
866 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
869 /// format!("l as binary is: {:#032b}", l),
870 /// "l as binary is: 0b000000000000000000000001101011"
873 #[stable(feature = "rust1", since = "1.0.0")]
875 /// Formats the value using the given formatter.
876 #[stable(feature = "rust1", since = "1.0.0")]
877 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
882 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
885 /// For primitive signed integers (`i8` to `i128`, and `isize`),
886 /// negative values are formatted as the two’s complement representation.
888 /// The alternate flag, `#`, adds a `0x` in front of the output.
890 /// For more information on formatters, see [the module-level documentation][module].
892 /// [module]: ../../std/fmt/index.html
896 /// Basic usage with `i32`:
899 /// let x = 42; // 42 is '2a' in hex
901 /// assert_eq!(format!("{:x}", x), "2a");
902 /// assert_eq!(format!("{:#x}", x), "0x2a");
904 /// assert_eq!(format!("{:x}", -16), "fffffff0");
907 /// Implementing `LowerHex` on a type:
912 /// struct Length(i32);
914 /// impl fmt::LowerHex for Length {
915 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916 /// let val = self.0;
918 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
922 /// let l = Length(9);
924 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
926 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
928 #[stable(feature = "rust1", since = "1.0.0")]
930 /// Formats the value using the given formatter.
931 #[stable(feature = "rust1", since = "1.0.0")]
932 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
937 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
940 /// For primitive signed integers (`i8` to `i128`, and `isize`),
941 /// negative values are formatted as the two’s complement representation.
943 /// The alternate flag, `#`, adds a `0x` in front of the output.
945 /// For more information on formatters, see [the module-level documentation][module].
947 /// [module]: ../../std/fmt/index.html
951 /// Basic usage with `i32`:
954 /// let x = 42; // 42 is '2A' in hex
956 /// assert_eq!(format!("{:X}", x), "2A");
957 /// assert_eq!(format!("{:#X}", x), "0x2A");
959 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
962 /// Implementing `UpperHex` on a type:
967 /// struct Length(i32);
969 /// impl fmt::UpperHex for Length {
970 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
971 /// let val = self.0;
973 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
977 /// let l = Length(i32::MAX);
979 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
981 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
983 #[stable(feature = "rust1", since = "1.0.0")]
985 /// Formats the value using the given formatter.
986 #[stable(feature = "rust1", since = "1.0.0")]
987 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
992 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
995 /// For more information on formatters, see [the module-level documentation][module].
997 /// [module]: ../../std/fmt/index.html
1001 /// Basic usage with `&i32`:
1006 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
1009 /// Implementing `Pointer` on a type:
1014 /// struct Length(i32);
1016 /// impl fmt::Pointer for Length {
1017 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1018 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1020 /// let ptr = self as *const Self;
1021 /// fmt::Pointer::fmt(&ptr, f)
1025 /// let l = Length(42);
1027 /// println!("l is in memory here: {:p}", l);
1029 /// let l_ptr = format!("{:018p}", l);
1030 /// assert_eq!(l_ptr.len(), 18);
1031 /// assert_eq!(&l_ptr[..2], "0x");
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 #[rustc_diagnostic_item = "Pointer"]
1036 /// Formats the value using the given formatter.
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 #[rustc_diagnostic_item = "pointer_trait_fmt"]
1039 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1044 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1046 /// For more information on formatters, see [the module-level documentation][module].
1048 /// [module]: ../../std/fmt/index.html
1052 /// Basic usage with `f64`:
1055 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1057 /// assert_eq!(format!("{:e}", x), "4.2e1");
1060 /// Implementing `LowerExp` on a type:
1065 /// struct Length(i32);
1067 /// impl fmt::LowerExp for Length {
1068 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1069 /// let val = f64::from(self.0);
1070 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1074 /// let l = Length(100);
1077 /// format!("l in scientific notation is: {:e}", l),
1078 /// "l in scientific notation is: 1e2"
1082 /// format!("l in scientific notation is: {:05e}", l),
1083 /// "l in scientific notation is: 001e2"
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 pub trait LowerExp {
1088 /// Formats the value using the given formatter.
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1095 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1097 /// For more information on formatters, see [the module-level documentation][module].
1099 /// [module]: ../../std/fmt/index.html
1103 /// Basic usage with `f64`:
1106 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1108 /// assert_eq!(format!("{:E}", x), "4.2E1");
1111 /// Implementing `UpperExp` on a type:
1116 /// struct Length(i32);
1118 /// impl fmt::UpperExp for Length {
1119 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1120 /// let val = f64::from(self.0);
1121 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1125 /// let l = Length(100);
1128 /// format!("l in scientific notation is: {:E}", l),
1129 /// "l in scientific notation is: 1E2"
1133 /// format!("l in scientific notation is: {:05E}", l),
1134 /// "l in scientific notation is: 001E2"
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 pub trait UpperExp {
1139 /// Formats the value using the given formatter.
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1144 /// The `write` function takes an output stream, and an `Arguments` struct
1145 /// that can be precompiled with the `format_args!` macro.
1147 /// The arguments will be formatted according to the specified format string
1148 /// into the output stream provided.
1157 /// let mut output = String::new();
1158 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1159 /// .expect("Error occurred while trying to write in String");
1160 /// assert_eq!(output, "Hello world!");
1163 /// Please note that using [`write!`] might be preferable. Example:
1166 /// use std::fmt::Write;
1168 /// let mut output = String::new();
1169 /// write!(&mut output, "Hello {}!", "world")
1170 /// .expect("Error occurred while trying to write in String");
1171 /// assert_eq!(output, "Hello world!");
1174 /// [`write!`]: crate::write!
1175 #[stable(feature = "rust1", since = "1.0.0")]
1176 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1177 let mut formatter = Formatter::new(output);
1182 // We can use default formatting parameters for all arguments.
1183 for (i, arg) in args.args.iter().enumerate() {
1184 // SAFETY: args.args and args.pieces come from the same Arguments,
1185 // which guarantees the indexes are always within bounds.
1186 let piece = unsafe { args.pieces.get_unchecked(i) };
1187 if !piece.is_empty() {
1188 formatter.buf.write_str(*piece)?;
1190 (arg.formatter)(arg.value, &mut formatter)?;
1195 // Every spec has a corresponding argument that is preceded by
1197 for (i, arg) in fmt.iter().enumerate() {
1198 // SAFETY: fmt and args.pieces come from the same Arguments,
1199 // which guarantees the indexes are always within bounds.
1200 let piece = unsafe { args.pieces.get_unchecked(i) };
1201 if !piece.is_empty() {
1202 formatter.buf.write_str(*piece)?;
1204 // SAFETY: arg and args.args come from the same Arguments,
1205 // which guarantees the indexes are always within bounds.
1206 unsafe { run(&mut formatter, arg, args.args) }?;
1212 // There can be only one trailing string piece left.
1213 if let Some(piece) = args.pieces.get(idx) {
1214 formatter.buf.write_str(*piece)?;
1220 unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1221 fmt.fill = arg.format.fill;
1222 fmt.align = arg.format.align;
1223 fmt.flags = arg.format.flags;
1224 // SAFETY: arg and args come from the same Arguments,
1225 // which guarantees the indexes are always within bounds.
1227 fmt.width = getcount(args, &arg.format.width);
1228 fmt.precision = getcount(args, &arg.format.precision);
1231 // Extract the correct argument
1232 debug_assert!(arg.position < args.len());
1233 // SAFETY: arg and args come from the same Arguments,
1234 // which guarantees its index is always within bounds.
1235 let value = unsafe { args.get_unchecked(arg.position) };
1237 // Then actually do some printing
1238 (value.formatter)(value.value, fmt)
1241 unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1243 rt::v1::Count::Is(n) => Some(n),
1244 rt::v1::Count::Implied => None,
1245 rt::v1::Count::Param(i) => {
1246 debug_assert!(i < args.len());
1247 // SAFETY: cnt and args come from the same Arguments,
1248 // which guarantees this index is always within bounds.
1249 unsafe { args.get_unchecked(i).as_usize() }
1254 /// Padding after the end of something. Returned by `Formatter::padding`.
1255 #[must_use = "don't forget to write the post padding"]
1256 pub(crate) struct PostPadding {
1262 fn new(fill: char, padding: usize) -> PostPadding {
1263 PostPadding { fill, padding }
1266 /// Write this post padding.
1267 pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1268 for _ in 0..self.padding {
1269 f.buf.write_char(self.fill)?;
1275 impl<'a> Formatter<'a> {
1276 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1279 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1282 // We want to change this
1283 buf: wrap(self.buf),
1285 // And preserve these
1290 precision: self.precision,
1294 // Helper methods used for padding and processing formatting arguments that
1295 // all formatting traits can use.
1297 /// Performs the correct padding for an integer which has already been
1298 /// emitted into a str. The str should *not* contain the sign for the
1299 /// integer, that will be added by this method.
1303 /// * is_nonnegative - whether the original integer was either positive or zero.
1304 /// * prefix - if the '#' character (Alternate) is provided, this
1305 /// is the prefix to put in front of the number.
1306 /// * buf - the byte array that the number has been formatted into
1308 /// This function will correctly account for the flags provided as well as
1309 /// the minimum width. It will not take precision into account.
1316 /// struct Foo { nb: i32 }
1319 /// fn new(nb: i32) -> Foo {
1326 /// impl fmt::Display for Foo {
1327 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1328 /// // We need to remove "-" from the number output.
1329 /// let tmp = self.nb.abs().to_string();
1331 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1335 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1336 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1337 /// assert_eq!(&format!("{}", Foo::new(0)), "0");
1338 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1339 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1343 let mut width = buf.len();
1345 let mut sign = None;
1346 if !is_nonnegative {
1349 } else if self.sign_plus() {
1354 let prefix = if self.alternate() {
1355 width += prefix.chars().count();
1361 // Writes the sign if it exists, and then the prefix if it was requested
1363 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1364 if let Some(c) = sign {
1365 f.buf.write_char(c)?;
1367 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1370 // The `width` field is more of a `min-width` parameter at this point.
1372 // If there's no minimum length requirements then we can just
1375 write_prefix(self, sign, prefix)?;
1376 self.buf.write_str(buf)
1378 // Check if we're over the minimum width, if so then we can also
1379 // just write the bytes.
1380 Some(min) if width >= min => {
1381 write_prefix(self, sign, prefix)?;
1382 self.buf.write_str(buf)
1384 // The sign and prefix goes before the padding if the fill character
1386 Some(min) if self.sign_aware_zero_pad() => {
1387 let old_fill = crate::mem::replace(&mut self.fill, '0');
1388 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1389 write_prefix(self, sign, prefix)?;
1390 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1391 self.buf.write_str(buf)?;
1392 post_padding.write(self)?;
1393 self.fill = old_fill;
1394 self.align = old_align;
1397 // Otherwise, the sign and prefix goes after the padding
1399 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1400 write_prefix(self, sign, prefix)?;
1401 self.buf.write_str(buf)?;
1402 post_padding.write(self)
1407 /// This function takes a string slice and emits it to the internal buffer
1408 /// after applying the relevant formatting flags specified. The flags
1409 /// recognized for generic strings are:
1411 /// * width - the minimum width of what to emit
1412 /// * fill/align - what to emit and where to emit it if the string
1413 /// provided needs to be padded
1414 /// * precision - the maximum length to emit, the string is truncated if it
1415 /// is longer than this length
1417 /// Notably this function ignores the `flag` parameters.
1426 /// impl fmt::Display for Foo {
1427 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1428 /// formatter.pad("Foo")
1432 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1433 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 pub fn pad(&mut self, s: &str) -> Result {
1437 // Make sure there's a fast path up front
1438 if self.width.is_none() && self.precision.is_none() {
1439 return self.buf.write_str(s);
1441 // The `precision` field can be interpreted as a `max-width` for the
1442 // string being formatted.
1443 let s = if let Some(max) = self.precision {
1444 // If our string is longer that the precision, then we must have
1445 // truncation. However other flags like `fill`, `width` and `align`
1446 // must act as always.
1447 if let Some((i, _)) = s.char_indices().nth(max) {
1448 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1449 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1450 // `unsafe` and otherwise don't emit any panic-related code
1452 s.get(..i).unwrap_or(s)
1459 // The `width` field is more of a `min-width` parameter at this point.
1461 // If we're under the maximum length, and there's no minimum length
1462 // requirements, then we can just emit the string
1463 None => self.buf.write_str(s),
1465 let chars_count = s.chars().count();
1466 // If we're under the maximum width, check if we're over the minimum
1467 // width, if so it's as easy as just emitting the string.
1468 if chars_count >= width {
1469 self.buf.write_str(s)
1471 // If we're under both the maximum and the minimum width, then fill
1472 // up the minimum width with the specified string + some alignment.
1474 let align = rt::v1::Alignment::Left;
1475 let post_padding = self.padding(width - chars_count, align)?;
1476 self.buf.write_str(s)?;
1477 post_padding.write(self)
1483 /// Write the pre-padding and return the unwritten post-padding. Callers are
1484 /// responsible for ensuring post-padding is written after the thing that is
1486 pub(crate) fn padding(
1489 default: rt::v1::Alignment,
1490 ) -> result::Result<PostPadding, Error> {
1491 let align = match self.align {
1492 rt::v1::Alignment::Unknown => default,
1496 let (pre_pad, post_pad) = match align {
1497 rt::v1::Alignment::Left => (0, padding),
1498 rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1499 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1502 for _ in 0..pre_pad {
1503 self.buf.write_char(self.fill)?;
1506 Ok(PostPadding::new(self.fill, post_pad))
1509 /// Takes the formatted parts and applies the padding.
1510 /// Assumes that the caller already has rendered the parts with required precision,
1511 /// so that `self.precision` can be ignored.
1512 fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1513 if let Some(mut width) = self.width {
1514 // for the sign-aware zero padding, we render the sign first and
1515 // behave as if we had no sign from the beginning.
1516 let mut formatted = formatted.clone();
1517 let old_fill = self.fill;
1518 let old_align = self.align;
1519 let mut align = old_align;
1520 if self.sign_aware_zero_pad() {
1521 // a sign always goes first
1522 let sign = formatted.sign;
1523 self.buf.write_str(sign)?;
1525 // remove the sign from the formatted parts
1526 formatted.sign = "";
1527 width = width.saturating_sub(sign.len());
1528 align = rt::v1::Alignment::Right;
1530 self.align = rt::v1::Alignment::Right;
1533 // remaining parts go through the ordinary padding process.
1534 let len = formatted.len();
1535 let ret = if width <= len {
1537 self.write_formatted_parts(&formatted)
1539 let post_padding = self.padding(width - len, align)?;
1540 self.write_formatted_parts(&formatted)?;
1541 post_padding.write(self)
1543 self.fill = old_fill;
1544 self.align = old_align;
1547 // this is the common case and we take a shortcut
1548 self.write_formatted_parts(formatted)
1552 fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1553 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1554 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1555 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1556 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1557 // It's also probably safe in practice to use for `numfmt::Part::Copy(buf)`
1558 // since `buf` should be plain ASCII, but it's possible for someone to pass
1559 // in a bad value for `buf` into `numfmt::to_shortest_str` since it is a
1561 // FIXME: Determine whether this could result in UB.
1562 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1565 if !formatted.sign.is_empty() {
1566 self.buf.write_str(formatted.sign)?;
1568 for part in formatted.parts {
1570 numfmt::Part::Zero(mut nzeroes) => {
1571 const ZEROES: &str = // 64 zeroes
1572 "0000000000000000000000000000000000000000000000000000000000000000";
1573 while nzeroes > ZEROES.len() {
1574 self.buf.write_str(ZEROES)?;
1575 nzeroes -= ZEROES.len();
1578 self.buf.write_str(&ZEROES[..nzeroes])?;
1581 numfmt::Part::Num(mut v) => {
1583 let len = part.len();
1584 for c in s[..len].iter_mut().rev() {
1585 *c = b'0' + (v % 10) as u8;
1588 write_bytes(self.buf, &s[..len])?;
1590 numfmt::Part::Copy(buf) => {
1591 write_bytes(self.buf, buf)?;
1598 /// Writes some data to the underlying buffer contained within this
1608 /// impl fmt::Display for Foo {
1609 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1610 /// formatter.write_str("Foo")
1611 /// // This is equivalent to:
1612 /// // write!(formatter, "Foo")
1616 /// assert_eq!(&format!("{}", Foo), "Foo");
1617 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 pub fn write_str(&mut self, data: &str) -> Result {
1621 self.buf.write_str(data)
1624 /// Writes some formatted information into this instance.
1631 /// struct Foo(i32);
1633 /// impl fmt::Display for Foo {
1634 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1635 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1639 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1640 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1644 write(self.buf, fmt)
1647 /// Flags for formatting
1649 #[stable(feature = "rust1", since = "1.0.0")]
1652 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1653 or `sign_aware_zero_pad` methods instead"
1655 pub fn flags(&self) -> u32 {
1659 /// Character used as 'fill' whenever there is alignment.
1668 /// impl fmt::Display for Foo {
1669 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1670 /// let c = formatter.fill();
1671 /// if let Some(width) = formatter.width() {
1672 /// for _ in 0..width {
1673 /// write!(formatter, "{}", c)?;
1677 /// write!(formatter, "{}", c)
1682 /// // We set alignment to the right with ">".
1683 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1684 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1687 #[stable(feature = "fmt_flags", since = "1.5.0")]
1688 pub fn fill(&self) -> char {
1692 /// Flag indicating what form of alignment was requested.
1697 /// extern crate core;
1699 /// use std::fmt::{self, Alignment};
1703 /// impl fmt::Display for Foo {
1704 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1705 /// let s = if let Some(s) = formatter.align() {
1707 /// Alignment::Left => "left",
1708 /// Alignment::Right => "right",
1709 /// Alignment::Center => "center",
1714 /// write!(formatter, "{}", s)
1718 /// assert_eq!(&format!("{:<}", Foo), "left");
1719 /// assert_eq!(&format!("{:>}", Foo), "right");
1720 /// assert_eq!(&format!("{:^}", Foo), "center");
1721 /// assert_eq!(&format!("{}", Foo), "into the void");
1724 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1725 pub fn align(&self) -> Option<Alignment> {
1727 rt::v1::Alignment::Left => Some(Alignment::Left),
1728 rt::v1::Alignment::Right => Some(Alignment::Right),
1729 rt::v1::Alignment::Center => Some(Alignment::Center),
1730 rt::v1::Alignment::Unknown => None,
1734 /// Optionally specified integer width that the output should be.
1741 /// struct Foo(i32);
1743 /// impl fmt::Display for Foo {
1744 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1745 /// if let Some(width) = formatter.width() {
1746 /// // If we received a width, we use it
1747 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1749 /// // Otherwise we do nothing special
1750 /// write!(formatter, "Foo({})", self.0)
1755 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1756 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1759 #[stable(feature = "fmt_flags", since = "1.5.0")]
1760 pub fn width(&self) -> Option<usize> {
1764 /// Optionally specified precision for numeric types. Alternatively, the
1765 /// maximum width for string types.
1772 /// struct Foo(f32);
1774 /// impl fmt::Display for Foo {
1775 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1776 /// if let Some(precision) = formatter.precision() {
1777 /// // If we received a precision, we use it.
1778 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1780 /// // Otherwise we default to 2.
1781 /// write!(formatter, "Foo({:.2})", self.0)
1786 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1787 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1790 #[stable(feature = "fmt_flags", since = "1.5.0")]
1791 pub fn precision(&self) -> Option<usize> {
1795 /// Determines if the `+` flag was specified.
1802 /// struct Foo(i32);
1804 /// impl fmt::Display for Foo {
1805 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1806 /// if formatter.sign_plus() {
1807 /// write!(formatter,
1809 /// if self.0 < 0 { '-' } else { '+' },
1812 /// write!(formatter, "Foo({})", self.0)
1817 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1818 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1821 #[stable(feature = "fmt_flags", since = "1.5.0")]
1822 pub fn sign_plus(&self) -> bool {
1823 self.flags & (1 << FlagV1::SignPlus as u32) != 0
1826 /// Determines if the `-` flag was specified.
1833 /// struct Foo(i32);
1835 /// impl fmt::Display for Foo {
1836 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1837 /// if formatter.sign_minus() {
1838 /// // You want a minus sign? Have one!
1839 /// write!(formatter, "-Foo({})", self.0)
1841 /// write!(formatter, "Foo({})", self.0)
1846 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1847 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1850 #[stable(feature = "fmt_flags", since = "1.5.0")]
1851 pub fn sign_minus(&self) -> bool {
1852 self.flags & (1 << FlagV1::SignMinus as u32) != 0
1855 /// Determines if the `#` flag was specified.
1862 /// struct Foo(i32);
1864 /// impl fmt::Display for Foo {
1865 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1866 /// if formatter.alternate() {
1867 /// write!(formatter, "Foo({})", self.0)
1869 /// write!(formatter, "{}", self.0)
1874 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1875 /// assert_eq!(&format!("{}", Foo(23)), "23");
1878 #[stable(feature = "fmt_flags", since = "1.5.0")]
1879 pub fn alternate(&self) -> bool {
1880 self.flags & (1 << FlagV1::Alternate as u32) != 0
1883 /// Determines if the `0` flag was specified.
1890 /// struct Foo(i32);
1892 /// impl fmt::Display for Foo {
1893 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1894 /// assert!(formatter.sign_aware_zero_pad());
1895 /// assert_eq!(formatter.width(), Some(4));
1896 /// // We ignore the formatter's options.
1897 /// write!(formatter, "{}", self.0)
1901 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1904 #[stable(feature = "fmt_flags", since = "1.5.0")]
1905 pub fn sign_aware_zero_pad(&self) -> bool {
1906 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1909 // FIXME: Decide what public API we want for these two flags.
1910 // https://github.com/rust-lang/rust/issues/48584
1911 fn debug_lower_hex(&self) -> bool {
1912 self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1915 fn debug_upper_hex(&self) -> bool {
1916 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1919 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1920 /// [`fmt::Debug`] implementations for structs.
1922 /// [`fmt::Debug`]: self::Debug
1928 /// use std::net::Ipv4Addr;
1936 /// impl fmt::Debug for Foo {
1937 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1938 /// fmt.debug_struct("Foo")
1939 /// .field("bar", &self.bar)
1940 /// .field("baz", &self.baz)
1941 /// .field("addr", &format_args!("{}", self.addr))
1947 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1948 /// format!("{:?}", Foo {
1950 /// baz: "Hello World".to_string(),
1951 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1955 #[stable(feature = "debug_builders", since = "1.2.0")]
1956 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1957 builders::debug_struct_new(self, name)
1960 /// Creates a `DebugTuple` builder designed to assist with creation of
1961 /// `fmt::Debug` implementations for tuple structs.
1967 /// use std::marker::PhantomData;
1969 /// struct Foo<T>(i32, String, PhantomData<T>);
1971 /// impl<T> fmt::Debug for Foo<T> {
1972 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1973 /// fmt.debug_tuple("Foo")
1976 /// .field(&format_args!("_"))
1982 /// "Foo(10, \"Hello\", _)",
1983 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1986 #[stable(feature = "debug_builders", since = "1.2.0")]
1987 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1988 builders::debug_tuple_new(self, name)
1991 /// Creates a `DebugList` builder designed to assist with creation of
1992 /// `fmt::Debug` implementations for list-like structures.
1999 /// struct Foo(Vec<i32>);
2001 /// impl fmt::Debug for Foo {
2002 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2003 /// fmt.debug_list().entries(self.0.iter()).finish()
2007 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2009 #[stable(feature = "debug_builders", since = "1.2.0")]
2010 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2011 builders::debug_list_new(self)
2014 /// Creates a `DebugSet` builder designed to assist with creation of
2015 /// `fmt::Debug` implementations for set-like structures.
2022 /// struct Foo(Vec<i32>);
2024 /// impl fmt::Debug for Foo {
2025 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2026 /// fmt.debug_set().entries(self.0.iter()).finish()
2030 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2033 /// [`format_args!`]: crate::format_args
2035 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2036 /// to build a list of match arms:
2041 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
2042 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
2044 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2046 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
2048 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2049 /// L::fmt(&(self.0).0, fmt)?;
2050 /// fmt.write_str(" => ")?;
2051 /// R::fmt(&(self.0).1, fmt)
2055 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2057 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
2059 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2061 /// .entries(self.0.iter().map(Arm))
2062 /// .entry(&Arm(&(format_args!("_"), &self.1)))
2067 #[stable(feature = "debug_builders", since = "1.2.0")]
2068 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2069 builders::debug_set_new(self)
2072 /// Creates a `DebugMap` builder designed to assist with creation of
2073 /// `fmt::Debug` implementations for map-like structures.
2080 /// struct Foo(Vec<(String, i32)>);
2082 /// impl fmt::Debug for Foo {
2083 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2084 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2089 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2090 /// r#"{"A": 10, "B": 11}"#
2093 #[stable(feature = "debug_builders", since = "1.2.0")]
2094 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2095 builders::debug_map_new(self)
2099 #[stable(since = "1.2.0", feature = "formatter_write")]
2100 impl Write for Formatter<'_> {
2101 fn write_str(&mut self, s: &str) -> Result {
2102 self.buf.write_str(s)
2105 fn write_char(&mut self, c: char) -> Result {
2106 self.buf.write_char(c)
2109 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2110 write(self.buf, args)
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl Display for Error {
2116 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2117 Display::fmt("an error occurred when formatting an argument", f)
2121 // Implementations of the core formatting traits
2123 macro_rules! fmt_refs {
2124 ($($tr:ident),*) => {
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 impl<T: ?Sized + $tr> $tr for &T {
2128 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2130 #[stable(feature = "rust1", since = "1.0.0")]
2131 impl<T: ?Sized + $tr> $tr for &mut T {
2132 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2138 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2140 #[unstable(feature = "never_type", issue = "35121")]
2142 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2147 #[unstable(feature = "never_type", issue = "35121")]
2148 impl Display for ! {
2149 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2154 #[stable(feature = "rust1", since = "1.0.0")]
2155 impl Debug for bool {
2157 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2158 Display::fmt(self, f)
2162 #[stable(feature = "rust1", since = "1.0.0")]
2163 impl Display for bool {
2164 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2165 Display::fmt(if *self { "true" } else { "false" }, f)
2169 #[stable(feature = "rust1", since = "1.0.0")]
2170 impl Debug for str {
2171 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2174 for (i, c) in self.char_indices() {
2175 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2176 escape_grapheme_extended: true,
2177 escape_single_quote: false,
2178 escape_double_quote: true,
2180 // If char needs escaping, flush backlog so far and write, else skip
2182 f.write_str(&self[from..i])?;
2186 from = i + c.len_utf8();
2189 f.write_str(&self[from..])?;
2194 #[stable(feature = "rust1", since = "1.0.0")]
2195 impl Display for str {
2196 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2201 #[stable(feature = "rust1", since = "1.0.0")]
2202 impl Debug for char {
2203 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2204 f.write_char('\'')?;
2205 for c in self.escape_debug_ext(EscapeDebugExtArgs {
2206 escape_grapheme_extended: true,
2207 escape_single_quote: true,
2208 escape_double_quote: false,
2216 #[stable(feature = "rust1", since = "1.0.0")]
2217 impl Display for char {
2218 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2219 if f.width.is_none() && f.precision.is_none() {
2222 f.pad(self.encode_utf8(&mut [0; 4]))
2227 #[stable(feature = "rust1", since = "1.0.0")]
2228 impl<T: ?Sized> Pointer for *const T {
2229 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2230 /// Since the formatting will be identical for all pointer types, use a non-monomorphized
2231 /// implementation for the actual formatting to reduce the amount of codegen work needed
2232 fn inner(ptr: *const (), f: &mut Formatter<'_>) -> Result {
2233 let old_width = f.width;
2234 let old_flags = f.flags;
2236 // The alternate flag is already treated by LowerHex as being special-
2237 // it denotes whether to prefix with 0x. We use it to work out whether
2238 // or not to zero extend, and then unconditionally set it to get the
2241 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2243 if f.width.is_none() {
2244 f.width = Some((usize::BITS / 4) as usize + 2);
2247 f.flags |= 1 << (FlagV1::Alternate as u32);
2249 let ret = LowerHex::fmt(&(ptr as usize), f);
2251 f.width = old_width;
2252 f.flags = old_flags;
2257 inner(*self as *const (), f)
2261 #[stable(feature = "rust1", since = "1.0.0")]
2262 impl<T: ?Sized> Pointer for *mut T {
2263 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2264 Pointer::fmt(&(*self as *const T), f)
2268 #[stable(feature = "rust1", since = "1.0.0")]
2269 impl<T: ?Sized> Pointer for &T {
2270 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2271 Pointer::fmt(&(*self as *const T), f)
2275 #[stable(feature = "rust1", since = "1.0.0")]
2276 impl<T: ?Sized> Pointer for &mut T {
2277 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2278 Pointer::fmt(&(&**self as *const T), f)
2282 // Implementation of Display/Debug for various core types
2284 #[stable(feature = "rust1", since = "1.0.0")]
2285 impl<T: ?Sized> Debug for *const T {
2286 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2287 Pointer::fmt(self, f)
2290 #[stable(feature = "rust1", since = "1.0.0")]
2291 impl<T: ?Sized> Debug for *mut T {
2292 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2293 Pointer::fmt(self, f)
2298 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2301 macro_rules! tuple {
2303 ( $($name:ident,)+ ) => (
2304 #[stable(feature = "rust1", since = "1.0.0")]
2305 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2306 #[allow(non_snake_case, unused_assignments)]
2307 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2308 let mut builder = f.debug_tuple("");
2309 let ($(ref $name,)+) = *self;
2311 builder.field(&$name);
2317 peel! { $($name,)+ }
2321 macro_rules! last_type {
2322 ($a:ident,) => { $a };
2323 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2326 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2328 #[stable(feature = "rust1", since = "1.0.0")]
2329 impl<T: Debug> Debug for [T] {
2330 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2331 f.debug_list().entries(self.iter()).finish()
2335 #[stable(feature = "rust1", since = "1.0.0")]
2338 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2342 #[stable(feature = "rust1", since = "1.0.0")]
2343 impl<T: ?Sized> Debug for PhantomData<T> {
2344 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2345 f.debug_struct("PhantomData").finish()
2349 #[stable(feature = "rust1", since = "1.0.0")]
2350 impl<T: Copy + Debug> Debug for Cell<T> {
2351 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2352 f.debug_struct("Cell").field("value", &self.get()).finish()
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2358 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2359 match self.try_borrow() {
2360 Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2362 // The RefCell is mutably borrowed so we can't look at its value
2363 // here. Show a placeholder instead.
2364 struct BorrowedPlaceholder;
2366 impl Debug for BorrowedPlaceholder {
2367 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2368 f.write_str("<borrowed>")
2372 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2378 #[stable(feature = "rust1", since = "1.0.0")]
2379 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2380 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2381 Debug::fmt(&**self, f)
2385 #[stable(feature = "rust1", since = "1.0.0")]
2386 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2387 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2388 Debug::fmt(&*(self.deref()), f)
2392 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2393 impl<T: ?Sized> Debug for UnsafeCell<T> {
2394 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2395 f.debug_struct("UnsafeCell").finish_non_exhaustive()
2399 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2400 // it's a lot easier than creating all of the rt::Piece structures here.
2401 // There are also tests in the alloc crate, for those that need allocations.