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 collection of methods that are required to format a message into a stream.
97 /// This trait is the type which this modules requires when formatting
98 /// information. This is similar to the standard library's [`io::Write`] trait,
99 /// but it is only intended for use in libcore.
101 /// This trait should generally not be implemented by consumers of the standard
102 /// library. The [`write!`] macro accepts an instance of [`io::Write`], and the
103 /// [`io::Write`] trait is favored over implementing this trait.
105 /// [`write!`]: ../../std/macro.write.html
106 /// [`io::Write`]: ../../std/io/trait.Write.html
107 #[stable(feature = "rust1", since = "1.0.0")]
109 /// Writes a string slice into this writer, returning whether the write
112 /// This method can only succeed if the entire string slice was successfully
113 /// written, and this method will not return until all data has been
114 /// written or an error occurs.
118 /// This function will return an instance of [`Error`] on error.
120 /// [`Error`]: struct.Error.html
125 /// use std::fmt::{Error, Write};
127 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
131 /// let mut buf = String::new();
132 /// writer(&mut buf, "hola").unwrap();
133 /// assert_eq!(&buf, "hola");
135 #[stable(feature = "rust1", since = "1.0.0")]
136 fn write_str(&mut self, s
: &str) -> Result
;
138 /// Writes a [`char`] into this writer, returning whether the write succeeded.
140 /// A single [`char`] may be encoded as more than one byte.
141 /// This method can only succeed if the entire byte sequence was successfully
142 /// written, and this method will not return until all data has been
143 /// written or an error occurs.
147 /// This function will return an instance of [`Error`] on error.
149 /// [`char`]: ../../std/primitive.char.html
150 /// [`Error`]: struct.Error.html
155 /// use std::fmt::{Error, Write};
157 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
161 /// let mut buf = String::new();
162 /// writer(&mut buf, 'a').unwrap();
163 /// writer(&mut buf, 'b').unwrap();
164 /// assert_eq!(&buf, "ab");
166 #[stable(feature = "fmt_write_char", since = "1.1.0")]
167 fn write_char(&mut self, c
: char) -> Result
{
168 self.write_str(c
.encode_utf8(&mut [0; 4]))
171 /// Glue for usage of the [`write!`] macro with implementors of this trait.
173 /// This method should generally not be invoked manually, but rather through
174 /// the [`write!`] macro itself.
176 /// [`write!`]: ../../std/macro.write.html
181 /// use std::fmt::{Error, Write};
183 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
184 /// f.write_fmt(format_args!("{}", s))
187 /// let mut buf = String::new();
188 /// writer(&mut buf, "world").unwrap();
189 /// assert_eq!(&buf, "world");
191 #[stable(feature = "rust1", since = "1.0.0")]
192 fn write_fmt(mut self: &mut Self, args
: Arguments
<'_
>) -> Result
{
193 write(&mut self, args
)
197 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
198 impl<W
: Write
+ ?Sized
> Write
for &mut W
{
199 fn write_str(&mut self, s
: &str) -> Result
{
200 (**self).write_str(s
)
203 fn write_char(&mut self, c
: char) -> Result
{
204 (**self).write_char(c
)
207 fn write_fmt(&mut self, args
: Arguments
<'_
>) -> Result
{
208 (**self).write_fmt(args
)
212 /// Configuration for formatting.
214 /// A `Formatter` represents various options related to formatting. Users do not
215 /// construct `Formatter`s directly; a mutable reference to one is passed to
216 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
218 /// To interact with a `Formatter`, you'll call various methods to change the
219 /// various options related to formatting. For examples, please see the
220 /// documentation of the methods defined on `Formatter` below.
222 /// [`Debug`]: trait.Debug.html
223 /// [`Display`]: trait.Display.html
224 #[allow(missing_debug_implementations)]
225 #[stable(feature = "rust1", since = "1.0.0")]
226 pub struct Formatter
<'a
> {
229 align
: rt
::v1
::Alignment
,
230 width
: Option
<usize>,
231 precision
: Option
<usize>,
233 buf
: &'a
mut (dyn Write
+ 'a
),
236 // NB. Argument is essentially an optimized partially applied formatting function,
237 // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
243 /// This struct represents the generic "argument" which is taken by the Xprintf
244 /// family of functions. It contains a function to format the given value. At
245 /// compile time it is ensured that the function and the value have the correct
246 /// types, and then this struct is used to canonicalize arguments to one type.
247 #[derive(Copy, Clone)]
248 #[allow(missing_debug_implementations)]
249 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
251 pub struct ArgumentV1
<'a
> {
253 formatter
: fn(&Opaque
, &mut Formatter
<'_
>) -> Result
,
256 // This guarantees a single stable value for the function pointer associated with
257 // indices/counts in the formatting infrastructure.
259 // Note that a function defined as such would not be correct as functions are
260 // always tagged unnamed_addr with the current lowering to LLVM IR, so their
261 // address is not considered important to LLVM and as such the as_usize cast
262 // could have been miscompiled. In practice, we never call as_usize on non-usize
263 // containing data (as a matter of static generation of the formatting
264 // arguments), so this is merely an additional check.
266 // We primarily want to ensure that the function pointer at `USIZE_MARKER` has
267 // an address corresponding *only* to functions that also take `&usize` as their
268 // first argument. The read_volatile here ensures that we can safely ready out a
269 // usize from the passed reference and that this address does not point at a
270 // non-usize taking function.
271 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
272 static USIZE_MARKER
: fn(&usize, &mut Formatter
<'_
>) -> Result
= |ptr
, _
| {
273 // SAFETY: ptr is a reference
274 let _v
: usize = unsafe { crate::ptr::read_volatile(ptr) }
;
278 impl<'a
> ArgumentV1
<'a
> {
280 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
281 pub fn new
<'b
, T
>(x
: &'b T
, f
: fn(&T
, &mut Formatter
<'_
>) -> Result
) -> ArgumentV1
<'b
> {
282 // SAFETY: `mem::transmute(x)` is safe because
283 // 1. `&'b T` keeps the lifetime it originated with `'b`
284 // (so as to not have an unbounded lifetime)
285 // 2. `&'b T` and `&'b Opaque` have the same memory layout
286 // (when `T` is `Sized`, as it is here)
287 // `mem::transmute(f)` is safe since `fn(&T, &mut Formatter<'_>) -> Result`
288 // and `fn(&Opaque, &mut Formatter<'_>) -> Result` have the same ABI
289 // (as long as `T` is `Sized`)
290 unsafe { ArgumentV1 { formatter: mem::transmute(f), value: mem::transmute(x) }
}
294 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
295 pub fn from_usize(x
: &usize) -> ArgumentV1
<'_
> {
296 ArgumentV1
::new(x
, USIZE_MARKER
)
299 fn as_usize(&self) -> Option
<usize> {
300 if self.formatter
as usize == USIZE_MARKER
as usize {
301 // SAFETY: The `formatter` field is only set to USIZE_MARKER if
302 // the value is a usize, so this is safe
303 Some(unsafe { *(self.value as *const _ as *const usize) }
)
310 // flags available in the v1 format of format_args
311 #[derive(Copy, Clone)]
321 impl<'a
> Arguments
<'a
> {
322 /// When using the format_args!() macro, this function is used to generate the
323 /// Arguments structure.
326 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
327 pub fn new_v1(pieces
: &'a
[&'a
str], args
: &'a
[ArgumentV1
<'a
>]) -> Arguments
<'a
> {
328 Arguments { pieces, fmt: None, args }
331 /// This function is used to specify nonstandard formatting parameters.
332 /// The `pieces` array must be at least as long as `fmt` to construct
333 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
334 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
335 /// created with `argumentusize`. However, failing to do so doesn't cause
336 /// unsafety, but will ignore invalid .
339 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
340 pub fn new_v1_formatted(
341 pieces
: &'a
[&'a
str],
342 args
: &'a
[ArgumentV1
<'a
>],
343 fmt
: &'a
[rt
::v1
::Argument
],
345 Arguments { pieces, fmt: Some(fmt), args }
348 /// Estimates the length of the formatted text.
350 /// This is intended to be used for setting initial `String` capacity
351 /// when using `format!`. Note: this is neither the lower nor upper bound.
354 #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
355 pub fn estimated_capacity(&self) -> usize {
356 let pieces_length
: usize = self.pieces
.iter().map(|x
| x
.len()).sum();
358 if self.args
.is_empty() {
360 } else if self.pieces
[0] == "" && pieces_length
< 16 {
361 // If the format string starts with an argument,
362 // don't preallocate anything, unless length
363 // of pieces is significant.
366 // There are some arguments, so any additional push
367 // will reallocate the string. To avoid that,
368 // we're "pre-doubling" the capacity here.
369 pieces_length
.checked_mul(2).unwrap_or(0)
374 /// This structure represents a safely precompiled version of a format string
375 /// and its arguments. This cannot be generated at runtime because it cannot
376 /// safely be done, so no constructors are given and the fields are private
377 /// to prevent modification.
379 /// The [`format_args!`] macro will safely create an instance of this structure.
380 /// The macro validates the format string at compile-time so usage of the
381 /// [`write`] and [`format`] functions can be safely performed.
383 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
384 /// and `Display` contexts as seen below. The example also shows that `Debug`
385 /// and `Display` format to the same thing: the interpolated format string
386 /// in `format_args!`.
389 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
390 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
391 /// assert_eq!("1 foo 2", display);
392 /// assert_eq!(display, debug);
395 /// [`format_args!`]: ../../std/macro.format_args.html
396 /// [`format`]: ../../std/fmt/fn.format.html
397 /// [`write`]: ../../std/fmt/fn.write.html
398 #[stable(feature = "rust1", since = "1.0.0")]
399 #[derive(Copy, Clone)]
400 pub struct Arguments
<'a
> {
401 // Format string pieces to print.
402 pieces
: &'a
[&'a
str],
404 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
405 fmt
: Option
<&'a
[rt
::v1
::Argument
]>,
407 // Dynamic arguments for interpolation, to be interleaved with string
408 // pieces. (Every argument is preceded by a string piece.)
409 args
: &'a
[ArgumentV1
<'a
>],
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl Debug
for Arguments
<'_
> {
414 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> Result
{
415 Display
::fmt(self, fmt
)
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl Display
for Arguments
<'_
> {
421 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> Result
{
422 write(fmt
.buf
, *self)
428 /// `Debug` should format the output in a programmer-facing, debugging context.
430 /// Generally speaking, you should just `derive` a `Debug` implementation.
432 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
434 /// For more information on formatters, see [the module-level documentation][module].
436 /// [module]: ../../std/fmt/index.html
438 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
439 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
440 /// comma-separated list of each field's name and `Debug` value, then `}`. For
441 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
442 /// `Debug` values of the fields, then `)`.
446 /// Deriving an implementation:
455 /// let origin = Point { x: 0, y: 0 };
457 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
460 /// Manually implementing:
470 /// impl fmt::Debug for Point {
471 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 /// f.debug_struct("Point")
473 /// .field("x", &self.x)
474 /// .field("y", &self.y)
479 /// let origin = Point { x: 0, y: 0 };
481 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
484 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
485 /// implementations, such as [`debug_struct`].
487 /// `Debug` implementations using either `derive` or the debug builder API
488 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
490 /// [`debug_struct`]: ../../std/fmt/struct.Formatter.html#method.debug_struct
491 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
493 /// Pretty-printing with `#?`:
502 /// let origin = Point { x: 0, y: 0 };
504 /// assert_eq!(format!("The origin is: {:#?}", origin),
505 /// "The origin is: Point {
511 #[stable(feature = "rust1", since = "1.0.0")]
512 #[rustc_on_unimplemented(
515 label
= "`{Self}` cannot be formatted using `{{:?}}`",
516 note
= "add `#[derive(Debug)]` or manually implement `{Debug}`"
518 message
= "`{Self}` doesn't implement `{Debug}`",
519 label
= "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
521 #[doc(alias = "{:?}")]
522 #[rustc_diagnostic_item = "debug_trait"]
524 /// Formats the value using the given formatter.
531 /// struct Position {
536 /// impl fmt::Debug for Position {
537 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
538 /// f.debug_tuple("")
539 /// .field(&self.longitude)
540 /// .field(&self.latitude)
545 /// let position = Position { longitude: 1.987, latitude: 2.983 };
546 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
548 /// assert_eq!(format!("{:#?}", position), "(
553 #[stable(feature = "rust1", since = "1.0.0")]
554 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
557 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
558 pub(crate) mod macros
{
559 /// Derive macro generating an impl of the trait `Debug`.
560 #[rustc_builtin_macro]
561 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
562 #[allow_internal_unstable(core_intrinsics)]
563 pub macro Debug($item
:item
) {
564 /* compiler built-in */
567 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
569 pub use macros
::Debug
;
571 /// Format trait for an empty format, `{}`.
573 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
574 /// output, and so cannot be derived.
576 /// [debug]: trait.Debug.html
578 /// For more information on formatters, see [the module-level documentation][module].
580 /// [module]: ../../std/fmt/index.html
584 /// Implementing `Display` on a type:
594 /// impl fmt::Display for Point {
595 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
596 /// write!(f, "({}, {})", self.x, self.y)
600 /// let origin = Point { x: 0, y: 0 };
602 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
604 #[rustc_on_unimplemented(
606 _Self
= "std::path::Path",
607 label
= "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
608 note
= "call `.display()` or `.to_string_lossy()` to safely print paths, \
609 as they may contain non-Unicode data"
611 message
= "`{Self}` doesn't implement `{Display}`",
612 label
= "`{Self}` cannot be formatted with the default formatter",
613 note
= "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
616 #[stable(feature = "rust1", since = "1.0.0")]
618 /// Formats the value using the given formatter.
625 /// struct Position {
630 /// impl fmt::Display for Position {
631 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
632 /// write!(f, "({}, {})", self.longitude, self.latitude)
636 /// assert_eq!("(1.987, 2.983)",
637 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
639 #[stable(feature = "rust1", since = "1.0.0")]
640 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
645 /// The `Octal` trait should format its output as a number in base-8.
647 /// For primitive signed integers (`i8` to `i128`, and `isize`),
648 /// negative values are formatted as the two’s complement representation.
650 /// The alternate flag, `#`, adds a `0o` in front of the output.
652 /// For more information on formatters, see [the module-level documentation][module].
654 /// [module]: ../../std/fmt/index.html
658 /// Basic usage with `i32`:
661 /// let x = 42; // 42 is '52' in octal
663 /// assert_eq!(format!("{:o}", x), "52");
664 /// assert_eq!(format!("{:#o}", x), "0o52");
666 /// assert_eq!(format!("{:o}", -16), "37777777760");
669 /// Implementing `Octal` on a type:
674 /// struct Length(i32);
676 /// impl fmt::Octal for Length {
677 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
678 /// let val = self.0;
680 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
684 /// let l = Length(9);
686 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
688 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
690 #[stable(feature = "rust1", since = "1.0.0")]
692 /// Formats the value using the given formatter.
693 #[stable(feature = "rust1", since = "1.0.0")]
694 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
699 /// The `Binary` trait should format its output as a number in binary.
701 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
702 /// negative values are formatted as the two’s complement representation.
704 /// The alternate flag, `#`, adds a `0b` in front of the output.
706 /// For more information on formatters, see [the module-level documentation][module].
710 /// Basic usage with [`i32`]:
713 /// let x = 42; // 42 is '101010' in binary
715 /// assert_eq!(format!("{:b}", x), "101010");
716 /// assert_eq!(format!("{:#b}", x), "0b101010");
718 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
721 /// Implementing `Binary` on a type:
726 /// struct Length(i32);
728 /// impl fmt::Binary for Length {
729 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
730 /// let val = self.0;
732 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
736 /// let l = Length(107);
738 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
741 /// format!("l as binary is: {:#032b}", l),
742 /// "l as binary is: 0b000000000000000000000001101011"
746 /// [module]: ../../std/fmt/index.html
747 /// [`i8`]: ../../std/primitive.i8.html
748 /// [`i128`]: ../../std/primitive.i128.html
749 /// [`isize`]: ../../std/primitive.isize.html
750 /// [`i32`]: ../../std/primitive.i32.html
751 #[stable(feature = "rust1", since = "1.0.0")]
753 /// Formats the value using the given formatter.
754 #[stable(feature = "rust1", since = "1.0.0")]
755 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
760 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
763 /// For primitive signed integers (`i8` to `i128`, and `isize`),
764 /// negative values are formatted as the two’s complement representation.
766 /// The alternate flag, `#`, adds a `0x` in front of the output.
768 /// For more information on formatters, see [the module-level documentation][module].
770 /// [module]: ../../std/fmt/index.html
774 /// Basic usage with `i32`:
777 /// let x = 42; // 42 is '2a' in hex
779 /// assert_eq!(format!("{:x}", x), "2a");
780 /// assert_eq!(format!("{:#x}", x), "0x2a");
782 /// assert_eq!(format!("{:x}", -16), "fffffff0");
785 /// Implementing `LowerHex` on a type:
790 /// struct Length(i32);
792 /// impl fmt::LowerHex for Length {
793 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
794 /// let val = self.0;
796 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
800 /// let l = Length(9);
802 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
804 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
806 #[stable(feature = "rust1", since = "1.0.0")]
808 /// Formats the value using the given formatter.
809 #[stable(feature = "rust1", since = "1.0.0")]
810 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
815 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
818 /// For primitive signed integers (`i8` to `i128`, and `isize`),
819 /// negative values are formatted as the two’s complement representation.
821 /// The alternate flag, `#`, adds a `0x` in front of the output.
823 /// For more information on formatters, see [the module-level documentation][module].
825 /// [module]: ../../std/fmt/index.html
829 /// Basic usage with `i32`:
832 /// let x = 42; // 42 is '2A' in hex
834 /// assert_eq!(format!("{:X}", x), "2A");
835 /// assert_eq!(format!("{:#X}", x), "0x2A");
837 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
840 /// Implementing `UpperHex` on a type:
845 /// struct Length(i32);
847 /// impl fmt::UpperHex for Length {
848 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849 /// let val = self.0;
851 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
855 /// let l = Length(i32::MAX);
857 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
859 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
861 #[stable(feature = "rust1", since = "1.0.0")]
863 /// Formats the value using the given formatter.
864 #[stable(feature = "rust1", since = "1.0.0")]
865 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
870 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
873 /// For more information on formatters, see [the module-level documentation][module].
875 /// [module]: ../../std/fmt/index.html
879 /// Basic usage with `&i32`:
884 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
887 /// Implementing `Pointer` on a type:
892 /// struct Length(i32);
894 /// impl fmt::Pointer for Length {
895 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
896 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
898 /// let ptr = self as *const Self;
899 /// fmt::Pointer::fmt(&ptr, f)
903 /// let l = Length(42);
905 /// println!("l is in memory here: {:p}", l);
907 /// let l_ptr = format!("{:018p}", l);
908 /// assert_eq!(l_ptr.len(), 18);
909 /// assert_eq!(&l_ptr[..2], "0x");
911 #[stable(feature = "rust1", since = "1.0.0")]
913 /// Formats the value using the given formatter.
914 #[stable(feature = "rust1", since = "1.0.0")]
915 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
920 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
922 /// For more information on formatters, see [the module-level documentation][module].
924 /// [module]: ../../std/fmt/index.html
928 /// Basic usage with `f64`:
931 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
933 /// assert_eq!(format!("{:e}", x), "4.2e1");
936 /// Implementing `LowerExp` on a type:
941 /// struct Length(i32);
943 /// impl fmt::LowerExp for Length {
944 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
945 /// let val = f64::from(self.0);
946 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
950 /// let l = Length(100);
953 /// format!("l in scientific notation is: {:e}", l),
954 /// "l in scientific notation is: 1e2"
958 /// format!("l in scientific notation is: {:05e}", l),
959 /// "l in scientific notation is: 001e2"
962 #[stable(feature = "rust1", since = "1.0.0")]
964 /// Formats the value using the given formatter.
965 #[stable(feature = "rust1", since = "1.0.0")]
966 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
971 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
973 /// For more information on formatters, see [the module-level documentation][module].
975 /// [module]: ../../std/fmt/index.html
979 /// Basic usage with `f64`:
982 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
984 /// assert_eq!(format!("{:E}", x), "4.2E1");
987 /// Implementing `UpperExp` on a type:
992 /// struct Length(i32);
994 /// impl fmt::UpperExp for Length {
995 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
996 /// let val = f64::from(self.0);
997 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1001 /// let l = Length(100);
1004 /// format!("l in scientific notation is: {:E}", l),
1005 /// "l in scientific notation is: 1E2"
1009 /// format!("l in scientific notation is: {:05E}", l),
1010 /// "l in scientific notation is: 001E2"
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub trait UpperExp
{
1015 /// Formats the value using the given formatter.
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
;
1020 /// The `write` function takes an output stream, and an `Arguments` struct
1021 /// that can be precompiled with the `format_args!` macro.
1023 /// The arguments will be formatted according to the specified format string
1024 /// into the output stream provided.
1033 /// let mut output = String::new();
1034 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1035 /// .expect("Error occurred while trying to write in String");
1036 /// assert_eq!(output, "Hello world!");
1039 /// Please note that using [`write!`] might be preferable. Example:
1042 /// use std::fmt::Write;
1044 /// let mut output = String::new();
1045 /// write!(&mut output, "Hello {}!", "world")
1046 /// .expect("Error occurred while trying to write in String");
1047 /// assert_eq!(output, "Hello world!");
1050 /// [`write!`]: ../../std/macro.write.html
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 pub fn write(output
: &mut dyn Write
, args
: Arguments
<'_
>) -> Result
{
1053 let mut formatter
= Formatter
{
1058 align
: rt
::v1
::Alignment
::Unknown
,
1066 // We can use default formatting parameters for all arguments.
1067 for (arg
, piece
) in args
.args
.iter().zip(args
.pieces
.iter()) {
1068 formatter
.buf
.write_str(*piece
)?
;
1069 (arg
.formatter
)(arg
.value
, &mut formatter
)?
;
1074 // Every spec has a corresponding argument that is preceded by
1076 for (arg
, piece
) in fmt
.iter().zip(args
.pieces
.iter()) {
1077 formatter
.buf
.write_str(*piece
)?
;
1078 run(&mut formatter
, arg
, &args
.args
)?
;
1084 // There can be only one trailing string piece left.
1085 if let Some(piece
) = args
.pieces
.get(idx
) {
1086 formatter
.buf
.write_str(*piece
)?
;
1092 fn run(fmt
: &mut Formatter
<'_
>, arg
: &rt
::v1
::Argument
, args
: &[ArgumentV1
<'_
>]) -> Result
{
1093 fmt
.fill
= arg
.format
.fill
;
1094 fmt
.align
= arg
.format
.align
;
1095 fmt
.flags
= arg
.format
.flags
;
1096 fmt
.width
= getcount(args
, &arg
.format
.width
);
1097 fmt
.precision
= getcount(args
, &arg
.format
.precision
);
1099 // Extract the correct argument
1100 let value
= args
[arg
.position
];
1102 // Then actually do some printing
1103 (value
.formatter
)(value
.value
, fmt
)
1106 fn getcount(args
: &[ArgumentV1
<'_
>], cnt
: &rt
::v1
::Count
) -> Option
<usize> {
1108 rt
::v1
::Count
::Is(n
) => Some(n
),
1109 rt
::v1
::Count
::Implied
=> None
,
1110 rt
::v1
::Count
::Param(i
) => args
[i
].as_usize(),
1114 /// Padding after the end of something. Returned by `Formatter::padding`.
1115 #[must_use = "don't forget to write the post padding"]
1116 struct PostPadding
{
1122 fn new(fill
: char, padding
: usize) -> PostPadding
{
1123 PostPadding { fill, padding }
1126 /// Write this post padding.
1127 fn write(self, buf
: &mut dyn Write
) -> Result
{
1128 for _
in 0..self.padding
{
1129 buf
.write_char(self.fill
)?
;
1135 impl<'a
> Formatter
<'a
> {
1136 fn wrap_buf
<'b
, 'c
, F
>(&'b
mut self, wrap
: F
) -> Formatter
<'c
>
1139 F
: FnOnce(&'b
mut (dyn Write
+ 'b
)) -> &'c
mut (dyn Write
+ 'c
),
1142 // We want to change this
1143 buf
: wrap(self.buf
),
1145 // And preserve these
1150 precision
: self.precision
,
1154 // Helper methods used for padding and processing formatting arguments that
1155 // all formatting traits can use.
1157 /// Performs the correct padding for an integer which has already been
1158 /// emitted into a str. The str should *not* contain the sign for the
1159 /// integer, that will be added by this method.
1163 /// * is_nonnegative - whether the original integer was either positive or zero.
1164 /// * prefix - if the '#' character (Alternate) is provided, this
1165 /// is the prefix to put in front of the number.
1166 /// * buf - the byte array that the number has been formatted into
1168 /// This function will correctly account for the flags provided as well as
1169 /// the minimum width. It will not take precision into account.
1176 /// struct Foo { nb: i32 };
1179 /// fn new(nb: i32) -> Foo {
1186 /// impl fmt::Display for Foo {
1187 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1188 /// // We need to remove "-" from the number output.
1189 /// let tmp = self.nb.abs().to_string();
1191 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1195 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1196 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1197 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1198 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1200 #[stable(feature = "rust1", since = "1.0.0")]
1201 pub fn pad_integral(&mut self, is_nonnegative
: bool
, prefix
: &str, buf
: &str) -> Result
{
1202 let mut width
= buf
.len();
1204 let mut sign
= None
;
1205 if !is_nonnegative
{
1208 } else if self.sign_plus() {
1213 let prefix
= if self.alternate() {
1214 width
+= prefix
.chars().count();
1220 // Writes the sign if it exists, and then the prefix if it was requested
1222 fn write_prefix(f
: &mut Formatter
<'_
>, sign
: Option
<char>, prefix
: Option
<&str>) -> Result
{
1223 if let Some(c
) = sign
{
1224 f
.buf
.write_char(c
)?
;
1226 if let Some(prefix
) = prefix { f.buf.write_str(prefix) }
else { Ok(()) }
1229 // The `width` field is more of a `min-width` parameter at this point.
1231 // If there's no minimum length requirements then we can just
1234 write_prefix(self, sign
, prefix
)?
;
1235 self.buf
.write_str(buf
)
1237 // Check if we're over the minimum width, if so then we can also
1238 // just write the bytes.
1239 Some(min
) if width
>= min
=> {
1240 write_prefix(self, sign
, prefix
)?
;
1241 self.buf
.write_str(buf
)
1243 // The sign and prefix goes before the padding if the fill character
1245 Some(min
) if self.sign_aware_zero_pad() => {
1246 let old_fill
= crate::mem
::replace(&mut self.fill
, '
0'
);
1247 let old_align
= crate::mem
::replace(&mut self.align
, rt
::v1
::Alignment
::Right
);
1248 write_prefix(self, sign
, prefix
)?
;
1249 let post_padding
= self.padding(min
- width
, rt
::v1
::Alignment
::Right
)?
;
1250 self.buf
.write_str(buf
)?
;
1251 post_padding
.write(self.buf
)?
;
1252 self.fill
= old_fill
;
1253 self.align
= old_align
;
1256 // Otherwise, the sign and prefix goes after the padding
1258 let post_padding
= self.padding(min
- width
, rt
::v1
::Alignment
::Right
)?
;
1259 write_prefix(self, sign
, prefix
)?
;
1260 self.buf
.write_str(buf
)?
;
1261 post_padding
.write(self.buf
)
1266 /// This function takes a string slice and emits it to the internal buffer
1267 /// after applying the relevant formatting flags specified. The flags
1268 /// recognized for generic strings are:
1270 /// * width - the minimum width of what to emit
1271 /// * fill/align - what to emit and where to emit it if the string
1272 /// provided needs to be padded
1273 /// * precision - the maximum length to emit, the string is truncated if it
1274 /// is longer than this length
1276 /// Notably this function ignores the `flag` parameters.
1285 /// impl fmt::Display for Foo {
1286 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1287 /// formatter.pad("Foo")
1291 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1292 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1294 #[stable(feature = "rust1", since = "1.0.0")]
1295 pub fn pad(&mut self, s
: &str) -> Result
{
1296 // Make sure there's a fast path up front
1297 if self.width
.is_none() && self.precision
.is_none() {
1298 return self.buf
.write_str(s
);
1300 // The `precision` field can be interpreted as a `max-width` for the
1301 // string being formatted.
1302 let s
= if let Some(max
) = self.precision
{
1303 // If our string is longer that the precision, then we must have
1304 // truncation. However other flags like `fill`, `width` and `align`
1305 // must act as always.
1306 if let Some((i
, _
)) = s
.char_indices().nth(max
) {
1307 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1308 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1309 // `unsafe` and otherwise don't emit any panic-related code
1311 s
.get(..i
).unwrap_or(&s
)
1318 // The `width` field is more of a `min-width` parameter at this point.
1320 // If we're under the maximum length, and there's no minimum length
1321 // requirements, then we can just emit the string
1322 None
=> self.buf
.write_str(s
),
1323 // If we're under the maximum width, check if we're over the minimum
1324 // width, if so it's as easy as just emitting the string.
1325 Some(width
) if s
.chars().count() >= width
=> self.buf
.write_str(s
),
1326 // If we're under both the maximum and the minimum width, then fill
1327 // up the minimum width with the specified string + some alignment.
1329 let align
= rt
::v1
::Alignment
::Left
;
1330 let post_padding
= self.padding(width
- s
.chars().count(), align
)?
;
1331 self.buf
.write_str(s
)?
;
1332 post_padding
.write(self.buf
)
1337 /// Write the pre-padding and return the unwritten post-padding. Callers are
1338 /// responsible for ensuring post-padding is written after the thing that is
1343 default: rt
::v1
::Alignment
,
1344 ) -> result
::Result
<PostPadding
, Error
> {
1345 let align
= match self.align
{
1346 rt
::v1
::Alignment
::Unknown
=> default,
1350 let (pre_pad
, post_pad
) = match align
{
1351 rt
::v1
::Alignment
::Left
=> (0, padding
),
1352 rt
::v1
::Alignment
::Right
| rt
::v1
::Alignment
::Unknown
=> (padding
, 0),
1353 rt
::v1
::Alignment
::Center
=> (padding
/ 2, (padding
+ 1) / 2),
1356 for _
in 0..pre_pad
{
1357 self.buf
.write_char(self.fill
)?
;
1360 Ok(PostPadding
::new(self.fill
, post_pad
))
1363 /// Takes the formatted parts and applies the padding.
1364 /// Assumes that the caller already has rendered the parts with required precision,
1365 /// so that `self.precision` can be ignored.
1366 fn pad_formatted_parts(&mut self, formatted
: &flt2dec
::Formatted
<'_
>) -> Result
{
1367 if let Some(mut width
) = self.width
{
1368 // for the sign-aware zero padding, we render the sign first and
1369 // behave as if we had no sign from the beginning.
1370 let mut formatted
= formatted
.clone();
1371 let old_fill
= self.fill
;
1372 let old_align
= self.align
;
1373 let mut align
= old_align
;
1374 if self.sign_aware_zero_pad() {
1375 // a sign always goes first
1376 let sign
= formatted
.sign
;
1377 self.buf
.write_str(sign
)?
;
1379 // remove the sign from the formatted parts
1380 formatted
.sign
= "";
1381 width
= width
.saturating_sub(sign
.len());
1382 align
= rt
::v1
::Alignment
::Right
;
1384 self.align
= rt
::v1
::Alignment
::Right
;
1387 // remaining parts go through the ordinary padding process.
1388 let len
= formatted
.len();
1389 let ret
= if width
<= len
{
1391 self.write_formatted_parts(&formatted
)
1393 let post_padding
= self.padding(width
- len
, align
)?
;
1394 self.write_formatted_parts(&formatted
)?
;
1395 post_padding
.write(self.buf
)
1397 self.fill
= old_fill
;
1398 self.align
= old_align
;
1401 // this is the common case and we take a shortcut
1402 self.write_formatted_parts(formatted
)
1406 fn write_formatted_parts(&mut self, formatted
: &flt2dec
::Formatted
<'_
>) -> Result
{
1407 fn write_bytes(buf
: &mut dyn Write
, s
: &[u8]) -> Result
{
1408 // SAFETY: This is used for `flt2dec::Part::Num` and `flt2dec::Part::Copy`.
1409 // It's safe to use for `flt2dec::Part::Num` since every char `c` is between
1410 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1411 // It's also probably safe in practice to use for `flt2dec::Part::Copy(buf)`
1412 // since `buf` should be plain ASCII, but it's possible for someone to pass
1413 // in a bad value for `buf` into `flt2dec::to_shortest_str` since it is a
1415 // FIXME: Determine whether this could result in UB.
1416 buf
.write_str(unsafe { str::from_utf8_unchecked(s) }
)
1419 if !formatted
.sign
.is_empty() {
1420 self.buf
.write_str(formatted
.sign
)?
;
1422 for part
in formatted
.parts
{
1424 flt2dec
::Part
::Zero(mut nzeroes
) => {
1425 const ZEROES
: &str = // 64 zeroes
1426 "0000000000000000000000000000000000000000000000000000000000000000";
1427 while nzeroes
> ZEROES
.len() {
1428 self.buf
.write_str(ZEROES
)?
;
1429 nzeroes
-= ZEROES
.len();
1432 self.buf
.write_str(&ZEROES
[..nzeroes
])?
;
1435 flt2dec
::Part
::Num(mut v
) => {
1437 let len
= part
.len();
1438 for c
in s
[..len
].iter_mut().rev() {
1439 *c
= b'
0'
+ (v
% 10) as u8;
1442 write_bytes(self.buf
, &s
[..len
])?
;
1444 flt2dec
::Part
::Copy(buf
) => {
1445 write_bytes(self.buf
, buf
)?
;
1452 /// Writes some data to the underlying buffer contained within this
1462 /// impl fmt::Display for Foo {
1463 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1464 /// formatter.write_str("Foo")
1465 /// // This is equivalent to:
1466 /// // write!(formatter, "Foo")
1470 /// assert_eq!(&format!("{}", Foo), "Foo");
1471 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 pub fn write_str(&mut self, data
: &str) -> Result
{
1475 self.buf
.write_str(data
)
1478 /// Writes some formatted information into this instance.
1485 /// struct Foo(i32);
1487 /// impl fmt::Display for Foo {
1488 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1489 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1493 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1494 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 pub fn write_fmt(&mut self, fmt
: Arguments
<'_
>) -> Result
{
1498 write(self.buf
, fmt
)
1501 /// Flags for formatting
1502 #[stable(feature = "rust1", since = "1.0.0")]
1505 reason
= "use the `sign_plus`, `sign_minus`, `alternate`, \
1506 or `sign_aware_zero_pad` methods instead"
1508 pub fn flags(&self) -> u32 {
1512 /// Character used as 'fill' whenever there is alignment.
1521 /// impl fmt::Display for Foo {
1522 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1523 /// let c = formatter.fill();
1524 /// if let Some(width) = formatter.width() {
1525 /// for _ in 0..width {
1526 /// write!(formatter, "{}", c)?;
1530 /// write!(formatter, "{}", c)
1535 /// // We set alignment to the left with ">".
1536 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1537 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1539 #[stable(feature = "fmt_flags", since = "1.5.0")]
1540 pub fn fill(&self) -> char {
1544 /// Flag indicating what form of alignment was requested.
1549 /// extern crate core;
1551 /// use std::fmt::{self, Alignment};
1555 /// impl fmt::Display for Foo {
1556 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1557 /// let s = if let Some(s) = formatter.align() {
1559 /// Alignment::Left => "left",
1560 /// Alignment::Right => "right",
1561 /// Alignment::Center => "center",
1566 /// write!(formatter, "{}", s)
1570 /// assert_eq!(&format!("{:<}", Foo), "left");
1571 /// assert_eq!(&format!("{:>}", Foo), "right");
1572 /// assert_eq!(&format!("{:^}", Foo), "center");
1573 /// assert_eq!(&format!("{}", Foo), "into the void");
1575 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1576 pub fn align(&self) -> Option
<Alignment
> {
1578 rt
::v1
::Alignment
::Left
=> Some(Alignment
::Left
),
1579 rt
::v1
::Alignment
::Right
=> Some(Alignment
::Right
),
1580 rt
::v1
::Alignment
::Center
=> Some(Alignment
::Center
),
1581 rt
::v1
::Alignment
::Unknown
=> None
,
1585 /// Optionally specified integer width that the output should be.
1592 /// struct Foo(i32);
1594 /// impl fmt::Display for Foo {
1595 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1596 /// if let Some(width) = formatter.width() {
1597 /// // If we received a width, we use it
1598 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1600 /// // Otherwise we do nothing special
1601 /// write!(formatter, "Foo({})", self.0)
1606 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1607 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1609 #[stable(feature = "fmt_flags", since = "1.5.0")]
1610 pub fn width(&self) -> Option
<usize> {
1614 /// Optionally specified precision for numeric types.
1621 /// struct Foo(f32);
1623 /// impl fmt::Display for Foo {
1624 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1625 /// if let Some(precision) = formatter.precision() {
1626 /// // If we received a precision, we use it.
1627 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1629 /// // Otherwise we default to 2.
1630 /// write!(formatter, "Foo({:.2})", self.0)
1635 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1636 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1638 #[stable(feature = "fmt_flags", since = "1.5.0")]
1639 pub fn precision(&self) -> Option
<usize> {
1643 /// Determines if the `+` flag was specified.
1650 /// struct Foo(i32);
1652 /// impl fmt::Display for Foo {
1653 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1654 /// if formatter.sign_plus() {
1655 /// write!(formatter,
1657 /// if self.0 < 0 { '-' } else { '+' },
1660 /// write!(formatter, "Foo({})", self.0)
1665 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1666 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1668 #[stable(feature = "fmt_flags", since = "1.5.0")]
1669 pub fn sign_plus(&self) -> bool
{
1670 self.flags
& (1 << FlagV1
::SignPlus
as u32) != 0
1673 /// Determines if the `-` flag was specified.
1680 /// struct Foo(i32);
1682 /// impl fmt::Display for Foo {
1683 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1684 /// if formatter.sign_minus() {
1685 /// // You want a minus sign? Have one!
1686 /// write!(formatter, "-Foo({})", self.0)
1688 /// write!(formatter, "Foo({})", self.0)
1693 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1694 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1696 #[stable(feature = "fmt_flags", since = "1.5.0")]
1697 pub fn sign_minus(&self) -> bool
{
1698 self.flags
& (1 << FlagV1
::SignMinus
as u32) != 0
1701 /// Determines if the `#` flag was specified.
1708 /// struct Foo(i32);
1710 /// impl fmt::Display for Foo {
1711 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1712 /// if formatter.alternate() {
1713 /// write!(formatter, "Foo({})", self.0)
1715 /// write!(formatter, "{}", self.0)
1720 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1721 /// assert_eq!(&format!("{}", Foo(23)), "23");
1723 #[stable(feature = "fmt_flags", since = "1.5.0")]
1724 pub fn alternate(&self) -> bool
{
1725 self.flags
& (1 << FlagV1
::Alternate
as u32) != 0
1728 /// Determines if the `0` flag was specified.
1735 /// struct Foo(i32);
1737 /// impl fmt::Display for Foo {
1738 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1739 /// assert!(formatter.sign_aware_zero_pad());
1740 /// assert_eq!(formatter.width(), Some(4));
1741 /// // We ignore the formatter's options.
1742 /// write!(formatter, "{}", self.0)
1746 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1748 #[stable(feature = "fmt_flags", since = "1.5.0")]
1749 pub fn sign_aware_zero_pad(&self) -> bool
{
1750 self.flags
& (1 << FlagV1
::SignAwareZeroPad
as u32) != 0
1753 // FIXME: Decide what public API we want for these two flags.
1754 // https://github.com/rust-lang/rust/issues/48584
1755 fn debug_lower_hex(&self) -> bool
{
1756 self.flags
& (1 << FlagV1
::DebugLowerHex
as u32) != 0
1759 fn debug_upper_hex(&self) -> bool
{
1760 self.flags
& (1 << FlagV1
::DebugUpperHex
as u32) != 0
1763 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1764 /// [`fmt::Debug`] implementations for structs.
1766 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1767 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1773 /// use std::net::Ipv4Addr;
1781 /// impl fmt::Debug for Foo {
1782 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1783 /// fmt.debug_struct("Foo")
1784 /// .field("bar", &self.bar)
1785 /// .field("baz", &self.baz)
1786 /// .field("addr", &format_args!("{}", self.addr))
1792 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1793 /// format!("{:?}", Foo {
1795 /// baz: "Hello World".to_string(),
1796 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1800 #[stable(feature = "debug_builders", since = "1.2.0")]
1801 pub fn debug_struct
<'b
>(&'b
mut self, name
: &str) -> DebugStruct
<'b
, 'a
> {
1802 builders
::debug_struct_new(self, name
)
1805 /// Creates a `DebugTuple` builder designed to assist with creation of
1806 /// `fmt::Debug` implementations for tuple structs.
1812 /// use std::marker::PhantomData;
1814 /// struct Foo<T>(i32, String, PhantomData<T>);
1816 /// impl<T> fmt::Debug for Foo<T> {
1817 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1818 /// fmt.debug_tuple("Foo")
1821 /// .field(&format_args!("_"))
1827 /// "Foo(10, \"Hello\", _)",
1828 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1831 #[stable(feature = "debug_builders", since = "1.2.0")]
1832 pub fn debug_tuple
<'b
>(&'b
mut self, name
: &str) -> DebugTuple
<'b
, 'a
> {
1833 builders
::debug_tuple_new(self, name
)
1836 /// Creates a `DebugList` builder designed to assist with creation of
1837 /// `fmt::Debug` implementations for list-like structures.
1844 /// struct Foo(Vec<i32>);
1846 /// impl fmt::Debug for Foo {
1847 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1848 /// fmt.debug_list().entries(self.0.iter()).finish()
1852 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
1854 #[stable(feature = "debug_builders", since = "1.2.0")]
1855 pub fn debug_list
<'b
>(&'b
mut self) -> DebugList
<'b
, 'a
> {
1856 builders
::debug_list_new(self)
1859 /// Creates a `DebugSet` builder designed to assist with creation of
1860 /// `fmt::Debug` implementations for set-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_set().entries(self.0.iter()).finish()
1875 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
1878 /// [`format_args!`]: ../../std/macro.format_args.html
1880 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1881 /// to build a list of match arms:
1886 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1887 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1889 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1891 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1893 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1894 /// L::fmt(&(self.0).0, fmt)?;
1895 /// fmt.write_str(" => ")?;
1896 /// R::fmt(&(self.0).1, fmt)
1900 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1902 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1904 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1906 /// .entries(self.0.iter().map(Arm))
1907 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1912 #[stable(feature = "debug_builders", since = "1.2.0")]
1913 pub fn debug_set
<'b
>(&'b
mut self) -> DebugSet
<'b
, 'a
> {
1914 builders
::debug_set_new(self)
1917 /// Creates a `DebugMap` builder designed to assist with creation of
1918 /// `fmt::Debug` implementations for map-like structures.
1925 /// struct Foo(Vec<(String, i32)>);
1927 /// impl fmt::Debug for Foo {
1928 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1929 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1934 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1935 /// r#"{"A": 10, "B": 11}"#
1938 #[stable(feature = "debug_builders", since = "1.2.0")]
1939 pub fn debug_map
<'b
>(&'b
mut self) -> DebugMap
<'b
, 'a
> {
1940 builders
::debug_map_new(self)
1944 #[stable(since = "1.2.0", feature = "formatter_write")]
1945 impl Write
for Formatter
<'_
> {
1946 fn write_str(&mut self, s
: &str) -> Result
{
1947 self.buf
.write_str(s
)
1950 fn write_char(&mut self, c
: char) -> Result
{
1951 self.buf
.write_char(c
)
1954 fn write_fmt(&mut self, args
: Arguments
<'_
>) -> Result
{
1955 write(self.buf
, args
)
1959 #[stable(feature = "rust1", since = "1.0.0")]
1960 impl Display
for Error
{
1961 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
1962 Display
::fmt("an error occurred when formatting an argument", f
)
1966 // Implementations of the core formatting traits
1968 macro_rules
! fmt_refs
{
1969 ($
($tr
:ident
),*) => {
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 impl<T
: ?Sized
+ $tr
> $tr
for &T
{
1973 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result { $tr::fmt(&**self, f) }
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 impl<T
: ?Sized
+ $tr
> $tr
for &mut T
{
1977 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result { $tr::fmt(&**self, f) }
1983 fmt_refs
! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1985 #[unstable(feature = "never_type", issue = "35121")]
1987 fn fmt(&self, _
: &mut Formatter
<'_
>) -> Result
{
1992 #[unstable(feature = "never_type", issue = "35121")]
1993 impl Display
for ! {
1994 fn fmt(&self, _
: &mut Formatter
<'_
>) -> Result
{
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 impl Debug
for bool
{
2002 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2003 Display
::fmt(self, f
)
2007 #[stable(feature = "rust1", since = "1.0.0")]
2008 impl Display
for bool
{
2009 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2010 Display
::fmt(if *self { "true" }
else { "false" }
, f
)
2014 #[stable(feature = "rust1", since = "1.0.0")]
2015 impl Debug
for str {
2016 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2019 for (i, c) in self.char_indices() {
2020 let esc = c.escape_debug();
2021 // If char needs escaping, flush backlog so far and write, else skip
2023 f.write_str(&self[from..i])?;
2027 from = i + c.len_utf8();
2030 f.write_str(&self[from..])?;
2035 #[stable(feature = "rust1", since = "1.0.0")]
2036 impl Display
for str {
2037 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2042 #[stable(feature = "rust1", since = "1.0.0")]
2043 impl Debug
for char {
2044 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2045 f
.write_char('
\''
)?
;
2046 for c
in self.escape_debug() {
2053 #[stable(feature = "rust1", since = "1.0.0")]
2054 impl Display
for char {
2055 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2056 if f
.width
.is_none() && f
.precision
.is_none() {
2059 f
.pad(self.encode_utf8(&mut [0; 4]))
2064 #[stable(feature = "rust1", since = "1.0.0")]
2065 impl<T
: ?Sized
> Pointer
for *const T
{
2066 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2067 let old_width
= f
.width
;
2068 let old_flags
= f
.flags
;
2070 // The alternate flag is already treated by LowerHex as being special-
2071 // it denotes whether to prefix with 0x. We use it to work out whether
2072 // or not to zero extend, and then unconditionally set it to get the
2075 f
.flags
|= 1 << (FlagV1
::SignAwareZeroPad
as u32);
2077 if f
.width
.is_none() {
2078 f
.width
= Some(((mem
::size_of
::<usize>() * 8) / 4) + 2);
2081 f
.flags
|= 1 << (FlagV1
::Alternate
as u32);
2083 let ret
= LowerHex
::fmt(&(*self as *const () as usize), f
);
2085 f
.width
= old_width
;
2086 f
.flags
= old_flags
;
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 impl<T
: ?Sized
> Pointer
for *mut T
{
2094 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2095 Pointer
::fmt(&(*self as *const T
), f
)
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 impl<T
: ?Sized
> Pointer
for &T
{
2101 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2102 Pointer
::fmt(&(*self as *const T
), f
)
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 impl<T
: ?Sized
> Pointer
for &mut T
{
2108 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2109 Pointer
::fmt(&(&**self as *const T
), f
)
2113 // Implementation of Display/Debug for various core types
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 impl<T
: ?Sized
> Debug
for *const T
{
2117 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2118 Pointer
::fmt(self, f
)
2121 #[stable(feature = "rust1", since = "1.0.0")]
2122 impl<T
: ?Sized
> Debug
for *mut T
{
2123 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2124 Pointer
::fmt(self, f
)
2129 ($name
:ident
, $
($other
:ident
,)*) => (tuple
! { $($other,)* }
)
2132 macro_rules
! tuple
{
2134 ( $
($name
:ident
,)+ ) => (
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 impl<$
($name
:Debug
),+> Debug
for ($
($name
,)+) where last_type
!($
($name
,)+): ?Sized
{
2137 #[allow(non_snake_case, unused_assignments)]
2138 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2139 let mut builder
= f
.debug_tuple("");
2140 let ($
(ref $name
,)+) = *self;
2142 builder
.field(&$name
);
2148 peel
! { $($name,)+ }
2152 macro_rules
! last_type
{
2153 ($a
:ident
,) => { $a }
;
2154 ($a
:ident
, $
($rest_a
:ident
,)+) => { last_type!($($rest_a,)+) }
;
2157 tuple
! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2159 #[stable(feature = "rust1", since = "1.0.0")]
2160 impl<T
: Debug
> Debug
for [T
] {
2161 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2162 f
.debug_list().entries(self.iter()).finish()
2166 #[stable(feature = "rust1", since = "1.0.0")]
2169 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 impl<T
: ?Sized
> Debug
for PhantomData
<T
> {
2175 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2176 f
.pad("PhantomData")
2180 #[stable(feature = "rust1", since = "1.0.0")]
2181 impl<T
: Copy
+ Debug
> Debug
for Cell
<T
> {
2182 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2183 f
.debug_struct("Cell").field("value", &self.get()).finish()
2187 #[stable(feature = "rust1", since = "1.0.0")]
2188 impl<T
: ?Sized
+ Debug
> Debug
for RefCell
<T
> {
2189 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2190 match self.try_borrow() {
2191 Ok(borrow
) => f
.debug_struct("RefCell").field("value", &borrow
).finish(),
2193 // The RefCell is mutably borrowed so we can't look at its value
2194 // here. Show a placeholder instead.
2195 struct BorrowedPlaceholder
;
2197 impl Debug
for BorrowedPlaceholder
{
2198 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2199 f
.write_str("<borrowed>")
2203 f
.debug_struct("RefCell").field("value", &BorrowedPlaceholder
).finish()
2209 #[stable(feature = "rust1", since = "1.0.0")]
2210 impl<T
: ?Sized
+ Debug
> Debug
for Ref
<'_
, T
> {
2211 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2212 Debug
::fmt(&**self, f
)
2216 #[stable(feature = "rust1", since = "1.0.0")]
2217 impl<T
: ?Sized
+ Debug
> Debug
for RefMut
<'_
, T
> {
2218 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2219 Debug
::fmt(&*(self.deref()), f
)
2223 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2224 impl<T
: ?Sized
+ Debug
> Debug
for UnsafeCell
<T
> {
2225 fn fmt(&self, f
: &mut Formatter
<'_
>) -> Result
{
2230 // If you expected tests to be here, look instead at the ui/ifmt.rs test,
2231 // it's a lot easier than creating all of the rt::Piece structures here.