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][self].
461 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
462 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
463 /// comma-separated list of each field's name and `Debug` value, then `}`. For
464 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
465 /// `Debug` values of the fields, then `)`.
469 /// Derived `Debug` formats are not stable, and so may change with future Rust
470 /// versions. Additionally, `Debug` implementations of types provided by the
471 /// standard library (`libstd`, `libcore`, `liballoc`, etc.) are not stable, and
472 /// may also change with future Rust versions.
476 /// Deriving an implementation:
485 /// let origin = Point { x: 0, y: 0 };
487 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
490 /// Manually implementing:
500 /// impl fmt::Debug for Point {
501 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
502 /// f.debug_struct("Point")
503 /// .field("x", &self.x)
504 /// .field("y", &self.y)
509 /// let origin = Point { x: 0, y: 0 };
511 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
514 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
515 /// implementations, such as [`debug_struct`].
517 /// `Debug` implementations using either `derive` or the debug builder API
518 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
520 /// [`debug_struct`]: Formatter::debug_struct
522 /// Pretty-printing with `#?`:
531 /// let origin = Point { x: 0, y: 0 };
533 /// assert_eq!(format!("The origin is: {:#?}", origin),
534 /// "The origin is: Point {
540 #[stable(feature = "rust1", since = "1.0.0")]
541 #[rustc_on_unimplemented(
544 label
= "`{Self}` cannot be formatted using `{{:?}}`",
545 note
= "add `#[derive(Debug)]` or manually implement `{Debug}`"
547 message
= "`{Self}` doesn't implement `{Debug}`",
548 label
= "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
550 #[doc(alias = "{:?}")]
551 #[rustc_diagnostic_item = "debug_trait"]
553 /// Formats the value using the given formatter.
560 /// struct Position {
565 /// impl fmt::Debug for Position {
566 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567 /// f.debug_tuple("")
568 /// .field(&self.longitude)
569 /// .field(&self.latitude)
574 /// let position = Position { longitude: 1.987, latitude: 2.983 };
575 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
577 /// assert_eq!(format!("{:#?}", position), "(
582 #[stable(feature = "rust1", since = "1.0.0")]
583 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
586 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
587 pub(crate) mod macros
{
588 /// Derive macro generating an impl of the trait `Debug`.
589 #[rustc_builtin_macro]
590 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
591 #[allow_internal_unstable(core_intrinsics)]
592 pub macro Debug($item
:item
) {
593 /* compiler built-in */
596 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
598 pub use macros
::Debug
;
600 /// Format trait for an empty format, `{}`.
602 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
603 /// output, and so cannot be derived.
605 /// For more information on formatters, see [the module-level documentation][self].
609 /// Implementing `Display` on a type:
619 /// impl fmt::Display for Point {
620 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621 /// write!(f, "({}, {})", self.x, self.y)
625 /// let origin = Point { x: 0, y: 0 };
627 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
629 #[rustc_on_unimplemented(
631 _Self
= "std::path::Path",
632 label
= "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
633 note
= "call `.display()` or `.to_string_lossy()` to safely print paths, \
634 as they may contain non-Unicode data"
636 message
= "`{Self}` doesn't implement `{Display}`",
637 label
= "`{Self}` cannot be formatted with the default formatter",
638 note
= "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
641 #[stable(feature = "rust1", since = "1.0.0")]
643 /// Formats the value using the given formatter.
650 /// struct Position {
655 /// impl fmt::Display for Position {
656 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
657 /// write!(f, "({}, {})", self.longitude, self.latitude)
661 /// assert_eq!("(1.987, 2.983)",
662 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
664 #[stable(feature = "rust1", since = "1.0.0")]
665 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
670 /// The `Octal` trait should format its output as a number in base-8.
672 /// For primitive signed integers (`i8` to `i128`, and `isize`),
673 /// negative values are formatted as the two’s complement representation.
675 /// The alternate flag, `#`, adds a `0o` in front of the output.
677 /// For more information on formatters, see [the module-level documentation][self].
681 /// Basic usage with `i32`:
684 /// let x = 42; // 42 is '52' in octal
686 /// assert_eq!(format!("{:o}", x), "52");
687 /// assert_eq!(format!("{:#o}", x), "0o52");
689 /// assert_eq!(format!("{:o}", -16), "37777777760");
692 /// Implementing `Octal` on a type:
697 /// struct Length(i32);
699 /// impl fmt::Octal for Length {
700 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
701 /// let val = self.0;
703 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
707 /// let l = Length(9);
709 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
711 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
713 #[stable(feature = "rust1", since = "1.0.0")]
715 /// Formats the value using the given formatter.
716 #[stable(feature = "rust1", since = "1.0.0")]
717 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
722 /// The `Binary` trait should format its output as a number in binary.
724 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
725 /// negative values are formatted as the two’s complement representation.
727 /// The alternate flag, `#`, adds a `0b` in front of the output.
729 /// For more information on formatters, see [the module-level documentation][self].
733 /// Basic usage with [`i32`]:
736 /// let x = 42; // 42 is '101010' in binary
738 /// assert_eq!(format!("{:b}", x), "101010");
739 /// assert_eq!(format!("{:#b}", x), "0b101010");
741 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
744 /// Implementing `Binary` on a type:
749 /// struct Length(i32);
751 /// impl fmt::Binary for Length {
752 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
753 /// let val = self.0;
755 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
759 /// let l = Length(107);
761 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
764 /// format!("l as binary is: {:#032b}", l),
765 /// "l as binary is: 0b000000000000000000000001101011"
768 #[stable(feature = "rust1", since = "1.0.0")]
770 /// Formats the value using the given formatter.
771 #[stable(feature = "rust1", since = "1.0.0")]
772 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
777 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
780 /// For primitive signed integers (`i8` to `i128`, and `isize`),
781 /// negative values are formatted as the two’s complement representation.
783 /// The alternate flag, `#`, adds a `0x` in front of the output.
785 /// For more information on formatters, see [the module-level documentation][self].
789 /// Basic usage with `i32`:
792 /// let x = 42; // 42 is '2a' in hex
794 /// assert_eq!(format!("{:x}", x), "2a");
795 /// assert_eq!(format!("{:#x}", x), "0x2a");
797 /// assert_eq!(format!("{:x}", -16), "fffffff0");
800 /// Implementing `LowerHex` on a type:
805 /// struct Length(i32);
807 /// impl fmt::LowerHex for Length {
808 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
809 /// let val = self.0;
811 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
815 /// let l = Length(9);
817 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
819 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
821 #[stable(feature = "rust1", since = "1.0.0")]
823 /// Formats the value using the given formatter.
824 #[stable(feature = "rust1", since = "1.0.0")]
825 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
830 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
833 /// For primitive signed integers (`i8` to `i128`, and `isize`),
834 /// negative values are formatted as the two’s complement representation.
836 /// The alternate flag, `#`, adds a `0x` in front of the output.
838 /// For more information on formatters, see [the module-level documentation][self].
842 /// Basic usage with `i32`:
845 /// let x = 42; // 42 is '2A' in hex
847 /// assert_eq!(format!("{:X}", x), "2A");
848 /// assert_eq!(format!("{:#X}", x), "0x2A");
850 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
853 /// Implementing `UpperHex` on a type:
858 /// struct Length(i32);
860 /// impl fmt::UpperHex for Length {
861 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
862 /// let val = self.0;
864 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
868 /// let l = Length(i32::MAX);
870 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
872 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
874 #[stable(feature = "rust1", since = "1.0.0")]
876 /// Formats the value using the given formatter.
877 #[stable(feature = "rust1", since = "1.0.0")]
878 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
883 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
886 /// For more information on formatters, see [the module-level documentation][self].
890 /// Basic usage with `&i32`:
895 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
898 /// Implementing `Pointer` on a type:
903 /// struct Length(i32);
905 /// impl fmt::Pointer for Length {
906 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
907 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
909 /// let ptr = self as *const Self;
910 /// fmt::Pointer::fmt(&ptr, f)
914 /// let l = Length(42);
916 /// println!("l is in memory here: {:p}", l);
918 /// let l_ptr = format!("{:018p}", l);
919 /// assert_eq!(l_ptr.len(), 18);
920 /// assert_eq!(&l_ptr[..2], "0x");
922 #[stable(feature = "rust1", since = "1.0.0")]
923 #[rustc_diagnostic_item = "pointer_trait"]
925 /// Formats the value using the given formatter.
926 #[stable(feature = "rust1", since = "1.0.0")]
927 #[rustc_diagnostic_item = "pointer_trait_fmt"]
928 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
933 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
935 /// For more information on formatters, see [the module-level documentation][self].
939 /// Basic usage with `f64`:
942 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
944 /// assert_eq!(format!("{:e}", x), "4.2e1");
947 /// Implementing `LowerExp` on a type:
952 /// struct Length(i32);
954 /// impl fmt::LowerExp for Length {
955 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
956 /// let val = f64::from(self.0);
957 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
961 /// let l = Length(100);
964 /// format!("l in scientific notation is: {:e}", l),
965 /// "l in scientific notation is: 1e2"
969 /// format!("l in scientific notation is: {:05e}", l),
970 /// "l in scientific notation is: 001e2"
973 #[stable(feature = "rust1", since = "1.0.0")]
975 /// Formats the value using the given formatter.
976 #[stable(feature = "rust1", since = "1.0.0")]
977 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
982 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
984 /// For more information on formatters, see [the module-level documentation][self].
988 /// Basic usage with `f64`:
991 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
993 /// assert_eq!(format!("{:E}", x), "4.2E1");
996 /// Implementing `UpperExp` on a type:
1001 /// struct Length(i32);
1003 /// impl fmt::UpperExp for Length {
1004 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1005 /// let val = f64::from(self.0);
1006 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1010 /// let l = Length(100);
1013 /// format!("l in scientific notation is: {:E}", l),
1014 /// "l in scientific notation is: 1E2"
1018 /// format!("l in scientific notation is: {:05E}", l),
1019 /// "l in scientific notation is: 001E2"
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 pub trait UpperExp
{
1024 /// Formats the value using the given formatter.
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
1029 /// The `write` function takes an output stream, and an `Arguments` struct
1030 /// that can be precompiled with the `format_args!` macro.
1032 /// The arguments will be formatted according to the specified format string
1033 /// into the output stream provided.
1042 /// let mut output = String::new();
1043 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1044 /// .expect("Error occurred while trying to write in String");
1045 /// assert_eq!(output, "Hello world!");
1048 /// Please note that using [`write!`] might be preferable. Example:
1051 /// use std::fmt::Write;
1053 /// let mut output = String::new();
1054 /// write!(&mut output, "Hello {}!", "world")
1055 /// .expect("Error occurred while trying to write in String");
1056 /// assert_eq!(output, "Hello world!");
1059 /// [`write!`]: crate::write!
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 pub fn write(output
: &mut dyn Write
, args
: Arguments
<'_
>) -> Result
{
1062 let mut formatter
= Formatter
{
1067 align
: rt
::v1
::Alignment
::Unknown
,
1075 // We can use default formatting parameters for all arguments.
1076 for (arg
, piece
) in args
.args
.iter().zip(args
.pieces
.iter()) {
1077 formatter
.buf
.write_str(*piece
)?
;
1078 (arg
.formatter
)(arg
.value
, &mut formatter
)?
;
1083 // Every spec has a corresponding argument that is preceded by
1085 for (arg
, piece
) in fmt
.iter().zip(args
.pieces
.iter()) {
1086 formatter
.buf
.write_str(*piece
)?
;
1087 // SAFETY: arg and args.args come from the same Arguments,
1088 // which guarantees the indexes are always within bounds.
1089 unsafe { run(&mut formatter, arg, &args.args) }?
;
1095 // There can be only one trailing string piece left.
1096 if let Some(piece
) = args
.pieces
.get(idx
) {
1097 formatter
.buf
.write_str(*piece
)?
;
1103 unsafe fn run(fmt
: &mut Formatter
<'_
>, arg
: &rt
::v1
::Argument
, args
: &[ArgumentV1
<'_
>]) -> Result
{
1104 fmt
.fill
= arg
.format
.fill
;
1105 fmt
.align
= arg
.format
.align
;
1106 fmt
.flags
= arg
.format
.flags
;
1107 // SAFETY: arg and args come from the same Arguments,
1108 // which guarantees the indexes are always within bounds.
1110 fmt
.width
= getcount(args
, &arg
.format
.width
);
1111 fmt
.precision
= getcount(args
, &arg
.format
.precision
);
1114 // Extract the correct argument
1115 debug_assert
!(arg
.position
< args
.len());
1116 // SAFETY: arg and args come from the same Arguments,
1117 // which guarantees its index is always within bounds.
1118 let value
= unsafe { args.get_unchecked(arg.position) }
;
1120 // Then actually do some printing
1121 (value
.formatter
)(value
.value
, fmt
)
1124 unsafe fn getcount(args
: &[ArgumentV1
<'_
>], cnt
: &rt
::v1
::Count
) -> Option
<usize> {
1126 rt
::v1
::Count
::Is(n
) => Some(n
),
1127 rt
::v1
::Count
::Implied
=> None
,
1128 rt
::v1
::Count
::Param(i
) => {
1129 debug_assert
!(i
< args
.len());
1130 // SAFETY: cnt and args come from the same Arguments,
1131 // which guarantees this index is always within bounds.
1132 unsafe { args.get_unchecked(i).as_usize() }
1137 /// Padding after the end of something. Returned by `Formatter::padding`.
1138 #[must_use = "don't forget to write the post padding"]
1139 struct PostPadding
{
1145 fn new(fill
: char, padding
: usize) -> PostPadding
{
1146 PostPadding { fill, padding }
1149 /// Write this post padding.
1150 fn write(self, buf
: &mut dyn Write
) -> Result
{
1151 for _
in 0..self.padding
{
1152 buf
.write_char(self.fill
)?
;
1158 impl<'a
> Formatter
<'a
> {
1159 fn wrap_buf
<'b
, 'c
, F
>(&'b
mut self, wrap
: F
) -> Formatter
<'c
>
1162 F
: FnOnce(&'b
mut (dyn Write
+ 'b
)) -> &'c
mut (dyn Write
+ 'c
),
1165 // We want to change this
1166 buf
: wrap(self.buf
),
1168 // And preserve these
1173 precision
: self.precision
,
1177 // Helper methods used for padding and processing formatting arguments that
1178 // all formatting traits can use.
1180 /// Performs the correct padding for an integer which has already been
1181 /// emitted into a str. The str should *not* contain the sign for the
1182 /// integer, that will be added by this method.
1186 /// * is_nonnegative - whether the original integer was either positive or zero.
1187 /// * prefix - if the '#' character (Alternate) is provided, this
1188 /// is the prefix to put in front of the number.
1189 /// * buf - the byte array that the number has been formatted into
1191 /// This function will correctly account for the flags provided as well as
1192 /// the minimum width. It will not take precision into account.
1199 /// struct Foo { nb: i32 }
1202 /// fn new(nb: i32) -> Foo {
1209 /// impl fmt::Display for Foo {
1210 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1211 /// // We need to remove "-" from the number output.
1212 /// let tmp = self.nb.abs().to_string();
1214 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1218 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1219 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1220 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1221 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 pub fn pad_integral(&mut self, is_nonnegative
: bool
, prefix
: &str, buf
: &str) -> Result
{
1225 let mut width
= buf
.len();
1227 let mut sign
= None
;
1228 if !is_nonnegative
{
1231 } else if self.sign_plus() {
1236 let prefix
= if self.alternate() {
1237 width
+= prefix
.chars().count();
1243 // Writes the sign if it exists, and then the prefix if it was requested
1245 fn write_prefix(f
: &mut Formatter
<'_
>, sign
: Option
<char>, prefix
: Option
<&str>) -> Result
{
1246 if let Some(c
) = sign
{
1247 f
.buf
.write_char(c
)?
;
1249 if let Some(prefix
) = prefix { f.buf.write_str(prefix) }
else { Ok(()) }
1252 // The `width` field is more of a `min-width` parameter at this point.
1254 // If there's no minimum length requirements then we can just
1257 write_prefix(self, sign
, prefix
)?
;
1258 self.buf
.write_str(buf
)
1260 // Check if we're over the minimum width, if so then we can also
1261 // just write the bytes.
1262 Some(min
) if width
>= min
=> {
1263 write_prefix(self, sign
, prefix
)?
;
1264 self.buf
.write_str(buf
)
1266 // The sign and prefix goes before the padding if the fill character
1268 Some(min
) if self.sign_aware_zero_pad() => {
1269 let old_fill
= crate::mem
::replace(&mut self.fill
, '
0'
);
1270 let old_align
= crate::mem
::replace(&mut self.align
, rt
::v1
::Alignment
::Right
);
1271 write_prefix(self, sign
, prefix
)?
;
1272 let post_padding
= self.padding(min
- width
, rt
::v1
::Alignment
::Right
)?
;
1273 self.buf
.write_str(buf
)?
;
1274 post_padding
.write(self.buf
)?
;
1275 self.fill
= old_fill
;
1276 self.align
= old_align
;
1279 // Otherwise, the sign and prefix goes after the padding
1281 let post_padding
= self.padding(min
- width
, rt
::v1
::Alignment
::Right
)?
;
1282 write_prefix(self, sign
, prefix
)?
;
1283 self.buf
.write_str(buf
)?
;
1284 post_padding
.write(self.buf
)
1289 /// This function takes a string slice and emits it to the internal buffer
1290 /// after applying the relevant formatting flags specified. The flags
1291 /// recognized for generic strings are:
1293 /// * width - the minimum width of what to emit
1294 /// * fill/align - what to emit and where to emit it if the string
1295 /// provided needs to be padded
1296 /// * precision - the maximum length to emit, the string is truncated if it
1297 /// is longer than this length
1299 /// Notably this function ignores the `flag` parameters.
1308 /// impl fmt::Display for Foo {
1309 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1310 /// formatter.pad("Foo")
1314 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1315 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub fn pad(&mut self, s
: &str) -> Result
{
1319 // Make sure there's a fast path up front
1320 if self.width
.is_none() && self.precision
.is_none() {
1321 return self.buf
.write_str(s
);
1323 // The `precision` field can be interpreted as a `max-width` for the
1324 // string being formatted.
1325 let s
= if let Some(max
) = self.precision
{
1326 // If our string is longer that the precision, then we must have
1327 // truncation. However other flags like `fill`, `width` and `align`
1328 // must act as always.
1329 if let Some((i
, _
)) = s
.char_indices().nth(max
) {
1330 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1331 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1332 // `unsafe` and otherwise don't emit any panic-related code
1334 s
.get(..i
).unwrap_or(&s
)
1341 // The `width` field is more of a `min-width` parameter at this point.
1343 // If we're under the maximum length, and there's no minimum length
1344 // requirements, then we can just emit the string
1345 None
=> self.buf
.write_str(s
),
1346 // If we're under the maximum width, check if we're over the minimum
1347 // width, if so it's as easy as just emitting the string.
1348 Some(width
) if s
.chars().count() >= width
=> self.buf
.write_str(s
),
1349 // If we're under both the maximum and the minimum width, then fill
1350 // up the minimum width with the specified string + some alignment.
1352 let align
= rt
::v1
::Alignment
::Left
;
1353 let post_padding
= self.padding(width
- s
.chars().count(), align
)?
;
1354 self.buf
.write_str(s
)?
;
1355 post_padding
.write(self.buf
)
1360 /// Write the pre-padding and return the unwritten post-padding. Callers are
1361 /// responsible for ensuring post-padding is written after the thing that is
1366 default: rt
::v1
::Alignment
,
1367 ) -> result
::Result
<PostPadding
, Error
> {
1368 let align
= match self.align
{
1369 rt
::v1
::Alignment
::Unknown
=> default,
1373 let (pre_pad
, post_pad
) = match align
{
1374 rt
::v1
::Alignment
::Left
=> (0, padding
),
1375 rt
::v1
::Alignment
::Right
| rt
::v1
::Alignment
::Unknown
=> (padding
, 0),
1376 rt
::v1
::Alignment
::Center
=> (padding
/ 2, (padding
+ 1) / 2),
1379 for _
in 0..pre_pad
{
1380 self.buf
.write_char(self.fill
)?
;
1383 Ok(PostPadding
::new(self.fill
, post_pad
))
1386 /// Takes the formatted parts and applies the padding.
1387 /// Assumes that the caller already has rendered the parts with required precision,
1388 /// so that `self.precision` can be ignored.
1389 fn pad_formatted_parts(&mut self, formatted
: &flt2dec
::Formatted
<'_
>) -> Result
{
1390 if let Some(mut width
) = self.width
{
1391 // for the sign-aware zero padding, we render the sign first and
1392 // behave as if we had no sign from the beginning.
1393 let mut formatted
= formatted
.clone();
1394 let old_fill
= self.fill
;
1395 let old_align
= self.align
;
1396 let mut align
= old_align
;
1397 if self.sign_aware_zero_pad() {
1398 // a sign always goes first
1399 let sign
= formatted
.sign
;
1400 self.buf
.write_str(sign
)?
;
1402 // remove the sign from the formatted parts
1403 formatted
.sign
= "";
1404 width
= width
.saturating_sub(sign
.len());
1405 align
= rt
::v1
::Alignment
::Right
;
1407 self.align
= rt
::v1
::Alignment
::Right
;
1410 // remaining parts go through the ordinary padding process.
1411 let len
= formatted
.len();
1412 let ret
= if width
<= len
{
1414 self.write_formatted_parts(&formatted
)
1416 let post_padding
= self.padding(width
- len
, align
)?
;
1417 self.write_formatted_parts(&formatted
)?
;
1418 post_padding
.write(self.buf
)
1420 self.fill
= old_fill
;
1421 self.align
= old_align
;
1424 // this is the common case and we take a shortcut
1425 self.write_formatted_parts(formatted
)
1429 fn write_formatted_parts(&mut self, formatted
: &flt2dec
::Formatted
<'_
>) -> Result
{
1430 fn write_bytes(buf
: &mut dyn Write
, s
: &[u8]) -> Result
{
1431 // SAFETY: This is used for `flt2dec::Part::Num` and `flt2dec::Part::Copy`.
1432 // It's safe to use for `flt2dec::Part::Num` since every char `c` is between
1433 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1434 // It's also probably safe in practice to use for `flt2dec::Part::Copy(buf)`
1435 // since `buf` should be plain ASCII, but it's possible for someone to pass
1436 // in a bad value for `buf` into `flt2dec::to_shortest_str` since it is a
1438 // FIXME: Determine whether this could result in UB.
1439 buf
.write_str(unsafe { str::from_utf8_unchecked(s) }
)
1442 if !formatted
.sign
.is_empty() {
1443 self.buf
.write_str(formatted
.sign
)?
;
1445 for part
in formatted
.parts
{
1447 flt2dec
::Part
::Zero(mut nzeroes
) => {
1448 const ZEROES
: &str = // 64 zeroes
1449 "0000000000000000000000000000000000000000000000000000000000000000";
1450 while nzeroes
> ZEROES
.len() {
1451 self.buf
.write_str(ZEROES
)?
;
1452 nzeroes
-= ZEROES
.len();
1455 self.buf
.write_str(&ZEROES
[..nzeroes
])?
;
1458 flt2dec
::Part
::Num(mut v
) => {
1460 let len
= part
.len();
1461 for c
in s
[..len
].iter_mut().rev() {
1462 *c
= b'
0'
+ (v
% 10) as u8;
1465 write_bytes(self.buf
, &s
[..len
])?
;
1467 flt2dec
::Part
::Copy(buf
) => {
1468 write_bytes(self.buf
, buf
)?
;
1475 /// Writes some data to the underlying buffer contained within this
1485 /// impl fmt::Display for Foo {
1486 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1487 /// formatter.write_str("Foo")
1488 /// // This is equivalent to:
1489 /// // write!(formatter, "Foo")
1493 /// assert_eq!(&format!("{}", Foo), "Foo");
1494 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 pub fn write_str(&mut self, data
: &str) -> Result
{
1498 self.buf
.write_str(data
)
1501 /// Writes some formatted information into this instance.
1508 /// struct Foo(i32);
1510 /// impl fmt::Display for Foo {
1511 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1512 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1516 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1517 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 pub fn write_fmt(&mut self, fmt
: Arguments
<'_
>) -> Result
{
1521 write(self.buf
, fmt
)
1524 /// Flags for formatting
1525 #[stable(feature = "rust1", since = "1.0.0")]
1528 reason
= "use the `sign_plus`, `sign_minus`, `alternate`, \
1529 or `sign_aware_zero_pad` methods instead"
1531 pub fn flags(&self) -> u32 {
1535 /// Character used as 'fill' whenever there is alignment.
1544 /// impl fmt::Display for Foo {
1545 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1546 /// let c = formatter.fill();
1547 /// if let Some(width) = formatter.width() {
1548 /// for _ in 0..width {
1549 /// write!(formatter, "{}", c)?;
1553 /// write!(formatter, "{}", c)
1558 /// // We set alignment to the left with ">".
1559 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1560 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1562 #[stable(feature = "fmt_flags", since = "1.5.0")]
1563 pub fn fill(&self) -> char {
1567 /// Flag indicating what form of alignment was requested.
1572 /// extern crate core;
1574 /// use std::fmt::{self, Alignment};
1578 /// impl fmt::Display for Foo {
1579 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1580 /// let s = if let Some(s) = formatter.align() {
1582 /// Alignment::Left => "left",
1583 /// Alignment::Right => "right",
1584 /// Alignment::Center => "center",
1589 /// write!(formatter, "{}", s)
1593 /// assert_eq!(&format!("{:<}", Foo), "left");
1594 /// assert_eq!(&format!("{:>}", Foo), "right");
1595 /// assert_eq!(&format!("{:^}", Foo), "center");
1596 /// assert_eq!(&format!("{}", Foo), "into the void");
1598 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1599 pub fn align(&self) -> Option
<Alignment
> {
1601 rt
::v1
::Alignment
::Left
=> Some(Alignment
::Left
),
1602 rt
::v1
::Alignment
::Right
=> Some(Alignment
::Right
),
1603 rt
::v1
::Alignment
::Center
=> Some(Alignment
::Center
),
1604 rt
::v1
::Alignment
::Unknown
=> None
,
1608 /// Optionally specified integer width that the output should be.
1615 /// struct Foo(i32);
1617 /// impl fmt::Display for Foo {
1618 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1619 /// if let Some(width) = formatter.width() {
1620 /// // If we received a width, we use it
1621 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1623 /// // Otherwise we do nothing special
1624 /// write!(formatter, "Foo({})", self.0)
1629 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1630 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1632 #[stable(feature = "fmt_flags", since = "1.5.0")]
1633 pub fn width(&self) -> Option
<usize> {
1637 /// Optionally specified precision for numeric types. Alternatively, the
1638 /// maximum width for string types.
1645 /// struct Foo(f32);
1647 /// impl fmt::Display for Foo {
1648 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1649 /// if let Some(precision) = formatter.precision() {
1650 /// // If we received a precision, we use it.
1651 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1653 /// // Otherwise we default to 2.
1654 /// write!(formatter, "Foo({:.2})", self.0)
1659 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1660 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1662 #[stable(feature = "fmt_flags", since = "1.5.0")]
1663 pub fn precision(&self) -> Option
<usize> {
1667 /// Determines if the `+` flag was specified.
1674 /// struct Foo(i32);
1676 /// impl fmt::Display for Foo {
1677 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1678 /// if formatter.sign_plus() {
1679 /// write!(formatter,
1681 /// if self.0 < 0 { '-' } else { '+' },
1684 /// write!(formatter, "Foo({})", self.0)
1689 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1690 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1692 #[stable(feature = "fmt_flags", since = "1.5.0")]
1693 pub fn sign_plus(&self) -> bool
{
1694 self.flags
& (1 << FlagV1
::SignPlus
as u32) != 0
1697 /// Determines if the `-` flag was specified.
1704 /// struct Foo(i32);
1706 /// impl fmt::Display for Foo {
1707 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1708 /// if formatter.sign_minus() {
1709 /// // You want a minus sign? Have one!
1710 /// write!(formatter, "-Foo({})", self.0)
1712 /// write!(formatter, "Foo({})", self.0)
1717 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1718 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1720 #[stable(feature = "fmt_flags", since = "1.5.0")]
1721 pub fn sign_minus(&self) -> bool
{
1722 self.flags
& (1 << FlagV1
::SignMinus
as u32) != 0
1725 /// Determines if the `#` flag was specified.
1732 /// struct Foo(i32);
1734 /// impl fmt::Display for Foo {
1735 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1736 /// if formatter.alternate() {
1737 /// write!(formatter, "Foo({})", self.0)
1739 /// write!(formatter, "{}", self.0)
1744 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1745 /// assert_eq!(&format!("{}", Foo(23)), "23");
1747 #[stable(feature = "fmt_flags", since = "1.5.0")]
1748 pub fn alternate(&self) -> bool
{
1749 self.flags
& (1 << FlagV1
::Alternate
as u32) != 0
1752 /// Determines if the `0` flag was specified.
1759 /// struct Foo(i32);
1761 /// impl fmt::Display for Foo {
1762 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1763 /// assert!(formatter.sign_aware_zero_pad());
1764 /// assert_eq!(formatter.width(), Some(4));
1765 /// // We ignore the formatter's options.
1766 /// write!(formatter, "{}", self.0)
1770 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1772 #[stable(feature = "fmt_flags", since = "1.5.0")]
1773 pub fn sign_aware_zero_pad(&self) -> bool
{
1774 self.flags
& (1 << FlagV1
::SignAwareZeroPad
as u32) != 0
1777 // FIXME: Decide what public API we want for these two flags.
1778 // https://github.com/rust-lang/rust/issues/48584
1779 fn debug_lower_hex(&self) -> bool
{
1780 self.flags
& (1 << FlagV1
::DebugLowerHex
as u32) != 0
1783 fn debug_upper_hex(&self) -> bool
{
1784 self.flags
& (1 << FlagV1
::DebugUpperHex
as u32) != 0
1787 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1788 /// [`fmt::Debug`] implementations for structs.
1790 /// [`fmt::Debug`]: self::Debug
1796 /// use std::net::Ipv4Addr;
1804 /// impl fmt::Debug for Foo {
1805 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1806 /// fmt.debug_struct("Foo")
1807 /// .field("bar", &self.bar)
1808 /// .field("baz", &self.baz)
1809 /// .field("addr", &format_args!("{}", self.addr))
1815 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1816 /// format!("{:?}", Foo {
1818 /// baz: "Hello World".to_string(),
1819 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1823 #[stable(feature = "debug_builders", since = "1.2.0")]
1824 pub fn debug_struct
<'b
>(&'b
mut self, name
: &str) -> DebugStruct
<'b
, 'a
> {
1825 builders
::debug_struct_new(self, name
)
1828 /// Creates a `DebugTuple` builder designed to assist with creation of
1829 /// `fmt::Debug` implementations for tuple structs.
1835 /// use std::marker::PhantomData;
1837 /// struct Foo<T>(i32, String, PhantomData<T>);
1839 /// impl<T> fmt::Debug for Foo<T> {
1840 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1841 /// fmt.debug_tuple("Foo")
1844 /// .field(&format_args!("_"))
1850 /// "Foo(10, \"Hello\", _)",
1851 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1854 #[stable(feature = "debug_builders", since = "1.2.0")]
1855 pub fn debug_tuple
<'b
>(&'b
mut self, name
: &str) -> DebugTuple
<'b
, 'a
> {
1856 builders
::debug_tuple_new(self, name
)
1859 /// Creates a `DebugList` builder designed to assist with creation of
1860 /// `fmt::Debug` implementations for list-like structures.
1867 /// struct Foo(Vec<i32>);
1869 /// impl fmt::Debug for Foo {
1870 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1871 /// fmt.debug_list().entries(self.0.iter()).finish()
1875 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
1877 #[stable(feature = "debug_builders", since = "1.2.0")]
1878 pub fn debug_list
<'b
>(&'b
mut self) -> DebugList
<'b
, 'a
> {
1879 builders
::debug_list_new(self)
1882 /// Creates a `DebugSet` builder designed to assist with creation of
1883 /// `fmt::Debug` implementations for set-like structures.
1890 /// struct Foo(Vec<i32>);
1892 /// impl fmt::Debug for Foo {
1893 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1894 /// fmt.debug_set().entries(self.0.iter()).finish()
1898 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
1901 /// [`format_args!`]: crate::format_args
1903 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1904 /// to build a list of match arms:
1909 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1910 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1912 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1914 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1916 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1917 /// L::fmt(&(self.0).0, fmt)?;
1918 /// fmt.write_str(" => ")?;
1919 /// R::fmt(&(self.0).1, fmt)
1923 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1925 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1927 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1929 /// .entries(self.0.iter().map(Arm))
1930 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1935 #[stable(feature = "debug_builders", since = "1.2.0")]
1936 pub fn debug_set
<'b
>(&'b
mut self) -> DebugSet
<'b
, 'a
> {
1937 builders
::debug_set_new(self)
1940 /// Creates a `DebugMap` builder designed to assist with creation of
1941 /// `fmt::Debug` implementations for map-like structures.
1948 /// struct Foo(Vec<(String, i32)>);
1950 /// impl fmt::Debug for Foo {
1951 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1952 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1957 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1958 /// r#"{"A": 10, "B": 11}"#
1961 #[stable(feature = "debug_builders", since = "1.2.0")]
1962 pub fn debug_map
<'b
>(&'b
mut self) -> DebugMap
<'b
, 'a
> {
1963 builders
::debug_map_new(self)
1967 #[stable(since = "1.2.0", feature = "formatter_write")]
1968 impl Write
for Formatter
<'_
> {
1969 fn write_str(&mut self, s
: &str) -> Result
{
1970 self.buf
.write_str(s
)
1973 fn write_char(&mut self, c
: char) -> Result
{
1974 self.buf
.write_char(c
)
1977 fn write_fmt(&mut self, args
: Arguments
<'_
>) -> Result
{
1978 write(self.buf
, args
)
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 impl Display
for Error
{
1984 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
1985 Display
::fmt("an error occurred when formatting an argument", f
)
1989 // Implementations of the core formatting traits
1991 macro_rules
! fmt_refs
{
1992 ($
($tr
:ident
),*) => {
1994 #[stable(feature = "rust1", since = "1.0.0")]
1995 impl<T
: ?Sized
+ $tr
> $tr
for &T
{
1996 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result { $tr::fmt(&**self, f) }
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 impl<T
: ?Sized
+ $tr
> $tr
for &mut T
{
2000 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result { $tr::fmt(&**self, f) }
2006 fmt_refs
! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2008 #[unstable(feature = "never_type", issue = "35121")]
2010 fn fmt(&self, _
: &mut Formatter
<'_
>) -> Result
{
2015 #[unstable(feature = "never_type", issue = "35121")]
2016 impl Display
for ! {
2017 fn fmt(&self, _
: &mut Formatter
<'_
>) -> Result
{
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 impl Debug
for bool
{
2025 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2026 Display
::fmt(self, f
)
2030 #[stable(feature = "rust1", since = "1.0.0")]
2031 impl Display
for bool
{
2032 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2033 Display
::fmt(if *self { "true" }
else { "false" }
, f
)
2037 #[stable(feature = "rust1", since = "1.0.0")]
2038 impl Debug
for str {
2039 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2042 for (i, c) in self.char_indices() {
2043 let esc = c.escape_debug();
2044 // If char needs escaping, flush backlog so far and write, else skip
2046 f.write_str(&self[from..i])?;
2050 from = i + c.len_utf8();
2053 f.write_str(&self[from..])?;
2058 #[stable(feature = "rust1", since = "1.0.0")]
2059 impl Display
for str {
2060 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2065 #[stable(feature = "rust1", since = "1.0.0")]
2066 impl Debug
for char {
2067 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2068 f
.write_char('
\''
)?
;
2069 for c
in self.escape_debug() {
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 impl Display
for char {
2078 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2079 if f
.width
.is_none() && f
.precision
.is_none() {
2082 f
.pad(self.encode_utf8(&mut [0; 4]))
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 impl<T
: ?Sized
> Pointer
for *const T
{
2089 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2090 let old_width
= f
.width
;
2091 let old_flags
= f
.flags
;
2093 // The alternate flag is already treated by LowerHex as being special-
2094 // it denotes whether to prefix with 0x. We use it to work out whether
2095 // or not to zero extend, and then unconditionally set it to get the
2098 f
.flags
|= 1 << (FlagV1
::SignAwareZeroPad
as u32);
2100 if f
.width
.is_none() {
2101 f
.width
= Some((usize::BITS
/ 4) as usize + 2);
2104 f
.flags
|= 1 << (FlagV1
::Alternate
as u32);
2106 let ret
= LowerHex
::fmt(&(*self as *const () as usize), f
);
2108 f
.width
= old_width
;
2109 f
.flags
= old_flags
;
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 impl<T
: ?Sized
> Pointer
for *mut T
{
2117 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2118 Pointer
::fmt(&(*self as *const T
), f
)
2122 #[stable(feature = "rust1", since = "1.0.0")]
2123 impl<T
: ?Sized
> Pointer
for &T
{
2124 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2125 Pointer
::fmt(&(*self as *const T
), f
)
2129 #[stable(feature = "rust1", since = "1.0.0")]
2130 impl<T
: ?Sized
> Pointer
for &mut T
{
2131 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2132 Pointer
::fmt(&(&**self as *const T
), f
)
2136 // Implementation of Display/Debug for various core types
2138 #[stable(feature = "rust1", since = "1.0.0")]
2139 impl<T
: ?Sized
> Debug
for *const T
{
2140 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2141 Pointer
::fmt(self, f
)
2144 #[stable(feature = "rust1", since = "1.0.0")]
2145 impl<T
: ?Sized
> Debug
for *mut T
{
2146 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2147 Pointer
::fmt(self, f
)
2152 ($name
:ident
, $
($other
:ident
,)*) => (tuple
! { $($other,)* }
)
2155 macro_rules
! tuple
{
2157 ( $
($name
:ident
,)+ ) => (
2158 #[stable(feature = "rust1", since = "1.0.0")]
2159 impl<$
($name
:Debug
),+> Debug
for ($
($name
,)+) where last_type
!($
($name
,)+): ?Sized
{
2160 #[allow(non_snake_case, unused_assignments)]
2161 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2162 let mut builder
= f
.debug_tuple("");
2163 let ($
(ref $name
,)+) = *self;
2165 builder
.field(&$name
);
2171 peel
! { $($name,)+ }
2175 macro_rules
! last_type
{
2176 ($a
:ident
,) => { $a }
;
2177 ($a
:ident
, $
($rest_a
:ident
,)+) => { last_type!($($rest_a,)+) }
;
2180 tuple
! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2182 #[stable(feature = "rust1", since = "1.0.0")]
2183 impl<T
: Debug
> Debug
for [T
] {
2184 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2185 f
.debug_list().entries(self.iter()).finish()
2189 #[stable(feature = "rust1", since = "1.0.0")]
2192 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2196 #[stable(feature = "rust1", since = "1.0.0")]
2197 impl<T
: ?Sized
> Debug
for PhantomData
<T
> {
2198 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2199 f
.pad("PhantomData")
2203 #[stable(feature = "rust1", since = "1.0.0")]
2204 impl<T
: Copy
+ Debug
> Debug
for Cell
<T
> {
2205 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2206 f
.debug_struct("Cell").field("value", &self.get()).finish()
2210 #[stable(feature = "rust1", since = "1.0.0")]
2211 impl<T
: ?Sized
+ Debug
> Debug
for RefCell
<T
> {
2212 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2213 match self.try_borrow() {
2214 Ok(borrow
) => f
.debug_struct("RefCell").field("value", &borrow
).finish(),
2216 // The RefCell is mutably borrowed so we can't look at its value
2217 // here. Show a placeholder instead.
2218 struct BorrowedPlaceholder
;
2220 impl Debug
for BorrowedPlaceholder
{
2221 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2222 f
.write_str("<borrowed>")
2226 f
.debug_struct("RefCell").field("value", &BorrowedPlaceholder
).finish()
2232 #[stable(feature = "rust1", since = "1.0.0")]
2233 impl<T
: ?Sized
+ Debug
> Debug
for Ref
<'_
, T
> {
2234 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2235 Debug
::fmt(&**self, f
)
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 impl<T
: ?Sized
+ Debug
> Debug
for RefMut
<'_
, T
> {
2241 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2242 Debug
::fmt(&*(self.deref()), f
)
2246 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2247 impl<T
: ?Sized
+ Debug
> Debug
for UnsafeCell
<T
> {
2248 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2253 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2254 // it's a lot easier than creating all of the rt::Piece structures here.
2255 // There are also tests in the alloc crate, for those that need allocations.