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::marker
::PhantomData
;
8 use crate::num
::flt2dec
;
17 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
18 /// Possible alignments returned by `Formatter::align`
21 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
22 /// Indication that contents should be left-aligned.
24 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
25 /// Indication that contents should be right-aligned.
27 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
28 /// Indication that contents should be center-aligned.
32 #[stable(feature = "debug_builders", since = "1.2.0")]
33 pub use self::builders
::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}
;
35 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
41 /// The type returned by formatter methods.
55 /// impl fmt::Display for Triangle {
56 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
61 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
63 /// assert_eq!(format!("{}", pythagorean_triple), "(3, 4, 5)");
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub type Result
= result
::Result
<(), Error
>;
68 /// The error type which is returned from formatting a message into a stream.
70 /// This type does not support transmission of an error other than that an error
71 /// occurred. Any extra information must be arranged to be transmitted through
74 /// An important thing to remember is that the type `fmt::Error` should not be
75 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
78 /// [`std::io::Error`]: ../../std/io/struct.Error.html
79 /// [`std::error::Error`]: ../../std/error/trait.Error.html
84 /// use std::fmt::{self, write};
86 /// let mut output = String::new();
87 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
88 /// panic!("An error occurred");
91 #[stable(feature = "rust1", since = "1.0.0")]
92 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
95 /// A trait for writing or formatting into Unicode-accepting buffers or streams.
97 /// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
98 /// want to accept Unicode and you don't need flushing, you should implement this trait;
99 /// otherwise you should implement [`std::io::Write`].
101 /// [`std::io::Write`]: ../../std/io/trait.Write.html
102 /// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
103 #[stable(feature = "rust1", since = "1.0.0")]
105 /// Writes a string slice into this writer, returning whether the write
108 /// This method can only succeed if the entire string slice was successfully
109 /// written, and this method will not return until all data has been
110 /// written or an error occurs.
114 /// This function will return an instance of [`Error`] on error.
119 /// use std::fmt::{Error, Write};
121 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
125 /// let mut buf = String::new();
126 /// writer(&mut buf, "hola").unwrap();
127 /// assert_eq!(&buf, "hola");
129 #[stable(feature = "rust1", since = "1.0.0")]
130 fn write_str(&mut self, s
: &str) -> Result
;
132 /// Writes a [`char`] into this writer, returning whether the write succeeded.
134 /// A single [`char`] may be encoded as more than one byte.
135 /// This method can only succeed if the entire byte sequence was successfully
136 /// written, and this method will not return until all data has been
137 /// written or an error occurs.
141 /// This function will return an instance of [`Error`] on error.
146 /// use std::fmt::{Error, Write};
148 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
152 /// let mut buf = String::new();
153 /// writer(&mut buf, 'a').unwrap();
154 /// writer(&mut buf, 'b').unwrap();
155 /// assert_eq!(&buf, "ab");
157 #[stable(feature = "fmt_write_char", since = "1.1.0")]
158 fn write_char(&mut self, c
: char) -> Result
{
159 self.write_str(c
.encode_utf8(&mut [0; 4]))
162 /// Glue for usage of the [`write!`] macro with implementors of this trait.
164 /// This method should generally not be invoked manually, but rather through
165 /// the [`write!`] macro itself.
170 /// use std::fmt::{Error, Write};
172 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
173 /// f.write_fmt(format_args!("{}", s))
176 /// let mut buf = String::new();
177 /// writer(&mut buf, "world").unwrap();
178 /// assert_eq!(&buf, "world");
180 #[stable(feature = "rust1", since = "1.0.0")]
181 fn write_fmt(mut self: &mut Self, args
: Arguments
<'_
>) -> Result
{
182 write(&mut self, args
)
186 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
187 impl<W
: Write
+ ?Sized
> Write
for &mut W
{
188 fn write_str(&mut self, s
: &str) -> Result
{
189 (**self).write_str(s
)
192 fn write_char(&mut self, c
: char) -> Result
{
193 (**self).write_char(c
)
196 fn write_fmt(&mut self, args
: Arguments
<'_
>) -> Result
{
197 (**self).write_fmt(args
)
201 /// Configuration for formatting.
203 /// A `Formatter` represents various options related to formatting. Users do not
204 /// construct `Formatter`s directly; a mutable reference to one is passed to
205 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
207 /// To interact with a `Formatter`, you'll call various methods to change the
208 /// various options related to formatting. For examples, please see the
209 /// documentation of the methods defined on `Formatter` below.
210 #[allow(missing_debug_implementations)]
211 #[stable(feature = "rust1", since = "1.0.0")]
212 pub struct Formatter
<'a
> {
215 align
: rt
::v1
::Alignment
,
216 width
: Option
<usize>,
217 precision
: Option
<usize>,
219 buf
: &'a
mut (dyn Write
+ 'a
),
222 // NB. Argument is essentially an optimized partially applied formatting function,
223 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
229 /// This struct represents the generic "argument" which is taken by the Xprintf
230 /// family of functions. It contains a function to format the given value. At
231 /// compile time it is ensured that the function and the value have the correct
232 /// types, and then this struct is used to canonicalize arguments to one type.
233 #[derive(Copy, Clone)]
234 #[allow(missing_debug_implementations)]
235 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
237 pub struct ArgumentV1
<'a
> {
239 formatter
: fn(&Opaque
, &mut Formatter
<'_
>) -> Result
,
242 // This guarantees a single stable value for the function pointer associated with
243 // indices/counts in the formatting infrastructure.
245 // Note that a function defined as such would not be correct as functions are
246 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
247 // address is not considered important to LLVM and as such the as_usize cast
248 // could have been miscompiled. In practice, we never call as_usize on non-usize
249 // containing data (as a matter of static generation of the formatting
250 // arguments), so this is merely an additional check.
252 // We primarily want to ensure that the function pointer at `USIZE_MARKER` has
253 // an address corresponding *only* to functions that also take `&usize` as their
254 // first argument. The read_volatile here ensures that we can safely ready out a
255 // usize from the passed reference and that this address does not point at a
256 // non-usize taking function.
257 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
258 static USIZE_MARKER
: fn(&usize, &mut Formatter
<'_
>) -> Result
= |ptr
, _
| {
259 // SAFETY: ptr is a reference
260 let _v
: usize = unsafe { crate::ptr::read_volatile(ptr) }
;
264 impl<'a
> ArgumentV1
<'a
> {
266 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
267 pub fn new
<'b
, T
>(x
: &'b T
, f
: fn(&T
, &mut Formatter
<'_
>) -> Result
) -> ArgumentV1
<'b
> {
268 // SAFETY: `mem::transmute(x)` is safe because
269 // 1. `&'b T` keeps the lifetime it originated with `'b`
270 // (so as to not have an unbounded lifetime)
271 // 2. `&'b T` and `&'b Opaque` have the same memory layout
272 // (when `T` is `Sized`, as it is here)
273 // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
274 // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
275 // (as long as `T` is `Sized`)
276 unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) }
}
280 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
281 pub fn from_usize(x
: &usize) -> ArgumentV1
<'_
> {
282 ArgumentV1
::new(x
, USIZE_MARKER
)
285 fn as_usize(&self) -> Option
<usize> {
286 if self.formatter
as usize == USIZE_MARKER
as usize {
287 // SAFETY: The `formatter` field is only set to USIZE_MARKER if
288 // the value is a usize, so this is safe
289 Some(unsafe { *(self.value as *const _ as *const usize) }
)
296 // flags available in the v1 format of format_args
297 #[derive(Copy, Clone)]
307 impl<'a
> Arguments
<'a
> {
308 /// When using the format_args!() macro, this function is used to generate the
309 /// Arguments structure.
312 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
313 pub fn new_v1(pieces
: &'a
[&'
static str], args
: &'a
[ArgumentV1
<'a
>]) -> Arguments
<'a
> {
314 Arguments { pieces, fmt: None, args }
317 /// This function is used to specify nonstandard formatting parameters.
318 /// The `pieces` array must be at least as long as `fmt` to construct
319 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
320 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
321 /// created with `argumentusize`. However, failing to do so doesn't cause
322 /// unsafety, but will ignore invalid .
325 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
326 pub fn new_v1_formatted(
327 pieces
: &'a
[&'
static str],
328 args
: &'a
[ArgumentV1
<'a
>],
329 fmt
: &'a
[rt
::v1
::Argument
],
331 Arguments { pieces, fmt: Some(fmt), args }
334 /// Estimates the length of the formatted text.
336 /// This is intended to be used for setting initial `String` capacity
337 /// when using `format!`. Note: this is neither the lower nor upper bound.
340 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
341 pub fn estimated_capacity(&self) -> usize {
342 let pieces_length
: usize = self.pieces
.iter().map(|x
| x
.len()).sum();
344 if self.args
.is_empty() {
346 } else if self.pieces
[0] == "" && pieces_length
< 16 {
347 // If the format string starts with an argument,
348 // don't preallocate anything, unless length
349 // of pieces is significant.
352 // There are some arguments, so any additional push
353 // will reallocate the string. To avoid that,
354 // we're "pre-doubling" the capacity here.
355 pieces_length
.checked_mul(2).unwrap_or(0)
360 /// This structure represents a safely precompiled version of a format string
361 /// and its arguments. This cannot be generated at runtime because it cannot
362 /// safely be done, so no constructors are given and the fields are private
363 /// to prevent modification.
365 /// The [`format_args!`] macro will safely create an instance of this structure.
366 /// The macro validates the format string at compile-time so usage of the
367 /// [`write()`] and [`format()`] functions can be safely performed.
369 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
370 /// and `Display` contexts as seen below. The example also shows that `Debug`
371 /// and `Display` format to the same thing: the interpolated format string
372 /// in `format_args!`.
375 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
376 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
377 /// assert_eq!("1 foo 2", display);
378 /// assert_eq!(display, debug);
381 /// [`format()`]: ../../std/fmt/fn.format.html
382 #[stable(feature = "rust1", since = "1.0.0")]
383 #[derive(Copy, Clone)]
384 pub struct Arguments
<'a
> {
385 // Format string pieces to print.
386 pieces
: &'a
[&'
static str],
388 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
389 fmt
: Option
<&'a
[rt
::v1
::Argument
]>,
391 // Dynamic arguments for interpolation, to be interleaved with string
392 // pieces. (Every argument is preceded by a string piece.)
393 args
: &'a
[ArgumentV1
<'a
>],
396 impl<'a
> Arguments
<'a
> {
397 /// Get the formatted string, if it has no arguments to be formatted.
399 /// This can be used to avoid allocations in the most trivial case.
404 /// #![feature(fmt_as_str)]
406 /// use std::fmt::Arguments;
408 /// fn write_str(_: &str) { /* ... */ }
410 /// fn write_fmt(args: &Arguments) {
411 /// if let Some(s) = args.as_str() {
414 /// write_str(&args.to_string());
420 /// #![feature(fmt_as_str)]
422 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
423 /// assert_eq!(format_args!("").as_str(), Some(""));
424 /// assert_eq!(format_args!("{}", 1).as_str(), None);
426 #[unstable(feature = "fmt_as_str", issue = "74442")]
428 pub fn as_str(&self) -> Option
<&'
static str> {
429 match (self.pieces
, self.args
) {
430 ([], []) => Some(""),
431 ([s
], []) => Some(s
),
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl Debug
for Arguments
<'_
> {
439 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> Result
{
440 Display
::fmt(self, fmt
)
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl Display
for Arguments
<'_
> {
446 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> Result
{
447 write(fmt
.buf
, *self)
453 /// `Debug` should format the output in a programmer-facing, debugging context.
455 /// Generally speaking, you should just `derive` a `Debug` implementation.
457 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
459 /// For more information on formatters, see [the module-level documentation][module].
461 /// [module]: ../../std/fmt/index.html
463 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
464 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
465 /// comma-separated list of each field's name and `Debug` value, then `}`. For
466 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
467 /// `Debug` values of the fields, then `)`.
471 /// Derived `Debug` formats are not stable, and so may change with future Rust
472 /// versions. Additionally, `Debug` implementations of types provided by the
473 /// standard library (`libstd`, `libcore`, `liballoc`, etc.) are not stable, and
474 /// may also change with future Rust versions.
478 /// Deriving an implementation:
487 /// let origin = Point { x: 0, y: 0 };
489 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
492 /// Manually implementing:
502 /// impl fmt::Debug for Point {
503 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 /// f.debug_struct("Point")
505 /// .field("x", &self.x)
506 /// .field("y", &self.y)
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 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
517 /// implementations, such as [`debug_struct`].
519 /// `Debug` implementations using either `derive` or the debug builder API
520 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
522 /// [`debug_struct`]: Formatter::debug_struct
524 /// Pretty-printing with `#?`:
533 /// let origin = Point { x: 0, y: 0 };
535 /// assert_eq!(format!("The origin is: {:#?}", origin),
536 /// "The origin is: Point {
542 #[stable(feature = "rust1", since = "1.0.0")]
543 #[rustc_on_unimplemented(
546 label
= "`{Self}` cannot be formatted using `{{:?}}`",
547 note
= "add `#[derive(Debug)]` or manually implement `{Debug}`"
549 message
= "`{Self}` doesn't implement `{Debug}`",
550 label
= "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
552 #[doc(alias = "{:?}")]
553 #[rustc_diagnostic_item = "debug_trait"]
555 /// Formats the value using the given formatter.
562 /// struct Position {
567 /// impl fmt::Debug for Position {
568 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
569 /// f.debug_tuple("")
570 /// .field(&self.longitude)
571 /// .field(&self.latitude)
576 /// let position = Position { longitude: 1.987, latitude: 2.983 };
577 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
579 /// assert_eq!(format!("{:#?}", position), "(
584 #[stable(feature = "rust1", since = "1.0.0")]
585 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
588 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
589 pub(crate) mod macros
{
590 /// Derive macro generating an impl of the trait `Debug`.
591 #[rustc_builtin_macro]
592 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
593 #[allow_internal_unstable(core_intrinsics)]
594 pub macro Debug($item
:item
) {
595 /* compiler built-in */
598 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
600 pub use macros
::Debug
;
602 /// Format trait for an empty format, `{}`.
604 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
605 /// output, and so cannot be derived.
607 /// For more information on formatters, see [the module-level documentation][module].
609 /// [module]: ../../std/fmt/index.html
613 /// Implementing `Display` on a type:
623 /// impl fmt::Display for Point {
624 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
625 /// write!(f, "({}, {})", self.x, self.y)
629 /// let origin = Point { x: 0, y: 0 };
631 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
633 #[rustc_on_unimplemented(
635 _Self
= "std::path::Path",
636 label
= "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
637 note
= "call `.display()` or `.to_string_lossy()` to safely print paths, \
638 as they may contain non-Unicode data"
640 message
= "`{Self}` doesn't implement `{Display}`",
641 label
= "`{Self}` cannot be formatted with the default formatter",
642 note
= "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
645 #[stable(feature = "rust1", since = "1.0.0")]
647 /// Formats the value using the given formatter.
654 /// struct Position {
659 /// impl fmt::Display for Position {
660 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 /// write!(f, "({}, {})", self.longitude, self.latitude)
665 /// assert_eq!("(1.987, 2.983)",
666 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
674 /// The `Octal` trait should format its output as a number in base-8.
676 /// For primitive signed integers (`i8` to `i128`, and `isize`),
677 /// negative values are formatted as the two’s complement representation.
679 /// The alternate flag, `#`, adds a `0o` in front of the output.
681 /// For more information on formatters, see [the module-level documentation][module].
683 /// [module]: ../../std/fmt/index.html
687 /// Basic usage with `i32`:
690 /// let x = 42; // 42 is '52' in octal
692 /// assert_eq!(format!("{:o}", x), "52");
693 /// assert_eq!(format!("{:#o}", x), "0o52");
695 /// assert_eq!(format!("{:o}", -16), "37777777760");
698 /// Implementing `Octal` on a type:
703 /// struct Length(i32);
705 /// impl fmt::Octal for Length {
706 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707 /// let val = self.0;
709 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
713 /// let l = Length(9);
715 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
717 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
719 #[stable(feature = "rust1", since = "1.0.0")]
721 /// Formats the value using the given formatter.
722 #[stable(feature = "rust1", since = "1.0.0")]
723 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
728 /// The `Binary` trait should format its output as a number in binary.
730 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
731 /// negative values are formatted as the two’s complement representation.
733 /// The alternate flag, `#`, adds a `0b` in front of the output.
735 /// For more information on formatters, see [the module-level documentation][module].
737 /// [module]: ../../std/fmt/index.html
741 /// Basic usage with [`i32`]:
744 /// let x = 42; // 42 is '101010' in binary
746 /// assert_eq!(format!("{:b}", x), "101010");
747 /// assert_eq!(format!("{:#b}", x), "0b101010");
749 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
752 /// Implementing `Binary` on a type:
757 /// struct Length(i32);
759 /// impl fmt::Binary for Length {
760 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
761 /// let val = self.0;
763 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
767 /// let l = Length(107);
769 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
772 /// format!("l as binary is: {:#032b}", l),
773 /// "l as binary is: 0b000000000000000000000001101011"
776 #[stable(feature = "rust1", since = "1.0.0")]
778 /// Formats the value using the given formatter.
779 #[stable(feature = "rust1", since = "1.0.0")]
780 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
785 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
788 /// For primitive signed integers (`i8` to `i128`, and `isize`),
789 /// negative values are formatted as the two’s complement representation.
791 /// The alternate flag, `#`, adds a `0x` in front of the output.
793 /// For more information on formatters, see [the module-level documentation][module].
795 /// [module]: ../../std/fmt/index.html
799 /// Basic usage with `i32`:
802 /// let x = 42; // 42 is '2a' in hex
804 /// assert_eq!(format!("{:x}", x), "2a");
805 /// assert_eq!(format!("{:#x}", x), "0x2a");
807 /// assert_eq!(format!("{:x}", -16), "fffffff0");
810 /// Implementing `LowerHex` on a type:
815 /// struct Length(i32);
817 /// impl fmt::LowerHex for Length {
818 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
819 /// let val = self.0;
821 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
825 /// let l = Length(9);
827 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
829 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
831 #[stable(feature = "rust1", since = "1.0.0")]
833 /// Formats the value using the given formatter.
834 #[stable(feature = "rust1", since = "1.0.0")]
835 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
840 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
843 /// For primitive signed integers (`i8` to `i128`, and `isize`),
844 /// negative values are formatted as the two’s complement representation.
846 /// The alternate flag, `#`, adds a `0x` in front of the output.
848 /// For more information on formatters, see [the module-level documentation][module].
850 /// [module]: ../../std/fmt/index.html
854 /// Basic usage with `i32`:
857 /// let x = 42; // 42 is '2A' in hex
859 /// assert_eq!(format!("{:X}", x), "2A");
860 /// assert_eq!(format!("{:#X}", x), "0x2A");
862 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
865 /// Implementing `UpperHex` on a type:
870 /// struct Length(i32);
872 /// impl fmt::UpperHex for Length {
873 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
874 /// let val = self.0;
876 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
880 /// let l = Length(i32::MAX);
882 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
884 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
886 #[stable(feature = "rust1", since = "1.0.0")]
888 /// Formats the value using the given formatter.
889 #[stable(feature = "rust1", since = "1.0.0")]
890 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
895 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
898 /// For more information on formatters, see [the module-level documentation][module].
900 /// [module]: ../../std/fmt/index.html
904 /// Basic usage with `&i32`:
909 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
912 /// Implementing `Pointer` on a type:
917 /// struct Length(i32);
919 /// impl fmt::Pointer for Length {
920 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
921 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
923 /// let ptr = self as *const Self;
924 /// fmt::Pointer::fmt(&ptr, f)
928 /// let l = Length(42);
930 /// println!("l is in memory here: {:p}", l);
932 /// let l_ptr = format!("{:018p}", l);
933 /// assert_eq!(l_ptr.len(), 18);
934 /// assert_eq!(&l_ptr[..2], "0x");
936 #[stable(feature = "rust1", since = "1.0.0")]
937 #[rustc_diagnostic_item = "pointer_trait"]
939 /// Formats the value using the given formatter.
940 #[stable(feature = "rust1", since = "1.0.0")]
941 #[rustc_diagnostic_item = "pointer_trait_fmt"]
942 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
947 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
949 /// For more information on formatters, see [the module-level documentation][module].
951 /// [module]: ../../std/fmt/index.html
955 /// Basic usage with `f64`:
958 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
960 /// assert_eq!(format!("{:e}", x), "4.2e1");
963 /// Implementing `LowerExp` on a type:
968 /// struct Length(i32);
970 /// impl fmt::LowerExp for Length {
971 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
972 /// let val = f64::from(self.0);
973 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
977 /// let l = Length(100);
980 /// format!("l in scientific notation is: {:e}", l),
981 /// "l in scientific notation is: 1e2"
985 /// format!("l in scientific notation is: {:05e}", l),
986 /// "l in scientific notation is: 001e2"
989 #[stable(feature = "rust1", since = "1.0.0")]
991 /// Formats the value using the given formatter.
992 #[stable(feature = "rust1", since = "1.0.0")]
993 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
998 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1000 /// For more information on formatters, see [the module-level documentation][module].
1002 /// [module]: ../../std/fmt/index.html
1006 /// Basic usage with `f64`:
1009 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1011 /// assert_eq!(format!("{:E}", x), "4.2E1");
1014 /// Implementing `UpperExp` on a type:
1019 /// struct Length(i32);
1021 /// impl fmt::UpperExp for Length {
1022 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1023 /// let val = f64::from(self.0);
1024 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1028 /// let l = Length(100);
1031 /// format!("l in scientific notation is: {:E}", l),
1032 /// "l in scientific notation is: 1E2"
1036 /// format!("l in scientific notation is: {:05E}", l),
1037 /// "l in scientific notation is: 001E2"
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 pub trait UpperExp
{
1042 /// Formats the value using the given formatter.
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
1047 /// The `write` function takes an output stream, and an `Arguments` struct
1048 /// that can be precompiled with the `format_args!` macro.
1050 /// The arguments will be formatted according to the specified format string
1051 /// into the output stream provided.
1060 /// let mut output = String::new();
1061 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1062 /// .expect("Error occurred while trying to write in String");
1063 /// assert_eq!(output, "Hello world!");
1066 /// Please note that using [`write!`] might be preferable. Example:
1069 /// use std::fmt::Write;
1071 /// let mut output = String::new();
1072 /// write!(&mut output, "Hello {}!", "world")
1073 /// .expect("Error occurred while trying to write in String");
1074 /// assert_eq!(output, "Hello world!");
1077 /// [`write!`]: crate::write!
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 pub fn write(output
: &mut dyn Write
, args
: Arguments
<'_
>) -> Result
{
1080 let mut formatter
= Formatter
{
1085 align
: rt
::v1
::Alignment
::Unknown
,
1093 // We can use default formatting parameters for all arguments.
1094 for (arg
, piece
) in args
.args
.iter().zip(args
.pieces
.iter()) {
1095 formatter
.buf
.write_str(*piece
)?
;
1096 (arg
.formatter
)(arg
.value
, &mut formatter
)?
;
1101 // Every spec has a corresponding argument that is preceded by
1103 for (arg
, piece
) in fmt
.iter().zip(args
.pieces
.iter()) {
1104 formatter
.buf
.write_str(*piece
)?
;
1105 // SAFETY: arg and args.args come from the same Arguments,
1106 // which guarantees the indexes are always within bounds.
1107 unsafe { run(&mut formatter, arg, &args.args) }?
;
1113 // There can be only one trailing string piece left.
1114 if let Some(piece
) = args
.pieces
.get(idx
) {
1115 formatter
.buf
.write_str(*piece
)?
;
1121 unsafe fn run(fmt
: &mut Formatter
<'_
>, arg
: &rt
::v1
::Argument
, args
: &[ArgumentV1
<'_
>]) -> Result
{
1122 fmt
.fill
= arg
.format
.fill
;
1123 fmt
.align
= arg
.format
.align
;
1124 fmt
.flags
= arg
.format
.flags
;
1125 // SAFETY: arg and args come from the same Arguments,
1126 // which guarantees the indexes are always within bounds.
1128 fmt
.width
= getcount(args
, &arg
.format
.width
);
1129 fmt
.precision
= getcount(args
, &arg
.format
.precision
);
1132 // Extract the correct argument
1133 debug_assert
!(arg
.position
< args
.len());
1134 // SAFETY: arg and args come from the same Arguments,
1135 // which guarantees its index is always within bounds.
1136 let value
= unsafe { args.get_unchecked(arg.position) }
;
1138 // Then actually do some printing
1139 (value
.formatter
)(value
.value
, fmt
)
1142 unsafe fn getcount(args
: &[ArgumentV1
<'_
>], cnt
: &rt
::v1
::Count
) -> Option
<usize> {
1144 rt
::v1
::Count
::Is(n
) => Some(n
),
1145 rt
::v1
::Count
::Implied
=> None
,
1146 rt
::v1
::Count
::Param(i
) => {
1147 debug_assert
!(i
< args
.len());
1148 // SAFETY: cnt and args come from the same Arguments,
1149 // which guarantees this index is always within bounds.
1150 unsafe { args.get_unchecked(i).as_usize() }
1155 /// Padding after the end of something. Returned by `Formatter::padding`.
1156 #[must_use = "don't forget to write the post padding"]
1157 struct PostPadding
{
1163 fn new(fill
: char, padding
: usize) -> PostPadding
{
1164 PostPadding { fill, padding }
1167 /// Write this post padding.
1168 fn write(self, buf
: &mut dyn Write
) -> Result
{
1169 for _
in 0..self.padding
{
1170 buf
.write_char(self.fill
)?
;
1176 impl<'a
> Formatter
<'a
> {
1177 fn wrap_buf
<'b
, 'c
, F
>(&'b
mut self, wrap
: F
) -> Formatter
<'c
>
1180 F
: FnOnce(&'b
mut (dyn Write
+ 'b
)) -> &'c
mut (dyn Write
+ 'c
),
1183 // We want to change this
1184 buf
: wrap(self.buf
),
1186 // And preserve these
1191 precision
: self.precision
,
1195 // Helper methods used for padding and processing formatting arguments that
1196 // all formatting traits can use.
1198 /// Performs the correct padding for an integer which has already been
1199 /// emitted into a str. The str should *not* contain the sign for the
1200 /// integer, that will be added by this method.
1204 /// * is_nonnegative - whether the original integer was either positive or zero.
1205 /// * prefix - if the '#' character (Alternate) is provided, this
1206 /// is the prefix to put in front of the number.
1207 /// * buf - the byte array that the number has been formatted into
1209 /// This function will correctly account for the flags provided as well as
1210 /// the minimum width. It will not take precision into account.
1217 /// struct Foo { nb: i32 }
1220 /// fn new(nb: i32) -> Foo {
1227 /// impl fmt::Display for Foo {
1228 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1229 /// // We need to remove "-" from the number output.
1230 /// let tmp = self.nb.abs().to_string();
1232 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1236 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1237 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1238 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1239 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 pub fn pad_integral(&mut self, is_nonnegative
: bool
, prefix
: &str, buf
: &str) -> Result
{
1243 let mut width
= buf
.len();
1245 let mut sign
= None
;
1246 if !is_nonnegative
{
1249 } else if self.sign_plus() {
1254 let prefix
= if self.alternate() {
1255 width
+= prefix
.chars().count();
1261 // Writes the sign if it exists, and then the prefix if it was requested
1263 fn write_prefix(f
: &mut Formatter
<'_
>, sign
: Option
<char>, prefix
: Option
<&str>) -> Result
{
1264 if let Some(c
) = sign
{
1265 f
.buf
.write_char(c
)?
;
1267 if let Some(prefix
) = prefix { f.buf.write_str(prefix) }
else { Ok(()) }
1270 // The `width` field is more of a `min-width` parameter at this point.
1272 // If there's no minimum length requirements then we can just
1275 write_prefix(self, sign
, prefix
)?
;
1276 self.buf
.write_str(buf
)
1278 // Check if we're over the minimum width, if so then we can also
1279 // just write the bytes.
1280 Some(min
) if width
>= min
=> {
1281 write_prefix(self, sign
, prefix
)?
;
1282 self.buf
.write_str(buf
)
1284 // The sign and prefix goes before the padding if the fill character
1286 Some(min
) if self.sign_aware_zero_pad() => {
1287 let old_fill
= crate::mem
::replace(&mut self.fill
, '
0'
);
1288 let old_align
= crate::mem
::replace(&mut self.align
, rt
::v1
::Alignment
::Right
);
1289 write_prefix(self, sign
, prefix
)?
;
1290 let post_padding
= self.padding(min
- width
, rt
::v1
::Alignment
::Right
)?
;
1291 self.buf
.write_str(buf
)?
;
1292 post_padding
.write(self.buf
)?
;
1293 self.fill
= old_fill
;
1294 self.align
= old_align
;
1297 // Otherwise, the sign and prefix goes after the padding
1299 let post_padding
= self.padding(min
- width
, rt
::v1
::Alignment
::Right
)?
;
1300 write_prefix(self, sign
, prefix
)?
;
1301 self.buf
.write_str(buf
)?
;
1302 post_padding
.write(self.buf
)
1307 /// This function takes a string slice and emits it to the internal buffer
1308 /// after applying the relevant formatting flags specified. The flags
1309 /// recognized for generic strings are:
1311 /// * width - the minimum width of what to emit
1312 /// * fill/align - what to emit and where to emit it if the string
1313 /// provided needs to be padded
1314 /// * precision - the maximum length to emit, the string is truncated if it
1315 /// is longer than this length
1317 /// Notably this function ignores the `flag` parameters.
1326 /// impl fmt::Display for Foo {
1327 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1328 /// formatter.pad("Foo")
1332 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1333 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 pub fn pad(&mut self, s
: &str) -> Result
{
1337 // Make sure there's a fast path up front
1338 if self.width
.is_none() && self.precision
.is_none() {
1339 return self.buf
.write_str(s
);
1341 // The `precision` field can be interpreted as a `max-width` for the
1342 // string being formatted.
1343 let s
= if let Some(max
) = self.precision
{
1344 // If our string is longer that the precision, then we must have
1345 // truncation. However other flags like `fill`, `width` and `align`
1346 // must act as always.
1347 if let Some((i
, _
)) = s
.char_indices().nth(max
) {
1348 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1349 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1350 // `unsafe` and otherwise don't emit any panic-related code
1352 s
.get(..i
).unwrap_or(&s
)
1359 // The `width` field is more of a `min-width` parameter at this point.
1361 // If we're under the maximum length, and there's no minimum length
1362 // requirements, then we can just emit the string
1363 None
=> self.buf
.write_str(s
),
1364 // If we're under the maximum width, check if we're over the minimum
1365 // width, if so it's as easy as just emitting the string.
1366 Some(width
) if s
.chars().count() >= width
=> self.buf
.write_str(s
),
1367 // If we're under both the maximum and the minimum width, then fill
1368 // up the minimum width with the specified string + some alignment.
1370 let align
= rt
::v1
::Alignment
::Left
;
1371 let post_padding
= self.padding(width
- s
.chars().count(), align
)?
;
1372 self.buf
.write_str(s
)?
;
1373 post_padding
.write(self.buf
)
1378 /// Write the pre-padding and return the unwritten post-padding. Callers are
1379 /// responsible for ensuring post-padding is written after the thing that is
1384 default: rt
::v1
::Alignment
,
1385 ) -> result
::Result
<PostPadding
, Error
> {
1386 let align
= match self.align
{
1387 rt
::v1
::Alignment
::Unknown
=> default,
1391 let (pre_pad
, post_pad
) = match align
{
1392 rt
::v1
::Alignment
::Left
=> (0, padding
),
1393 rt
::v1
::Alignment
::Right
| rt
::v1
::Alignment
::Unknown
=> (padding
, 0),
1394 rt
::v1
::Alignment
::Center
=> (padding
/ 2, (padding
+ 1) / 2),
1397 for _
in 0..pre_pad
{
1398 self.buf
.write_char(self.fill
)?
;
1401 Ok(PostPadding
::new(self.fill
, post_pad
))
1404 /// Takes the formatted parts and applies the padding.
1405 /// Assumes that the caller already has rendered the parts with required precision,
1406 /// so that `self.precision` can be ignored.
1407 fn pad_formatted_parts(&mut self, formatted
: &flt2dec
::Formatted
<'_
>) -> Result
{
1408 if let Some(mut width
) = self.width
{
1409 // for the sign-aware zero padding, we render the sign first and
1410 // behave as if we had no sign from the beginning.
1411 let mut formatted
= formatted
.clone();
1412 let old_fill
= self.fill
;
1413 let old_align
= self.align
;
1414 let mut align
= old_align
;
1415 if self.sign_aware_zero_pad() {
1416 // a sign always goes first
1417 let sign
= formatted
.sign
;
1418 self.buf
.write_str(sign
)?
;
1420 // remove the sign from the formatted parts
1421 formatted
.sign
= "";
1422 width
= width
.saturating_sub(sign
.len());
1423 align
= rt
::v1
::Alignment
::Right
;
1425 self.align
= rt
::v1
::Alignment
::Right
;
1428 // remaining parts go through the ordinary padding process.
1429 let len
= formatted
.len();
1430 let ret
= if width
<= len
{
1432 self.write_formatted_parts(&formatted
)
1434 let post_padding
= self.padding(width
- len
, align
)?
;
1435 self.write_formatted_parts(&formatted
)?
;
1436 post_padding
.write(self.buf
)
1438 self.fill
= old_fill
;
1439 self.align
= old_align
;
1442 // this is the common case and we take a shortcut
1443 self.write_formatted_parts(formatted
)
1447 fn write_formatted_parts(&mut self, formatted
: &flt2dec
::Formatted
<'_
>) -> Result
{
1448 fn write_bytes(buf
: &mut dyn Write
, s
: &[u8]) -> Result
{
1449 // SAFETY: This is used for `flt2dec::Part::Num` and `flt2dec::Part::Copy`.
1450 // It's safe to use for `flt2dec::Part::Num` since every char `c` is between
1451 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1452 // It's also probably safe in practice to use for `flt2dec::Part::Copy(buf)`
1453 // since `buf` should be plain ASCII, but it's possible for someone to pass
1454 // in a bad value for `buf` into `flt2dec::to_shortest_str` since it is a
1456 // FIXME: Determine whether this could result in UB.
1457 buf
.write_str(unsafe { str::from_utf8_unchecked(s) }
)
1460 if !formatted
.sign
.is_empty() {
1461 self.buf
.write_str(formatted
.sign
)?
;
1463 for part
in formatted
.parts
{
1465 flt2dec
::Part
::Zero(mut nzeroes
) => {
1466 const ZEROES
: &str = // 64 zeroes
1467 "0000000000000000000000000000000000000000000000000000000000000000";
1468 while nzeroes
> ZEROES
.len() {
1469 self.buf
.write_str(ZEROES
)?
;
1470 nzeroes
-= ZEROES
.len();
1473 self.buf
.write_str(&ZEROES
[..nzeroes
])?
;
1476 flt2dec
::Part
::Num(mut v
) => {
1478 let len
= part
.len();
1479 for c
in s
[..len
].iter_mut().rev() {
1480 *c
= b'
0'
+ (v
% 10) as u8;
1483 write_bytes(self.buf
, &s
[..len
])?
;
1485 flt2dec
::Part
::Copy(buf
) => {
1486 write_bytes(self.buf
, buf
)?
;
1493 /// Writes some data to the underlying buffer contained within this
1503 /// impl fmt::Display for Foo {
1504 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1505 /// formatter.write_str("Foo")
1506 /// // This is equivalent to:
1507 /// // write!(formatter, "Foo")
1511 /// assert_eq!(&format!("{}", Foo), "Foo");
1512 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 pub fn write_str(&mut self, data
: &str) -> Result
{
1516 self.buf
.write_str(data
)
1519 /// Writes some formatted information into this instance.
1526 /// struct Foo(i32);
1528 /// impl fmt::Display for Foo {
1529 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1530 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1534 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1535 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 pub fn write_fmt(&mut self, fmt
: Arguments
<'_
>) -> Result
{
1539 write(self.buf
, fmt
)
1542 /// Flags for formatting
1543 #[stable(feature = "rust1", since = "1.0.0")]
1546 reason
= "use the `sign_plus`, `sign_minus`, `alternate`, \
1547 or `sign_aware_zero_pad` methods instead"
1549 pub fn flags(&self) -> u32 {
1553 /// Character used as 'fill' whenever there is alignment.
1562 /// impl fmt::Display for Foo {
1563 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1564 /// let c = formatter.fill();
1565 /// if let Some(width) = formatter.width() {
1566 /// for _ in 0..width {
1567 /// write!(formatter, "{}", c)?;
1571 /// write!(formatter, "{}", c)
1576 /// // We set alignment to the right with ">".
1577 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1578 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1580 #[stable(feature = "fmt_flags", since = "1.5.0")]
1581 pub fn fill(&self) -> char {
1585 /// Flag indicating what form of alignment was requested.
1590 /// extern crate core;
1592 /// use std::fmt::{self, Alignment};
1596 /// impl fmt::Display for Foo {
1597 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1598 /// let s = if let Some(s) = formatter.align() {
1600 /// Alignment::Left => "left",
1601 /// Alignment::Right => "right",
1602 /// Alignment::Center => "center",
1607 /// write!(formatter, "{}", s)
1611 /// assert_eq!(&format!("{:<}", Foo), "left");
1612 /// assert_eq!(&format!("{:>}", Foo), "right");
1613 /// assert_eq!(&format!("{:^}", Foo), "center");
1614 /// assert_eq!(&format!("{}", Foo), "into the void");
1616 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1617 pub fn align(&self) -> Option
<Alignment
> {
1619 rt
::v1
::Alignment
::Left
=> Some(Alignment
::Left
),
1620 rt
::v1
::Alignment
::Right
=> Some(Alignment
::Right
),
1621 rt
::v1
::Alignment
::Center
=> Some(Alignment
::Center
),
1622 rt
::v1
::Alignment
::Unknown
=> None
,
1626 /// Optionally specified integer width that the output should be.
1633 /// struct Foo(i32);
1635 /// impl fmt::Display for Foo {
1636 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1637 /// if let Some(width) = formatter.width() {
1638 /// // If we received a width, we use it
1639 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1641 /// // Otherwise we do nothing special
1642 /// write!(formatter, "Foo({})", self.0)
1647 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1648 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1650 #[stable(feature = "fmt_flags", since = "1.5.0")]
1651 pub fn width(&self) -> Option
<usize> {
1655 /// Optionally specified precision for numeric types. Alternatively, the
1656 /// maximum width for string types.
1663 /// struct Foo(f32);
1665 /// impl fmt::Display for Foo {
1666 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1667 /// if let Some(precision) = formatter.precision() {
1668 /// // If we received a precision, we use it.
1669 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1671 /// // Otherwise we default to 2.
1672 /// write!(formatter, "Foo({:.2})", self.0)
1677 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1678 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1680 #[stable(feature = "fmt_flags", since = "1.5.0")]
1681 pub fn precision(&self) -> Option
<usize> {
1685 /// Determines if the `+` flag was specified.
1692 /// struct Foo(i32);
1694 /// impl fmt::Display for Foo {
1695 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1696 /// if formatter.sign_plus() {
1697 /// write!(formatter,
1699 /// if self.0 < 0 { '-' } else { '+' },
1702 /// write!(formatter, "Foo({})", self.0)
1707 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1708 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1710 #[stable(feature = "fmt_flags", since = "1.5.0")]
1711 pub fn sign_plus(&self) -> bool
{
1712 self.flags
& (1 << FlagV1
::SignPlus
as u32) != 0
1715 /// Determines if the `-` flag was specified.
1722 /// struct Foo(i32);
1724 /// impl fmt::Display for Foo {
1725 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1726 /// if formatter.sign_minus() {
1727 /// // You want a minus sign? Have one!
1728 /// write!(formatter, "-Foo({})", self.0)
1730 /// write!(formatter, "Foo({})", self.0)
1735 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1736 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1738 #[stable(feature = "fmt_flags", since = "1.5.0")]
1739 pub fn sign_minus(&self) -> bool
{
1740 self.flags
& (1 << FlagV1
::SignMinus
as u32) != 0
1743 /// Determines if the `#` flag was specified.
1750 /// struct Foo(i32);
1752 /// impl fmt::Display for Foo {
1753 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1754 /// if formatter.alternate() {
1755 /// write!(formatter, "Foo({})", self.0)
1757 /// write!(formatter, "{}", self.0)
1762 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1763 /// assert_eq!(&format!("{}", Foo(23)), "23");
1765 #[stable(feature = "fmt_flags", since = "1.5.0")]
1766 pub fn alternate(&self) -> bool
{
1767 self.flags
& (1 << FlagV1
::Alternate
as u32) != 0
1770 /// Determines if the `0` flag was specified.
1777 /// struct Foo(i32);
1779 /// impl fmt::Display for Foo {
1780 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1781 /// assert!(formatter.sign_aware_zero_pad());
1782 /// assert_eq!(formatter.width(), Some(4));
1783 /// // We ignore the formatter's options.
1784 /// write!(formatter, "{}", self.0)
1788 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1790 #[stable(feature = "fmt_flags", since = "1.5.0")]
1791 pub fn sign_aware_zero_pad(&self) -> bool
{
1792 self.flags
& (1 << FlagV1
::SignAwareZeroPad
as u32) != 0
1795 // FIXME: Decide what public API we want for these two flags.
1796 // https://github.com/rust-lang/rust/issues/48584
1797 fn debug_lower_hex(&self) -> bool
{
1798 self.flags
& (1 << FlagV1
::DebugLowerHex
as u32) != 0
1801 fn debug_upper_hex(&self) -> bool
{
1802 self.flags
& (1 << FlagV1
::DebugUpperHex
as u32) != 0
1805 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1806 /// [`fmt::Debug`] implementations for structs.
1808 /// [`fmt::Debug`]: self::Debug
1814 /// use std::net::Ipv4Addr;
1822 /// impl fmt::Debug for Foo {
1823 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1824 /// fmt.debug_struct("Foo")
1825 /// .field("bar", &self.bar)
1826 /// .field("baz", &self.baz)
1827 /// .field("addr", &format_args!("{}", self.addr))
1833 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1834 /// format!("{:?}", Foo {
1836 /// baz: "Hello World".to_string(),
1837 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1841 #[stable(feature = "debug_builders", since = "1.2.0")]
1842 pub fn debug_struct
<'b
>(&'b
mut self, name
: &str) -> DebugStruct
<'b
, 'a
> {
1843 builders
::debug_struct_new(self, name
)
1846 /// Creates a `DebugTuple` builder designed to assist with creation of
1847 /// `fmt::Debug` implementations for tuple structs.
1853 /// use std::marker::PhantomData;
1855 /// struct Foo<T>(i32, String, PhantomData<T>);
1857 /// impl<T> fmt::Debug for Foo<T> {
1858 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1859 /// fmt.debug_tuple("Foo")
1862 /// .field(&format_args!("_"))
1868 /// "Foo(10, \"Hello\", _)",
1869 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1872 #[stable(feature = "debug_builders", since = "1.2.0")]
1873 pub fn debug_tuple
<'b
>(&'b
mut self, name
: &str) -> DebugTuple
<'b
, 'a
> {
1874 builders
::debug_tuple_new(self, name
)
1877 /// Creates a `DebugList` builder designed to assist with creation of
1878 /// `fmt::Debug` implementations for list-like structures.
1885 /// struct Foo(Vec<i32>);
1887 /// impl fmt::Debug for Foo {
1888 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1889 /// fmt.debug_list().entries(self.0.iter()).finish()
1893 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
1895 #[stable(feature = "debug_builders", since = "1.2.0")]
1896 pub fn debug_list
<'b
>(&'b
mut self) -> DebugList
<'b
, 'a
> {
1897 builders
::debug_list_new(self)
1900 /// Creates a `DebugSet` builder designed to assist with creation of
1901 /// `fmt::Debug` implementations for set-like structures.
1908 /// struct Foo(Vec<i32>);
1910 /// impl fmt::Debug for Foo {
1911 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1912 /// fmt.debug_set().entries(self.0.iter()).finish()
1916 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
1919 /// [`format_args!`]: crate::format_args
1921 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1922 /// to build a list of match arms:
1927 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1928 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1930 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1932 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1934 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1935 /// L::fmt(&(self.0).0, fmt)?;
1936 /// fmt.write_str(" => ")?;
1937 /// R::fmt(&(self.0).1, fmt)
1941 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1943 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1945 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1947 /// .entries(self.0.iter().map(Arm))
1948 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1953 #[stable(feature = "debug_builders", since = "1.2.0")]
1954 pub fn debug_set
<'b
>(&'b
mut self) -> DebugSet
<'b
, 'a
> {
1955 builders
::debug_set_new(self)
1958 /// Creates a `DebugMap` builder designed to assist with creation of
1959 /// `fmt::Debug` implementations for map-like structures.
1966 /// struct Foo(Vec<(String, i32)>);
1968 /// impl fmt::Debug for Foo {
1969 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1970 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1975 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1976 /// r#"{"A": 10, "B": 11}"#
1979 #[stable(feature = "debug_builders", since = "1.2.0")]
1980 pub fn debug_map
<'b
>(&'b
mut self) -> DebugMap
<'b
, 'a
> {
1981 builders
::debug_map_new(self)
1985 #[stable(since = "1.2.0", feature = "formatter_write")]
1986 impl Write
for Formatter
<'_
> {
1987 fn write_str(&mut self, s
: &str) -> Result
{
1988 self.buf
.write_str(s
)
1991 fn write_char(&mut self, c
: char) -> Result
{
1992 self.buf
.write_char(c
)
1995 fn write_fmt(&mut self, args
: Arguments
<'_
>) -> Result
{
1996 write(self.buf
, args
)
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl Display
for Error
{
2002 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2003 Display
::fmt("an error occurred when formatting an argument", f
)
2007 // Implementations of the core formatting traits
2009 macro_rules
! fmt_refs
{
2010 ($
($tr
:ident
),*) => {
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 impl<T
: ?Sized
+ $tr
> $tr
for &T
{
2014 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result { $tr::fmt(&**self, f) }
2016 #[stable(feature = "rust1", since = "1.0.0")]
2017 impl<T
: ?Sized
+ $tr
> $tr
for &mut T
{
2018 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result { $tr::fmt(&**self, f) }
2024 fmt_refs
! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2026 #[unstable(feature = "never_type", issue = "35121")]
2028 fn fmt(&self, _
: &mut Formatter
<'_
>) -> Result
{
2033 #[unstable(feature = "never_type", issue = "35121")]
2034 impl Display
for ! {
2035 fn fmt(&self, _
: &mut Formatter
<'_
>) -> Result
{
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 impl Debug
for bool
{
2043 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2044 Display
::fmt(self, f
)
2048 #[stable(feature = "rust1", since = "1.0.0")]
2049 impl Display
for bool
{
2050 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2051 Display
::fmt(if *self { "true" }
else { "false" }
, f
)
2055 #[stable(feature = "rust1", since = "1.0.0")]
2056 impl Debug
for str {
2057 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2060 for (i, c) in self.char_indices() {
2061 let esc = c.escape_debug();
2062 // If char needs escaping, flush backlog so far and write, else skip
2064 f.write_str(&self[from..i])?;
2068 from = i + c.len_utf8();
2071 f.write_str(&self[from..])?;
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 impl Display
for str {
2078 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 impl Debug
for char {
2085 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2086 f
.write_char('
\''
)?
;
2087 for c
in self.escape_debug() {
2094 #[stable(feature = "rust1", since = "1.0.0")]
2095 impl Display
for char {
2096 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2097 if f
.width
.is_none() && f
.precision
.is_none() {
2100 f
.pad(self.encode_utf8(&mut [0; 4]))
2105 #[stable(feature = "rust1", since = "1.0.0")]
2106 impl<T
: ?Sized
> Pointer
for *const T
{
2107 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2108 let old_width
= f
.width
;
2109 let old_flags
= f
.flags
;
2111 // The alternate flag is already treated by LowerHex as being special-
2112 // it denotes whether to prefix with 0x. We use it to work out whether
2113 // or not to zero extend, and then unconditionally set it to get the
2116 f
.flags
|= 1 << (FlagV1
::SignAwareZeroPad
as u32);
2118 if f
.width
.is_none() {
2119 f
.width
= Some((usize::BITS
/ 4) as usize + 2);
2122 f
.flags
|= 1 << (FlagV1
::Alternate
as u32);
2124 let ret
= LowerHex
::fmt(&(*self as *const () as usize), f
);
2126 f
.width
= old_width
;
2127 f
.flags
= old_flags
;
2133 #[stable(feature = "rust1", since = "1.0.0")]
2134 impl<T
: ?Sized
> Pointer
for *mut T
{
2135 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2136 Pointer
::fmt(&(*self as *const T
), f
)
2140 #[stable(feature = "rust1", since = "1.0.0")]
2141 impl<T
: ?Sized
> Pointer
for &T
{
2142 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2143 Pointer
::fmt(&(*self as *const T
), f
)
2147 #[stable(feature = "rust1", since = "1.0.0")]
2148 impl<T
: ?Sized
> Pointer
for &mut T
{
2149 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2150 Pointer
::fmt(&(&**self as *const T
), f
)
2154 // Implementation of Display/Debug for various core types
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 impl<T
: ?Sized
> Debug
for *const T
{
2158 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2159 Pointer
::fmt(self, f
)
2162 #[stable(feature = "rust1", since = "1.0.0")]
2163 impl<T
: ?Sized
> Debug
for *mut T
{
2164 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2165 Pointer
::fmt(self, f
)
2170 ($name
:ident
, $
($other
:ident
,)*) => (tuple
! { $($other,)* }
)
2173 macro_rules
! tuple
{
2175 ( $
($name
:ident
,)+ ) => (
2176 #[stable(feature = "rust1", since = "1.0.0")]
2177 impl<$
($name
:Debug
),+> Debug
for ($
($name
,)+) where last_type
!($
($name
,)+): ?Sized
{
2178 #[allow(non_snake_case, unused_assignments)]
2179 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2180 let mut builder
= f
.debug_tuple("");
2181 let ($
(ref $name
,)+) = *self;
2183 builder
.field(&$name
);
2189 peel
! { $($name,)+ }
2193 macro_rules
! last_type
{
2194 ($a
:ident
,) => { $a }
;
2195 ($a
:ident
, $
($rest_a
:ident
,)+) => { last_type!($($rest_a,)+) }
;
2198 tuple
! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 impl<T
: Debug
> Debug
for [T
] {
2202 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2203 f
.debug_list().entries(self.iter()).finish()
2207 #[stable(feature = "rust1", since = "1.0.0")]
2210 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2214 #[stable(feature = "rust1", since = "1.0.0")]
2215 impl<T
: ?Sized
> Debug
for PhantomData
<T
> {
2216 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2217 f
.pad("PhantomData")
2221 #[stable(feature = "rust1", since = "1.0.0")]
2222 impl<T
: Copy
+ Debug
> Debug
for Cell
<T
> {
2223 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2224 f
.debug_struct("Cell").field("value", &self.get()).finish()
2228 #[stable(feature = "rust1", since = "1.0.0")]
2229 impl<T
: ?Sized
+ Debug
> Debug
for RefCell
<T
> {
2230 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2231 match self.try_borrow() {
2232 Ok(borrow
) => f
.debug_struct("RefCell").field("value", &borrow
).finish(),
2234 // The RefCell is mutably borrowed so we can't look at its value
2235 // here. Show a placeholder instead.
2236 struct BorrowedPlaceholder
;
2238 impl Debug
for BorrowedPlaceholder
{
2239 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2240 f
.write_str("<borrowed>")
2244 f
.debug_struct("RefCell").field("value", &BorrowedPlaceholder
).finish()
2250 #[stable(feature = "rust1", since = "1.0.0")]
2251 impl<T
: ?Sized
+ Debug
> Debug
for Ref
<'_
, T
> {
2252 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2253 Debug
::fmt(&**self, f
)
2257 #[stable(feature = "rust1", since = "1.0.0")]
2258 impl<T
: ?Sized
+ Debug
> Debug
for RefMut
<'_
, T
> {
2259 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2260 Debug
::fmt(&*(self.deref()), f
)
2264 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2265 impl<T
: ?Sized
+ Debug
> Debug
for UnsafeCell
<T
> {
2266 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2271 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2272 // it's a lot easier than creating all of the rt::Piece structures here.
2273 // There are also tests in the alloc crate, for those that need allocations.