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
;
8 use crate::marker
::PhantomData
;
10 use crate::num
::fmt
as numfmt
;
11 use crate::ops
::Deref
;
16 #[cfg(not(no_fp_fmt_parse))]
18 #[cfg(no_fp_fmt_parse)]
22 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
23 /// Possible alignments returned by `Formatter::align`
26 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
27 /// Indication that contents should be left-aligned.
29 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
30 /// Indication that contents should be right-aligned.
32 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
33 /// Indication that contents should be center-aligned.
37 #[stable(feature = "debug_builders", since = "1.2.0")]
38 pub use self::builders
::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}
;
40 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
46 /// The type returned by formatter methods.
60 /// impl fmt::Display for Triangle {
61 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
66 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
68 /// assert_eq!(format!("{}", pythagorean_triple), "(3, 4, 5)");
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub type Result
= result
::Result
<(), Error
>;
73 /// The error type which is returned from formatting a message into a stream.
75 /// This type does not support transmission of an error other than that an error
76 /// occurred. Any extra information must be arranged to be transmitted through
79 /// An important thing to remember is that the type `fmt::Error` should not be
80 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
83 /// [`std::io::Error`]: ../../std/io/struct.Error.html
84 /// [`std::error::Error`]: ../../std/error/trait.Error.html
89 /// use std::fmt::{self, write};
91 /// let mut output = String::new();
92 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
93 /// panic!("An error occurred");
96 #[stable(feature = "rust1", since = "1.0.0")]
97 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
100 /// A trait for writing or formatting into Unicode-accepting buffers or streams.
102 /// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
103 /// want to accept Unicode and you don't need flushing, you should implement this trait;
104 /// otherwise you should implement [`std::io::Write`].
106 /// [`std::io::Write`]: ../../std/io/trait.Write.html
107 /// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
108 #[stable(feature = "rust1", since = "1.0.0")]
110 /// Writes a string slice into this writer, returning whether the write
113 /// This method can only succeed if the entire string slice was successfully
114 /// written, and this method will not return until all data has been
115 /// written or an error occurs.
119 /// This function will return an instance of [`Error`] on error.
124 /// use std::fmt::{Error, Write};
126 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
130 /// let mut buf = String::new();
131 /// writer(&mut buf, "hola").unwrap();
132 /// assert_eq!(&buf, "hola");
134 #[stable(feature = "rust1", since = "1.0.0")]
135 fn write_str(&mut self, s
: &str) -> Result
;
137 /// Writes a [`char`] into this writer, returning whether the write succeeded.
139 /// A single [`char`] may be encoded as more than one byte.
140 /// This method can only succeed if the entire byte sequence was successfully
141 /// written, and this method will not return until all data has been
142 /// written or an error occurs.
146 /// This function will return an instance of [`Error`] on error.
151 /// use std::fmt::{Error, Write};
153 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
157 /// let mut buf = String::new();
158 /// writer(&mut buf, 'a').unwrap();
159 /// writer(&mut buf, 'b').unwrap();
160 /// assert_eq!(&buf, "ab");
162 #[stable(feature = "fmt_write_char", since = "1.1.0")]
163 fn write_char(&mut self, c
: char) -> Result
{
164 self.write_str(c
.encode_utf8(&mut [0; 4]))
167 /// Glue for usage of the [`write!`] macro with implementors of this trait.
169 /// This method should generally not be invoked manually, but rather through
170 /// the [`write!`] macro itself.
175 /// use std::fmt::{Error, Write};
177 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
178 /// f.write_fmt(format_args!("{}", s))
181 /// let mut buf = String::new();
182 /// writer(&mut buf, "world").unwrap();
183 /// assert_eq!(&buf, "world");
185 #[stable(feature = "rust1", since = "1.0.0")]
186 fn write_fmt(mut self: &mut Self, args
: Arguments
<'_
>) -> Result
{
187 write(&mut self, args
)
191 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
192 impl<W
: Write
+ ?Sized
> Write
for &mut W
{
193 fn write_str(&mut self, s
: &str) -> Result
{
194 (**self).write_str(s
)
197 fn write_char(&mut self, c
: char) -> Result
{
198 (**self).write_char(c
)
201 fn write_fmt(&mut self, args
: Arguments
<'_
>) -> Result
{
202 (**self).write_fmt(args
)
206 /// Configuration for formatting.
208 /// A `Formatter` represents various options related to formatting. Users do not
209 /// construct `Formatter`s directly; a mutable reference to one is passed to
210 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
212 /// To interact with a `Formatter`, you'll call various methods to change the
213 /// various options related to formatting. For examples, please see the
214 /// documentation of the methods defined on `Formatter` below.
215 #[allow(missing_debug_implementations)]
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub struct Formatter
<'a
> {
220 align
: rt
::v1
::Alignment
,
221 width
: Option
<usize>,
222 precision
: Option
<usize>,
224 buf
: &'a
mut (dyn Write
+ 'a
),
227 impl<'a
> Formatter
<'a
> {
228 /// Creates a new formatter with default settings.
230 /// This can be used as a micro-optimization in cases where a full `Arguments`
231 /// structure (as created by `format_args!`) is not necessary; `Arguments`
232 /// is a little more expensive to use in simple formatting scenarios.
234 /// Currently not intended for use outside of the standard library.
235 #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
237 pub fn new(buf
: &'a
mut (dyn Write
+ 'a
)) -> Formatter
<'a
> {
241 align
: rt
::v1
::Alignment
::Unknown
,
249 // NB. Argument is essentially an optimized partially applied formatting function,
250 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
256 /// This struct represents the generic "argument" which is taken by the Xprintf
257 /// family of functions. It contains a function to format the given value. At
258 /// compile time it is ensured that the function and the value have the correct
259 /// types, and then this struct is used to canonicalize arguments to one type.
260 #[derive(Copy, Clone)]
261 #[allow(missing_debug_implementations)]
262 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
264 pub struct ArgumentV1
<'a
> {
266 formatter
: fn(&Opaque
, &mut Formatter
<'_
>) -> Result
,
269 // This guarantees a single stable value for the function pointer associated with
270 // indices/counts in the formatting infrastructure.
272 // Note that a function defined as such would not be correct as functions are
273 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
274 // address is not considered important to LLVM and as such the as_usize cast
275 // could have been miscompiled. In practice, we never call as_usize on non-usize
276 // containing data (as a matter of static generation of the formatting
277 // arguments), so this is merely an additional check.
279 // We primarily want to ensure that the function pointer at `USIZE_MARKER` has
280 // an address corresponding *only* to functions that also take `&usize` as their
281 // first argument. The read_volatile here ensures that we can safely ready out a
282 // usize from the passed reference and that this address does not point at a
283 // non-usize taking function.
284 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
285 static USIZE_MARKER
: fn(&usize, &mut Formatter
<'_
>) -> Result
= |ptr
, _
| {
286 // SAFETY: ptr is a reference
287 let _v
: usize = unsafe { crate::ptr::read_volatile(ptr) }
;
291 impl<'a
> ArgumentV1
<'a
> {
293 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
294 pub fn new
<'b
, T
>(x
: &'b T
, f
: fn(&T
, &mut Formatter
<'_
>) -> Result
) -> ArgumentV1
<'b
> {
295 // SAFETY: `mem::transmute(x)` is safe because
296 // 1. `&'b T` keeps the lifetime it originated with `'b`
297 // (so as to not have an unbounded lifetime)
298 // 2. `&'b T` and `&'b Opaque` have the same memory layout
299 // (when `T` is `Sized`, as it is here)
300 // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
301 // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
302 // (as long as `T` is `Sized`)
303 unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) }
}
307 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
308 pub fn from_usize(x
: &usize) -> ArgumentV1
<'_
> {
309 ArgumentV1
::new(x
, USIZE_MARKER
)
312 fn as_usize(&self) -> Option
<usize> {
313 if self.formatter
as usize == USIZE_MARKER
as usize {
314 // SAFETY: The `formatter` field is only set to USIZE_MARKER if
315 // the value is a usize, so this is safe
316 Some(unsafe { *(self.value as *const _ as *const usize) }
)
323 // flags available in the v1 format of format_args
324 #[derive(Copy, Clone)]
334 impl<'a
> Arguments
<'a
> {
335 /// When using the format_args!() macro, this function is used to generate the
336 /// Arguments structure.
339 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
340 pub fn new_v1(pieces
: &'a
[&'
static str], args
: &'a
[ArgumentV1
<'a
>]) -> Arguments
<'a
> {
341 Arguments { pieces, fmt: None, args }
344 /// This function is used to specify nonstandard formatting parameters.
345 /// The `pieces` array must be at least as long as `fmt` to construct
346 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
347 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
348 /// created with `argumentusize`. However, failing to do so doesn't cause
349 /// unsafety, but will ignore invalid .
352 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
353 pub fn new_v1_formatted(
354 pieces
: &'a
[&'
static str],
355 args
: &'a
[ArgumentV1
<'a
>],
356 fmt
: &'a
[rt
::v1
::Argument
],
358 Arguments { pieces, fmt: Some(fmt), args }
361 /// Estimates the length of the formatted text.
363 /// This is intended to be used for setting initial `String` capacity
364 /// when using `format!`. Note: this is neither the lower nor upper bound.
367 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
368 pub fn estimated_capacity(&self) -> usize {
369 let pieces_length
: usize = self.pieces
.iter().map(|x
| x
.len()).sum();
371 if self.args
.is_empty() {
373 } else if self.pieces
[0] == "" && pieces_length
< 16 {
374 // If the format string starts with an argument,
375 // don't preallocate anything, unless length
376 // of pieces is significant.
379 // There are some arguments, so any additional push
380 // will reallocate the string. To avoid that,
381 // we're "pre-doubling" the capacity here.
382 pieces_length
.checked_mul(2).unwrap_or(0)
387 /// This structure represents a safely precompiled version of a format string
388 /// and its arguments. This cannot be generated at runtime because it cannot
389 /// safely be done, so no constructors are given and the fields are private
390 /// to prevent modification.
392 /// The [`format_args!`] macro will safely create an instance of this structure.
393 /// The macro validates the format string at compile-time so usage of the
394 /// [`write()`] and [`format()`] functions can be safely performed.
396 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
397 /// and `Display` contexts as seen below. The example also shows that `Debug`
398 /// and `Display` format to the same thing: the interpolated format string
399 /// in `format_args!`.
402 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
403 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
404 /// assert_eq!("1 foo 2", display);
405 /// assert_eq!(display, debug);
408 /// [`format()`]: ../../std/fmt/fn.format.html
409 #[stable(feature = "rust1", since = "1.0.0")]
410 #[derive(Copy, Clone)]
411 pub struct Arguments
<'a
> {
412 // Format string pieces to print.
413 pieces
: &'a
[&'
static str],
415 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
416 fmt
: Option
<&'a
[rt
::v1
::Argument
]>,
418 // Dynamic arguments for interpolation, to be interleaved with string
419 // pieces. (Every argument is preceded by a string piece.)
420 args
: &'a
[ArgumentV1
<'a
>],
423 impl<'a
> Arguments
<'a
> {
424 /// Get the formatted string, if it has no arguments to be formatted.
426 /// This can be used to avoid allocations in the most trivial case.
431 /// use std::fmt::Arguments;
433 /// fn write_str(_: &str) { /* ... */ }
435 /// fn write_fmt(args: &Arguments) {
436 /// if let Some(s) = args.as_str() {
439 /// write_str(&args.to_string());
445 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
446 /// assert_eq!(format_args!("").as_str(), Some(""));
447 /// assert_eq!(format_args!("{}", 1).as_str(), None);
449 #[stable(feature = "fmt_as_str", since = "1.52.0")]
450 #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "none")]
452 pub const fn as_str(&self) -> Option
<&'
static str> {
453 match (self.pieces
, self.args
) {
454 ([], []) => Some(""),
455 ([s
], []) => Some(s
),
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl Debug
for Arguments
<'_
> {
463 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> Result
{
464 Display
::fmt(self, fmt
)
468 #[stable(feature = "rust1", since = "1.0.0")]
469 impl Display
for Arguments
<'_
> {
470 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> Result
{
471 write(fmt
.buf
, *self)
477 /// `Debug` should format the output in a programmer-facing, debugging context.
479 /// Generally speaking, you should just `derive` a `Debug` implementation.
481 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
483 /// For more information on formatters, see [the module-level documentation][module].
485 /// [module]: ../../std/fmt/index.html
487 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
488 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
489 /// comma-separated list of each field's name and `Debug` value, then `}`. For
490 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
491 /// `Debug` values of the fields, then `)`.
495 /// Derived `Debug` formats are not stable, and so may change with future Rust
496 /// versions. Additionally, `Debug` implementations of types provided by the
497 /// standard library (`libstd`, `libcore`, `liballoc`, etc.) are not stable, and
498 /// may also change with future Rust versions.
502 /// Deriving an implementation:
511 /// let origin = Point { x: 0, y: 0 };
513 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
516 /// Manually implementing:
526 /// impl fmt::Debug for Point {
527 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528 /// f.debug_struct("Point")
529 /// .field("x", &self.x)
530 /// .field("y", &self.y)
535 /// let origin = Point { x: 0, y: 0 };
537 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
540 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
541 /// implementations, such as [`debug_struct`].
543 /// `Debug` implementations using either `derive` or the debug builder API
544 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
546 /// [`debug_struct`]: Formatter::debug_struct
548 /// Pretty-printing with `#?`:
557 /// let origin = Point { x: 0, y: 0 };
559 /// assert_eq!(format!("The origin is: {:#?}", origin),
560 /// "The origin is: Point {
566 #[stable(feature = "rust1", since = "1.0.0")]
567 #[rustc_on_unimplemented(
570 label
= "`{Self}` cannot be formatted using `{{:?}}`",
571 note
= "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
573 message
= "`{Self}` doesn't implement `{Debug}`",
574 label
= "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
576 #[doc(alias = "{:?}")]
577 #[rustc_diagnostic_item = "debug_trait"]
579 /// Formats the value using the given formatter.
586 /// struct Position {
591 /// impl fmt::Debug for Position {
592 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593 /// f.debug_tuple("")
594 /// .field(&self.longitude)
595 /// .field(&self.latitude)
600 /// let position = Position { longitude: 1.987, latitude: 2.983 };
601 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
603 /// assert_eq!(format!("{:#?}", position), "(
608 #[stable(feature = "rust1", since = "1.0.0")]
609 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
612 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
613 pub(crate) mod macros
{
614 /// Derive macro generating an impl of the trait `Debug`.
615 #[rustc_builtin_macro]
616 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
617 #[allow_internal_unstable(core_intrinsics)]
618 pub macro Debug($item
:item
) {
619 /* compiler built-in */
622 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
624 pub use macros
::Debug
;
626 /// Format trait for an empty format, `{}`.
628 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
629 /// output, and so cannot be derived.
631 /// For more information on formatters, see [the module-level documentation][module].
633 /// [module]: ../../std/fmt/index.html
637 /// Implementing `Display` on a type:
647 /// impl fmt::Display for Point {
648 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
649 /// write!(f, "({}, {})", self.x, self.y)
653 /// let origin = Point { x: 0, y: 0 };
655 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
657 #[rustc_on_unimplemented(
659 _Self
= "std::path::Path",
660 label
= "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
661 note
= "call `.display()` or `.to_string_lossy()` to safely print paths, \
662 as they may contain non-Unicode data"
664 message
= "`{Self}` doesn't implement `{Display}`",
665 label
= "`{Self}` cannot be formatted with the default formatter",
666 note
= "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
669 #[rustc_diagnostic_item = "display_trait"]
670 #[stable(feature = "rust1", since = "1.0.0")]
672 /// Formats the value using the given formatter.
679 /// struct Position {
684 /// impl fmt::Display for Position {
685 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
686 /// write!(f, "({}, {})", self.longitude, self.latitude)
690 /// assert_eq!("(1.987, 2.983)",
691 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
693 #[stable(feature = "rust1", since = "1.0.0")]
694 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
699 /// The `Octal` trait should format its output as a number in base-8.
701 /// For primitive signed integers (`i8` to `i128`, and `isize`),
702 /// negative values are formatted as the two’s complement representation.
704 /// The alternate flag, `#`, adds a `0o` in front of the output.
706 /// For more information on formatters, see [the module-level documentation][module].
708 /// [module]: ../../std/fmt/index.html
712 /// Basic usage with `i32`:
715 /// let x = 42; // 42 is '52' in octal
717 /// assert_eq!(format!("{:o}", x), "52");
718 /// assert_eq!(format!("{:#o}", x), "0o52");
720 /// assert_eq!(format!("{:o}", -16), "37777777760");
723 /// Implementing `Octal` on a type:
728 /// struct Length(i32);
730 /// impl fmt::Octal for Length {
731 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732 /// let val = self.0;
734 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
738 /// let l = Length(9);
740 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
742 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
744 #[stable(feature = "rust1", since = "1.0.0")]
746 /// Formats the value using the given formatter.
747 #[stable(feature = "rust1", since = "1.0.0")]
748 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
753 /// The `Binary` trait should format its output as a number in binary.
755 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
756 /// negative values are formatted as the two’s complement representation.
758 /// The alternate flag, `#`, adds a `0b` in front of the output.
760 /// For more information on formatters, see [the module-level documentation][module].
762 /// [module]: ../../std/fmt/index.html
766 /// Basic usage with [`i32`]:
769 /// let x = 42; // 42 is '101010' in binary
771 /// assert_eq!(format!("{:b}", x), "101010");
772 /// assert_eq!(format!("{:#b}", x), "0b101010");
774 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
777 /// Implementing `Binary` on a type:
782 /// struct Length(i32);
784 /// impl fmt::Binary for Length {
785 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
786 /// let val = self.0;
788 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
792 /// let l = Length(107);
794 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
797 /// format!("l as binary is: {:#032b}", l),
798 /// "l as binary is: 0b000000000000000000000001101011"
801 #[stable(feature = "rust1", since = "1.0.0")]
803 /// Formats the value using the given formatter.
804 #[stable(feature = "rust1", since = "1.0.0")]
805 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
810 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
813 /// For primitive signed integers (`i8` to `i128`, and `isize`),
814 /// negative values are formatted as the two’s complement representation.
816 /// The alternate flag, `#`, adds a `0x` in front of the output.
818 /// For more information on formatters, see [the module-level documentation][module].
820 /// [module]: ../../std/fmt/index.html
824 /// Basic usage with `i32`:
827 /// let x = 42; // 42 is '2a' in hex
829 /// assert_eq!(format!("{:x}", x), "2a");
830 /// assert_eq!(format!("{:#x}", x), "0x2a");
832 /// assert_eq!(format!("{:x}", -16), "fffffff0");
835 /// Implementing `LowerHex` on a type:
840 /// struct Length(i32);
842 /// impl fmt::LowerHex for Length {
843 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
844 /// let val = self.0;
846 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
850 /// let l = Length(9);
852 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
854 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
856 #[stable(feature = "rust1", since = "1.0.0")]
858 /// Formats the value using the given formatter.
859 #[stable(feature = "rust1", since = "1.0.0")]
860 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
865 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
868 /// For primitive signed integers (`i8` to `i128`, and `isize`),
869 /// negative values are formatted as the two’s complement representation.
871 /// The alternate flag, `#`, adds a `0x` in front of the output.
873 /// For more information on formatters, see [the module-level documentation][module].
875 /// [module]: ../../std/fmt/index.html
879 /// Basic usage with `i32`:
882 /// let x = 42; // 42 is '2A' in hex
884 /// assert_eq!(format!("{:X}", x), "2A");
885 /// assert_eq!(format!("{:#X}", x), "0x2A");
887 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
890 /// Implementing `UpperHex` on a type:
895 /// struct Length(i32);
897 /// impl fmt::UpperHex for Length {
898 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899 /// let val = self.0;
901 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
905 /// let l = Length(i32::MAX);
907 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
909 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
911 #[stable(feature = "rust1", since = "1.0.0")]
913 /// Formats the value using the given formatter.
914 #[stable(feature = "rust1", since = "1.0.0")]
915 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
920 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
923 /// For more information on formatters, see [the module-level documentation][module].
925 /// [module]: ../../std/fmt/index.html
929 /// Basic usage with `&i32`:
934 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
937 /// Implementing `Pointer` on a type:
942 /// struct Length(i32);
944 /// impl fmt::Pointer for Length {
945 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
948 /// let ptr = self as *const Self;
949 /// fmt::Pointer::fmt(&ptr, f)
953 /// let l = Length(42);
955 /// println!("l is in memory here: {:p}", l);
957 /// let l_ptr = format!("{:018p}", l);
958 /// assert_eq!(l_ptr.len(), 18);
959 /// assert_eq!(&l_ptr[..2], "0x");
961 #[stable(feature = "rust1", since = "1.0.0")]
962 #[rustc_diagnostic_item = "pointer_trait"]
964 /// Formats the value using the given formatter.
965 #[stable(feature = "rust1", since = "1.0.0")]
966 #[rustc_diagnostic_item = "pointer_trait_fmt"]
967 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
972 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
974 /// For more information on formatters, see [the module-level documentation][module].
976 /// [module]: ../../std/fmt/index.html
980 /// Basic usage with `f64`:
983 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
985 /// assert_eq!(format!("{:e}", x), "4.2e1");
988 /// Implementing `LowerExp` on a type:
993 /// struct Length(i32);
995 /// impl fmt::LowerExp for Length {
996 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
997 /// let val = f64::from(self.0);
998 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1002 /// let l = Length(100);
1005 /// format!("l in scientific notation is: {:e}", l),
1006 /// "l in scientific notation is: 1e2"
1010 /// format!("l in scientific notation is: {:05e}", l),
1011 /// "l in scientific notation is: 001e2"
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 pub trait LowerExp
{
1016 /// Formats the value using the given formatter.
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
1023 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1025 /// For more information on formatters, see [the module-level documentation][module].
1027 /// [module]: ../../std/fmt/index.html
1031 /// Basic usage with `f64`:
1034 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1036 /// assert_eq!(format!("{:E}", x), "4.2E1");
1039 /// Implementing `UpperExp` on a type:
1044 /// struct Length(i32);
1046 /// impl fmt::UpperExp for Length {
1047 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048 /// let val = f64::from(self.0);
1049 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1053 /// let l = Length(100);
1056 /// format!("l in scientific notation is: {:E}", l),
1057 /// "l in scientific notation is: 1E2"
1061 /// format!("l in scientific notation is: {:05E}", l),
1062 /// "l in scientific notation is: 001E2"
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 pub trait UpperExp
{
1067 /// Formats the value using the given formatter.
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
1072 /// The `write` function takes an output stream, and an `Arguments` struct
1073 /// that can be precompiled with the `format_args!` macro.
1075 /// The arguments will be formatted according to the specified format string
1076 /// into the output stream provided.
1085 /// let mut output = String::new();
1086 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1087 /// .expect("Error occurred while trying to write in String");
1088 /// assert_eq!(output, "Hello world!");
1091 /// Please note that using [`write!`] might be preferable. Example:
1094 /// use std::fmt::Write;
1096 /// let mut output = String::new();
1097 /// write!(&mut output, "Hello {}!", "world")
1098 /// .expect("Error occurred while trying to write in String");
1099 /// assert_eq!(output, "Hello world!");
1102 /// [`write!`]: crate::write!
1103 #[stable(feature = "rust1", since = "1.0.0")]
1104 pub fn write(output
: &mut dyn Write
, args
: Arguments
<'_
>) -> Result
{
1105 let mut formatter
= Formatter
::new(output
);
1110 // We can use default formatting parameters for all arguments.
1111 for (arg
, piece
) in iter
::zip(args
.args
, args
.pieces
) {
1112 if !piece
.is_empty() {
1113 formatter
.buf
.write_str(*piece
)?
;
1115 (arg
.formatter
)(arg
.value
, &mut formatter
)?
;
1120 // Every spec has a corresponding argument that is preceded by
1122 for (arg
, piece
) in iter
::zip(fmt
, args
.pieces
) {
1123 if !piece
.is_empty() {
1124 formatter
.buf
.write_str(*piece
)?
;
1126 // SAFETY: arg and args.args come from the same Arguments,
1127 // which guarantees the indexes are always within bounds.
1128 unsafe { run(&mut formatter, arg, &args.args) }?
;
1134 // There can be only one trailing string piece left.
1135 if let Some(piece
) = args
.pieces
.get(idx
) {
1136 formatter
.buf
.write_str(*piece
)?
;
1142 unsafe fn run(fmt
: &mut Formatter
<'_
>, arg
: &rt
::v1
::Argument
, args
: &[ArgumentV1
<'_
>]) -> Result
{
1143 fmt
.fill
= arg
.format
.fill
;
1144 fmt
.align
= arg
.format
.align
;
1145 fmt
.flags
= arg
.format
.flags
;
1146 // SAFETY: arg and args come from the same Arguments,
1147 // which guarantees the indexes are always within bounds.
1149 fmt
.width
= getcount(args
, &arg
.format
.width
);
1150 fmt
.precision
= getcount(args
, &arg
.format
.precision
);
1153 // Extract the correct argument
1154 debug_assert
!(arg
.position
< args
.len());
1155 // SAFETY: arg and args come from the same Arguments,
1156 // which guarantees its index is always within bounds.
1157 let value
= unsafe { args.get_unchecked(arg.position) }
;
1159 // Then actually do some printing
1160 (value
.formatter
)(value
.value
, fmt
)
1163 unsafe fn getcount(args
: &[ArgumentV1
<'_
>], cnt
: &rt
::v1
::Count
) -> Option
<usize> {
1165 rt
::v1
::Count
::Is(n
) => Some(n
),
1166 rt
::v1
::Count
::Implied
=> None
,
1167 rt
::v1
::Count
::Param(i
) => {
1168 debug_assert
!(i
< args
.len());
1169 // SAFETY: cnt and args come from the same Arguments,
1170 // which guarantees this index is always within bounds.
1171 unsafe { args.get_unchecked(i).as_usize() }
1176 /// Padding after the end of something. Returned by `Formatter::padding`.
1177 #[must_use = "don't forget to write the post padding"]
1178 struct PostPadding
{
1184 fn new(fill
: char, padding
: usize) -> PostPadding
{
1185 PostPadding { fill, padding }
1188 /// Write this post padding.
1189 fn write(self, buf
: &mut dyn Write
) -> Result
{
1190 for _
in 0..self.padding
{
1191 buf
.write_char(self.fill
)?
;
1197 impl<'a
> Formatter
<'a
> {
1198 fn wrap_buf
<'b
, 'c
, F
>(&'b
mut self, wrap
: F
) -> Formatter
<'c
>
1201 F
: FnOnce(&'b
mut (dyn Write
+ 'b
)) -> &'c
mut (dyn Write
+ 'c
),
1204 // We want to change this
1205 buf
: wrap(self.buf
),
1207 // And preserve these
1212 precision
: self.precision
,
1216 // Helper methods used for padding and processing formatting arguments that
1217 // all formatting traits can use.
1219 /// Performs the correct padding for an integer which has already been
1220 /// emitted into a str. The str should *not* contain the sign for the
1221 /// integer, that will be added by this method.
1225 /// * is_nonnegative - whether the original integer was either positive or zero.
1226 /// * prefix - if the '#' character (Alternate) is provided, this
1227 /// is the prefix to put in front of the number.
1228 /// * buf - the byte array that the number has been formatted into
1230 /// This function will correctly account for the flags provided as well as
1231 /// the minimum width. It will not take precision into account.
1238 /// struct Foo { nb: i32 }
1241 /// fn new(nb: i32) -> Foo {
1248 /// impl fmt::Display for Foo {
1249 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1250 /// // We need to remove "-" from the number output.
1251 /// let tmp = self.nb.abs().to_string();
1253 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1257 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1258 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1259 /// assert_eq!(&format!("{}", Foo::new(0)), "0");
1260 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1261 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 pub fn pad_integral(&mut self, is_nonnegative
: bool
, prefix
: &str, buf
: &str) -> Result
{
1265 let mut width
= buf
.len();
1267 let mut sign
= None
;
1268 if !is_nonnegative
{
1271 } else if self.sign_plus() {
1276 let prefix
= if self.alternate() {
1277 width
+= prefix
.chars().count();
1283 // Writes the sign if it exists, and then the prefix if it was requested
1285 fn write_prefix(f
: &mut Formatter
<'_
>, sign
: Option
<char>, prefix
: Option
<&str>) -> Result
{
1286 if let Some(c
) = sign
{
1287 f
.buf
.write_char(c
)?
;
1289 if let Some(prefix
) = prefix { f.buf.write_str(prefix) }
else { Ok(()) }
1292 // The `width` field is more of a `min-width` parameter at this point.
1294 // If there's no minimum length requirements then we can just
1297 write_prefix(self, sign
, prefix
)?
;
1298 self.buf
.write_str(buf
)
1300 // Check if we're over the minimum width, if so then we can also
1301 // just write the bytes.
1302 Some(min
) if width
>= min
=> {
1303 write_prefix(self, sign
, prefix
)?
;
1304 self.buf
.write_str(buf
)
1306 // The sign and prefix goes before the padding if the fill character
1308 Some(min
) if self.sign_aware_zero_pad() => {
1309 let old_fill
= crate::mem
::replace(&mut self.fill
, '
0'
);
1310 let old_align
= crate::mem
::replace(&mut self.align
, rt
::v1
::Alignment
::Right
);
1311 write_prefix(self, sign
, prefix
)?
;
1312 let post_padding
= self.padding(min
- width
, rt
::v1
::Alignment
::Right
)?
;
1313 self.buf
.write_str(buf
)?
;
1314 post_padding
.write(self.buf
)?
;
1315 self.fill
= old_fill
;
1316 self.align
= old_align
;
1319 // Otherwise, the sign and prefix goes after the padding
1321 let post_padding
= self.padding(min
- width
, rt
::v1
::Alignment
::Right
)?
;
1322 write_prefix(self, sign
, prefix
)?
;
1323 self.buf
.write_str(buf
)?
;
1324 post_padding
.write(self.buf
)
1329 /// This function takes a string slice and emits it to the internal buffer
1330 /// after applying the relevant formatting flags specified. The flags
1331 /// recognized for generic strings are:
1333 /// * width - the minimum width of what to emit
1334 /// * fill/align - what to emit and where to emit it if the string
1335 /// provided needs to be padded
1336 /// * precision - the maximum length to emit, the string is truncated if it
1337 /// is longer than this length
1339 /// Notably this function ignores the `flag` parameters.
1348 /// impl fmt::Display for Foo {
1349 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1350 /// formatter.pad("Foo")
1354 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1355 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 pub fn pad(&mut self, s
: &str) -> Result
{
1359 // Make sure there's a fast path up front
1360 if self.width
.is_none() && self.precision
.is_none() {
1361 return self.buf
.write_str(s
);
1363 // The `precision` field can be interpreted as a `max-width` for the
1364 // string being formatted.
1365 let s
= if let Some(max
) = self.precision
{
1366 // If our string is longer that the precision, then we must have
1367 // truncation. However other flags like `fill`, `width` and `align`
1368 // must act as always.
1369 if let Some((i
, _
)) = s
.char_indices().nth(max
) {
1370 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1371 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1372 // `unsafe` and otherwise don't emit any panic-related code
1374 s
.get(..i
).unwrap_or(&s
)
1381 // The `width` field is more of a `min-width` parameter at this point.
1383 // If we're under the maximum length, and there's no minimum length
1384 // requirements, then we can just emit the string
1385 None
=> self.buf
.write_str(s
),
1386 // If we're under the maximum width, check if we're over the minimum
1387 // width, if so it's as easy as just emitting the string.
1388 Some(width
) if s
.chars().count() >= width
=> self.buf
.write_str(s
),
1389 // If we're under both the maximum and the minimum width, then fill
1390 // up the minimum width with the specified string + some alignment.
1392 let align
= rt
::v1
::Alignment
::Left
;
1393 let post_padding
= self.padding(width
- s
.chars().count(), align
)?
;
1394 self.buf
.write_str(s
)?
;
1395 post_padding
.write(self.buf
)
1400 /// Write the pre-padding and return the unwritten post-padding. Callers are
1401 /// responsible for ensuring post-padding is written after the thing that is
1406 default: rt
::v1
::Alignment
,
1407 ) -> result
::Result
<PostPadding
, Error
> {
1408 let align
= match self.align
{
1409 rt
::v1
::Alignment
::Unknown
=> default,
1413 let (pre_pad
, post_pad
) = match align
{
1414 rt
::v1
::Alignment
::Left
=> (0, padding
),
1415 rt
::v1
::Alignment
::Right
| rt
::v1
::Alignment
::Unknown
=> (padding
, 0),
1416 rt
::v1
::Alignment
::Center
=> (padding
/ 2, (padding
+ 1) / 2),
1419 for _
in 0..pre_pad
{
1420 self.buf
.write_char(self.fill
)?
;
1423 Ok(PostPadding
::new(self.fill
, post_pad
))
1426 /// Takes the formatted parts and applies the padding.
1427 /// Assumes that the caller already has rendered the parts with required precision,
1428 /// so that `self.precision` can be ignored.
1429 fn pad_formatted_parts(&mut self, formatted
: &numfmt
::Formatted
<'_
>) -> Result
{
1430 if let Some(mut width
) = self.width
{
1431 // for the sign-aware zero padding, we render the sign first and
1432 // behave as if we had no sign from the beginning.
1433 let mut formatted
= formatted
.clone();
1434 let old_fill
= self.fill
;
1435 let old_align
= self.align
;
1436 let mut align
= old_align
;
1437 if self.sign_aware_zero_pad() {
1438 // a sign always goes first
1439 let sign
= formatted
.sign
;
1440 self.buf
.write_str(sign
)?
;
1442 // remove the sign from the formatted parts
1443 formatted
.sign
= "";
1444 width
= width
.saturating_sub(sign
.len());
1445 align
= rt
::v1
::Alignment
::Right
;
1447 self.align
= rt
::v1
::Alignment
::Right
;
1450 // remaining parts go through the ordinary padding process.
1451 let len
= formatted
.len();
1452 let ret
= if width
<= len
{
1454 self.write_formatted_parts(&formatted
)
1456 let post_padding
= self.padding(width
- len
, align
)?
;
1457 self.write_formatted_parts(&formatted
)?
;
1458 post_padding
.write(self.buf
)
1460 self.fill
= old_fill
;
1461 self.align
= old_align
;
1464 // this is the common case and we take a shortcut
1465 self.write_formatted_parts(formatted
)
1469 fn write_formatted_parts(&mut self, formatted
: &numfmt
::Formatted
<'_
>) -> Result
{
1470 fn write_bytes(buf
: &mut dyn Write
, s
: &[u8]) -> Result
{
1471 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1472 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1473 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1474 // It's also probably safe in practice to use for `numfmt::Part::Copy(buf)`
1475 // since `buf` should be plain ASCII, but it's possible for someone to pass
1476 // in a bad value for `buf` into `numfmt::to_shortest_str` since it is a
1478 // FIXME: Determine whether this could result in UB.
1479 buf
.write_str(unsafe { str::from_utf8_unchecked(s) }
)
1482 if !formatted
.sign
.is_empty() {
1483 self.buf
.write_str(formatted
.sign
)?
;
1485 for part
in formatted
.parts
{
1487 numfmt
::Part
::Zero(mut nzeroes
) => {
1488 const ZEROES
: &str = // 64 zeroes
1489 "0000000000000000000000000000000000000000000000000000000000000000";
1490 while nzeroes
> ZEROES
.len() {
1491 self.buf
.write_str(ZEROES
)?
;
1492 nzeroes
-= ZEROES
.len();
1495 self.buf
.write_str(&ZEROES
[..nzeroes
])?
;
1498 numfmt
::Part
::Num(mut v
) => {
1500 let len
= part
.len();
1501 for c
in s
[..len
].iter_mut().rev() {
1502 *c
= b'
0'
+ (v
% 10) as u8;
1505 write_bytes(self.buf
, &s
[..len
])?
;
1507 numfmt
::Part
::Copy(buf
) => {
1508 write_bytes(self.buf
, buf
)?
;
1515 /// Writes some data to the underlying buffer contained within this
1525 /// impl fmt::Display for Foo {
1526 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1527 /// formatter.write_str("Foo")
1528 /// // This is equivalent to:
1529 /// // write!(formatter, "Foo")
1533 /// assert_eq!(&format!("{}", Foo), "Foo");
1534 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 pub fn write_str(&mut self, data
: &str) -> Result
{
1538 self.buf
.write_str(data
)
1541 /// Writes some formatted information into this instance.
1548 /// struct Foo(i32);
1550 /// impl fmt::Display for Foo {
1551 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1552 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1556 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1557 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 pub fn write_fmt(&mut self, fmt
: Arguments
<'_
>) -> Result
{
1561 write(self.buf
, fmt
)
1564 /// Flags for formatting
1565 #[stable(feature = "rust1", since = "1.0.0")]
1568 reason
= "use the `sign_plus`, `sign_minus`, `alternate`, \
1569 or `sign_aware_zero_pad` methods instead"
1571 pub fn flags(&self) -> u32 {
1575 /// Character used as 'fill' whenever there is alignment.
1584 /// impl fmt::Display for Foo {
1585 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1586 /// let c = formatter.fill();
1587 /// if let Some(width) = formatter.width() {
1588 /// for _ in 0..width {
1589 /// write!(formatter, "{}", c)?;
1593 /// write!(formatter, "{}", c)
1598 /// // We set alignment to the right with ">".
1599 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1600 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1602 #[stable(feature = "fmt_flags", since = "1.5.0")]
1603 pub fn fill(&self) -> char {
1607 /// Flag indicating what form of alignment was requested.
1612 /// extern crate core;
1614 /// use std::fmt::{self, Alignment};
1618 /// impl fmt::Display for Foo {
1619 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1620 /// let s = if let Some(s) = formatter.align() {
1622 /// Alignment::Left => "left",
1623 /// Alignment::Right => "right",
1624 /// Alignment::Center => "center",
1629 /// write!(formatter, "{}", s)
1633 /// assert_eq!(&format!("{:<}", Foo), "left");
1634 /// assert_eq!(&format!("{:>}", Foo), "right");
1635 /// assert_eq!(&format!("{:^}", Foo), "center");
1636 /// assert_eq!(&format!("{}", Foo), "into the void");
1638 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1639 pub fn align(&self) -> Option
<Alignment
> {
1641 rt
::v1
::Alignment
::Left
=> Some(Alignment
::Left
),
1642 rt
::v1
::Alignment
::Right
=> Some(Alignment
::Right
),
1643 rt
::v1
::Alignment
::Center
=> Some(Alignment
::Center
),
1644 rt
::v1
::Alignment
::Unknown
=> None
,
1648 /// Optionally specified integer width that the output should be.
1655 /// struct Foo(i32);
1657 /// impl fmt::Display for Foo {
1658 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1659 /// if let Some(width) = formatter.width() {
1660 /// // If we received a width, we use it
1661 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1663 /// // Otherwise we do nothing special
1664 /// write!(formatter, "Foo({})", self.0)
1669 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1670 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1672 #[stable(feature = "fmt_flags", since = "1.5.0")]
1673 pub fn width(&self) -> Option
<usize> {
1677 /// Optionally specified precision for numeric types. Alternatively, the
1678 /// maximum width for string types.
1685 /// struct Foo(f32);
1687 /// impl fmt::Display for Foo {
1688 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1689 /// if let Some(precision) = formatter.precision() {
1690 /// // If we received a precision, we use it.
1691 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1693 /// // Otherwise we default to 2.
1694 /// write!(formatter, "Foo({:.2})", self.0)
1699 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1700 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1702 #[stable(feature = "fmt_flags", since = "1.5.0")]
1703 pub fn precision(&self) -> Option
<usize> {
1707 /// Determines if the `+` flag was specified.
1714 /// struct Foo(i32);
1716 /// impl fmt::Display for Foo {
1717 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1718 /// if formatter.sign_plus() {
1719 /// write!(formatter,
1721 /// if self.0 < 0 { '-' } else { '+' },
1724 /// write!(formatter, "Foo({})", self.0)
1729 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1730 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1732 #[stable(feature = "fmt_flags", since = "1.5.0")]
1733 pub fn sign_plus(&self) -> bool
{
1734 self.flags
& (1 << FlagV1
::SignPlus
as u32) != 0
1737 /// Determines if the `-` flag was specified.
1744 /// struct Foo(i32);
1746 /// impl fmt::Display for Foo {
1747 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1748 /// if formatter.sign_minus() {
1749 /// // You want a minus sign? Have one!
1750 /// write!(formatter, "-Foo({})", self.0)
1752 /// write!(formatter, "Foo({})", self.0)
1757 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1758 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1760 #[stable(feature = "fmt_flags", since = "1.5.0")]
1761 pub fn sign_minus(&self) -> bool
{
1762 self.flags
& (1 << FlagV1
::SignMinus
as u32) != 0
1765 /// Determines if the `#` flag was specified.
1772 /// struct Foo(i32);
1774 /// impl fmt::Display for Foo {
1775 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1776 /// if formatter.alternate() {
1777 /// write!(formatter, "Foo({})", self.0)
1779 /// write!(formatter, "{}", self.0)
1784 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1785 /// assert_eq!(&format!("{}", Foo(23)), "23");
1787 #[stable(feature = "fmt_flags", since = "1.5.0")]
1788 pub fn alternate(&self) -> bool
{
1789 self.flags
& (1 << FlagV1
::Alternate
as u32) != 0
1792 /// Determines if the `0` flag was specified.
1799 /// struct Foo(i32);
1801 /// impl fmt::Display for Foo {
1802 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1803 /// assert!(formatter.sign_aware_zero_pad());
1804 /// assert_eq!(formatter.width(), Some(4));
1805 /// // We ignore the formatter's options.
1806 /// write!(formatter, "{}", self.0)
1810 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1812 #[stable(feature = "fmt_flags", since = "1.5.0")]
1813 pub fn sign_aware_zero_pad(&self) -> bool
{
1814 self.flags
& (1 << FlagV1
::SignAwareZeroPad
as u32) != 0
1817 // FIXME: Decide what public API we want for these two flags.
1818 // https://github.com/rust-lang/rust/issues/48584
1819 fn debug_lower_hex(&self) -> bool
{
1820 self.flags
& (1 << FlagV1
::DebugLowerHex
as u32) != 0
1823 fn debug_upper_hex(&self) -> bool
{
1824 self.flags
& (1 << FlagV1
::DebugUpperHex
as u32) != 0
1827 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1828 /// [`fmt::Debug`] implementations for structs.
1830 /// [`fmt::Debug`]: self::Debug
1836 /// use std::net::Ipv4Addr;
1844 /// impl fmt::Debug for Foo {
1845 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1846 /// fmt.debug_struct("Foo")
1847 /// .field("bar", &self.bar)
1848 /// .field("baz", &self.baz)
1849 /// .field("addr", &format_args!("{}", self.addr))
1855 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1856 /// format!("{:?}", Foo {
1858 /// baz: "Hello World".to_string(),
1859 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1863 #[stable(feature = "debug_builders", since = "1.2.0")]
1864 pub fn debug_struct
<'b
>(&'b
mut self, name
: &str) -> DebugStruct
<'b
, 'a
> {
1865 builders
::debug_struct_new(self, name
)
1868 /// Creates a `DebugTuple` builder designed to assist with creation of
1869 /// `fmt::Debug` implementations for tuple structs.
1875 /// use std::marker::PhantomData;
1877 /// struct Foo<T>(i32, String, PhantomData<T>);
1879 /// impl<T> fmt::Debug for Foo<T> {
1880 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1881 /// fmt.debug_tuple("Foo")
1884 /// .field(&format_args!("_"))
1890 /// "Foo(10, \"Hello\", _)",
1891 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1894 #[stable(feature = "debug_builders", since = "1.2.0")]
1895 pub fn debug_tuple
<'b
>(&'b
mut self, name
: &str) -> DebugTuple
<'b
, 'a
> {
1896 builders
::debug_tuple_new(self, name
)
1899 /// Creates a `DebugList` builder designed to assist with creation of
1900 /// `fmt::Debug` implementations for list-like structures.
1907 /// struct Foo(Vec<i32>);
1909 /// impl fmt::Debug for Foo {
1910 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1911 /// fmt.debug_list().entries(self.0.iter()).finish()
1915 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
1917 #[stable(feature = "debug_builders", since = "1.2.0")]
1918 pub fn debug_list
<'b
>(&'b
mut self) -> DebugList
<'b
, 'a
> {
1919 builders
::debug_list_new(self)
1922 /// Creates a `DebugSet` builder designed to assist with creation of
1923 /// `fmt::Debug` implementations for set-like structures.
1930 /// struct Foo(Vec<i32>);
1932 /// impl fmt::Debug for Foo {
1933 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1934 /// fmt.debug_set().entries(self.0.iter()).finish()
1938 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
1941 /// [`format_args!`]: crate::format_args
1943 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1944 /// to build a list of match arms:
1949 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1950 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1952 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1954 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1956 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1957 /// L::fmt(&(self.0).0, fmt)?;
1958 /// fmt.write_str(" => ")?;
1959 /// R::fmt(&(self.0).1, fmt)
1963 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1965 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1967 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1969 /// .entries(self.0.iter().map(Arm))
1970 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1975 #[stable(feature = "debug_builders", since = "1.2.0")]
1976 pub fn debug_set
<'b
>(&'b
mut self) -> DebugSet
<'b
, 'a
> {
1977 builders
::debug_set_new(self)
1980 /// Creates a `DebugMap` builder designed to assist with creation of
1981 /// `fmt::Debug` implementations for map-like structures.
1988 /// struct Foo(Vec<(String, i32)>);
1990 /// impl fmt::Debug for Foo {
1991 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1992 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1997 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1998 /// r#"{"A": 10, "B": 11}"#
2001 #[stable(feature = "debug_builders", since = "1.2.0")]
2002 pub fn debug_map
<'b
>(&'b
mut self) -> DebugMap
<'b
, 'a
> {
2003 builders
::debug_map_new(self)
2007 #[stable(since = "1.2.0", feature = "formatter_write")]
2008 impl Write
for Formatter
<'_
> {
2009 fn write_str(&mut self, s
: &str) -> Result
{
2010 self.buf
.write_str(s
)
2013 fn write_char(&mut self, c
: char) -> Result
{
2014 self.buf
.write_char(c
)
2017 fn write_fmt(&mut self, args
: Arguments
<'_
>) -> Result
{
2018 write(self.buf
, args
)
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 impl Display
for Error
{
2024 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2025 Display
::fmt("an error occurred when formatting an argument", f
)
2029 // Implementations of the core formatting traits
2031 macro_rules
! fmt_refs
{
2032 ($
($tr
:ident
),*) => {
2034 #[stable(feature = "rust1", since = "1.0.0")]
2035 impl<T
: ?Sized
+ $tr
> $tr
for &T
{
2036 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result { $tr::fmt(&**self, f) }
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 impl<T
: ?Sized
+ $tr
> $tr
for &mut T
{
2040 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result { $tr::fmt(&**self, f) }
2046 fmt_refs
! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2048 #[unstable(feature = "never_type", issue = "35121")]
2050 fn fmt(&self, _
: &mut Formatter
<'_
>) -> Result
{
2055 #[unstable(feature = "never_type", issue = "35121")]
2056 impl Display
for ! {
2057 fn fmt(&self, _
: &mut Formatter
<'_
>) -> Result
{
2062 #[stable(feature = "rust1", since = "1.0.0")]
2063 impl Debug
for bool
{
2065 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2066 Display
::fmt(self, f
)
2070 #[stable(feature = "rust1", since = "1.0.0")]
2071 impl Display
for bool
{
2072 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2073 Display
::fmt(if *self { "true" }
else { "false" }
, f
)
2077 #[stable(feature = "rust1", since = "1.0.0")]
2078 impl Debug
for str {
2079 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2082 for (i, c) in self.char_indices() {
2083 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2084 escape_grapheme_extended: true,
2085 escape_single_quote: false,
2086 escape_double_quote: true,
2088 // If char needs escaping, flush backlog so far and write, else skip
2090 f.write_str(&self[from..i])?;
2094 from = i + c.len_utf8();
2097 f.write_str(&self[from..])?;
2102 #[stable(feature = "rust1", since = "1.0.0")]
2103 impl Display
for str {
2104 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2109 #[stable(feature = "rust1", since = "1.0.0")]
2110 impl Debug
for char {
2111 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2112 f
.write_char('
\''
)?
;
2113 for c
in self.escape_debug_ext(EscapeDebugExtArgs
{
2114 escape_grapheme_extended
: true,
2115 escape_single_quote
: true,
2116 escape_double_quote
: false,
2124 #[stable(feature = "rust1", since = "1.0.0")]
2125 impl Display
for char {
2126 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2127 if f
.width
.is_none() && f
.precision
.is_none() {
2130 f
.pad(self.encode_utf8(&mut [0; 4]))
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 impl<T
: ?Sized
> Pointer
for *const T
{
2137 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2138 let old_width
= f
.width
;
2139 let old_flags
= f
.flags
;
2141 // The alternate flag is already treated by LowerHex as being special-
2142 // it denotes whether to prefix with 0x. We use it to work out whether
2143 // or not to zero extend, and then unconditionally set it to get the
2146 f
.flags
|= 1 << (FlagV1
::SignAwareZeroPad
as u32);
2148 if f
.width
.is_none() {
2149 f
.width
= Some((usize::BITS
/ 4) as usize + 2);
2152 f
.flags
|= 1 << (FlagV1
::Alternate
as u32);
2154 let ret
= LowerHex
::fmt(&(*self as *const () as usize), f
);
2156 f
.width
= old_width
;
2157 f
.flags
= old_flags
;
2163 #[stable(feature = "rust1", since = "1.0.0")]
2164 impl<T
: ?Sized
> Pointer
for *mut T
{
2165 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2166 Pointer
::fmt(&(*self as *const T
), f
)
2170 #[stable(feature = "rust1", since = "1.0.0")]
2171 impl<T
: ?Sized
> Pointer
for &T
{
2172 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2173 Pointer
::fmt(&(*self as *const T
), f
)
2177 #[stable(feature = "rust1", since = "1.0.0")]
2178 impl<T
: ?Sized
> Pointer
for &mut T
{
2179 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2180 Pointer
::fmt(&(&**self as *const T
), f
)
2184 // Implementation of Display/Debug for various core types
2186 #[stable(feature = "rust1", since = "1.0.0")]
2187 impl<T
: ?Sized
> Debug
for *const T
{
2188 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2189 Pointer
::fmt(self, f
)
2192 #[stable(feature = "rust1", since = "1.0.0")]
2193 impl<T
: ?Sized
> Debug
for *mut T
{
2194 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2195 Pointer
::fmt(self, f
)
2200 ($name
:ident
, $
($other
:ident
,)*) => (tuple
! { $($other,)* }
)
2203 macro_rules
! tuple
{
2205 ( $
($name
:ident
,)+ ) => (
2206 #[stable(feature = "rust1", since = "1.0.0")]
2207 impl<$
($name
:Debug
),+> Debug
for ($
($name
,)+) where last_type
!($
($name
,)+): ?Sized
{
2208 #[allow(non_snake_case, unused_assignments)]
2209 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2210 let mut builder
= f
.debug_tuple("");
2211 let ($
(ref $name
,)+) = *self;
2213 builder
.field(&$name
);
2219 peel
! { $($name,)+ }
2223 macro_rules
! last_type
{
2224 ($a
:ident
,) => { $a }
;
2225 ($a
:ident
, $
($rest_a
:ident
,)+) => { last_type!($($rest_a,)+) }
;
2228 tuple
! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2230 #[stable(feature = "rust1", since = "1.0.0")]
2231 impl<T
: Debug
> Debug
for [T
] {
2232 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2233 f
.debug_list().entries(self.iter()).finish()
2237 #[stable(feature = "rust1", since = "1.0.0")]
2240 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2244 #[stable(feature = "rust1", since = "1.0.0")]
2245 impl<T
: ?Sized
> Debug
for PhantomData
<T
> {
2246 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2247 f
.debug_struct("PhantomData").finish()
2251 #[stable(feature = "rust1", since = "1.0.0")]
2252 impl<T
: Copy
+ Debug
> Debug
for Cell
<T
> {
2253 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2254 f
.debug_struct("Cell").field("value", &self.get()).finish()
2258 #[stable(feature = "rust1", since = "1.0.0")]
2259 impl<T
: ?Sized
+ Debug
> Debug
for RefCell
<T
> {
2260 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2261 match self.try_borrow() {
2262 Ok(borrow
) => f
.debug_struct("RefCell").field("value", &borrow
).finish(),
2264 // The RefCell is mutably borrowed so we can't look at its value
2265 // here. Show a placeholder instead.
2266 struct BorrowedPlaceholder
;
2268 impl Debug
for BorrowedPlaceholder
{
2269 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2270 f
.write_str("<borrowed>")
2274 f
.debug_struct("RefCell").field("value", &BorrowedPlaceholder
).finish()
2280 #[stable(feature = "rust1", since = "1.0.0")]
2281 impl<T
: ?Sized
+ Debug
> Debug
for Ref
<'_
, T
> {
2282 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2283 Debug
::fmt(&**self, f
)
2287 #[stable(feature = "rust1", since = "1.0.0")]
2288 impl<T
: ?Sized
+ Debug
> Debug
for RefMut
<'_
, T
> {
2289 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2290 Debug
::fmt(&*(self.deref()), f
)
2294 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2295 impl<T
: ?Sized
> Debug
for UnsafeCell
<T
> {
2296 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2297 f
.debug_struct("UnsafeCell").finish_non_exhaustive()
2301 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2302 // it's a lot easier than creating all of the rt::Piece structures here.
2303 // There are also tests in the alloc crate, for those that need allocations.