1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Utilities for formatting and printing strings.
13 #![stable(feature = "rust1", since = "1.0.0")]
15 use cell::{UnsafeCell, Cell, RefCell, Ref, RefMut};
16 use marker::PhantomData;
28 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
29 /// Possible alignments returned by `Formatter::align`
32 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
33 /// Indication that contents should be left-aligned.
35 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
36 /// Indication that contents should be right-aligned.
38 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
39 /// Indication that contents should be center-aligned.
43 #[stable(feature = "debug_builders", since = "1.2.0")]
44 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
46 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
53 /// The type returned by formatter methods.
67 /// impl fmt::Display for Triangle {
68 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
73 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
75 /// println!("{}", pythagorean_triple);
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub type Result = result::Result<(), Error>;
80 /// The error type which is returned from formatting a message into a stream.
82 /// This type does not support transmission of an error other than that an error
83 /// occurred. Any extra information must be arranged to be transmitted through
86 /// An important thing to remember is that the type `fmt::Error` should not be
87 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
90 /// [`std::io::Error`]: ../../std/io/struct.Error.html
91 /// [`std::error::Error`]: ../../std/error/trait.Error.html
96 /// use std::fmt::{self, write};
98 /// let mut output = String::new();
99 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
100 /// panic!("An error occurred");
103 #[stable(feature = "rust1", since = "1.0.0")]
104 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
107 /// A collection of methods that are required to format a message into a stream.
109 /// This trait is the type which this modules requires when formatting
110 /// information. This is similar to the standard library's [`io::Write`] trait,
111 /// but it is only intended for use in libcore.
113 /// This trait should generally not be implemented by consumers of the standard
114 /// library. The [`write!`] macro accepts an instance of [`io::Write`], and the
115 /// [`io::Write`] trait is favored over implementing this trait.
117 /// [`write!`]: ../../std/macro.write.html
118 /// [`io::Write`]: ../../std/io/trait.Write.html
119 #[stable(feature = "rust1", since = "1.0.0")]
121 /// Writes a slice of bytes into this writer, returning whether the write
124 /// This method can only succeed if the entire byte slice was successfully
125 /// written, and this method will not return until all data has been
126 /// written or an error occurs.
130 /// This function will return an instance of [`Error`] on error.
132 /// [`Error`]: struct.Error.html
137 /// use std::fmt::{Error, Write};
139 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
143 /// let mut buf = String::new();
144 /// writer(&mut buf, "hola").unwrap();
145 /// assert_eq!(&buf, "hola");
147 #[stable(feature = "rust1", since = "1.0.0")]
148 fn write_str(&mut self, s: &str) -> Result;
150 /// Writes a [`char`] into this writer, returning whether the write succeeded.
152 /// A single [`char`] may be encoded as more than one byte.
153 /// This method can only succeed if the entire byte sequence was successfully
154 /// written, and this method will not return until all data has been
155 /// written or an error occurs.
159 /// This function will return an instance of [`Error`] on error.
161 /// [`char`]: ../../std/primitive.char.html
162 /// [`Error`]: struct.Error.html
167 /// use std::fmt::{Error, Write};
169 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
173 /// let mut buf = String::new();
174 /// writer(&mut buf, 'a').unwrap();
175 /// writer(&mut buf, 'b').unwrap();
176 /// assert_eq!(&buf, "ab");
178 #[stable(feature = "fmt_write_char", since = "1.1.0")]
179 fn write_char(&mut self, c: char) -> Result {
180 self.write_str(c.encode_utf8(&mut [0; 4]))
183 /// Glue for usage of the [`write!`] macro with implementors of this trait.
185 /// This method should generally not be invoked manually, but rather through
186 /// the [`write!`] macro itself.
188 /// [`write!`]: ../../std/macro.write.html
193 /// use std::fmt::{Error, Write};
195 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
196 /// f.write_fmt(format_args!("{}", s))
199 /// let mut buf = String::new();
200 /// writer(&mut buf, "world").unwrap();
201 /// assert_eq!(&buf, "world");
203 #[stable(feature = "rust1", since = "1.0.0")]
204 fn write_fmt(&mut self, args: Arguments) -> Result {
205 // This Adapter is needed to allow `self` (of type `&mut
206 // Self`) to be cast to a Write (below) without
207 // requiring a `Sized` bound.
208 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
210 impl<T: ?Sized> Write for Adapter<'_, T>
213 fn write_str(&mut self, s: &str) -> Result {
217 fn write_char(&mut self, c: char) -> Result {
221 fn write_fmt(&mut self, args: Arguments) -> Result {
222 self.0.write_fmt(args)
226 write(&mut Adapter(self), args)
230 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
231 impl<W: Write + ?Sized> Write for &mut W {
232 fn write_str(&mut self, s: &str) -> Result {
233 (**self).write_str(s)
236 fn write_char(&mut self, c: char) -> Result {
237 (**self).write_char(c)
240 fn write_fmt(&mut self, args: Arguments) -> Result {
241 (**self).write_fmt(args)
245 /// A struct to represent both where to emit formatting strings to and how they
246 /// should be formatted. A mutable version of this is passed to all formatting
248 #[allow(missing_debug_implementations)]
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub struct Formatter<'a> {
253 align: rt::v1::Alignment,
254 width: Option<usize>,
255 precision: Option<usize>,
257 buf: &'a mut (dyn Write+'a),
258 curarg: slice::Iter<'a, ArgumentV1<'a>>,
259 args: &'a [ArgumentV1<'a>],
262 // NB. Argument is essentially an optimized partially applied formatting function,
263 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
267 /// Erases all oibits, because `Void` erases the type of the object that
268 /// will be used to produce formatted output. Since we do not know what
269 /// oibits the real types have (and they can have any or none), we need to
270 /// take the most conservative approach and forbid all oibits.
272 /// It was added after #45197 showed that one could share a `!Sync`
273 /// object across threads by passing it into `format_args!`.
274 _oibit_remover: PhantomData<*mut dyn Fn()>,
277 /// This struct represents the generic "argument" which is taken by the Xprintf
278 /// family of functions. It contains a function to format the given value. At
279 /// compile time it is ensured that the function and the value have the correct
280 /// types, and then this struct is used to canonicalize arguments to one type.
282 #[allow(missing_debug_implementations)]
283 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
286 pub struct ArgumentV1<'a> {
288 formatter: fn(&Void, &mut Formatter) -> Result,
291 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
293 impl Clone for ArgumentV1<'_> {
294 fn clone(&self) -> Self {
299 impl<'a> ArgumentV1<'a> {
301 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
306 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
308 pub fn new<'b, T>(x: &'b T,
309 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
312 formatter: mem::transmute(f),
313 value: mem::transmute(x)
319 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
321 pub fn from_usize(x: &usize) -> ArgumentV1 {
322 ArgumentV1::new(x, ArgumentV1::show_usize)
325 fn as_usize(&self) -> Option<usize> {
326 if self.formatter as usize == ArgumentV1::show_usize as usize {
327 Some(unsafe { *(self.value as *const _ as *const usize) })
334 // flags available in the v1 format of format_args
335 #[derive(Copy, Clone)]
336 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, DebugLowerHex, DebugUpperHex }
338 impl<'a> Arguments<'a> {
339 /// When using the format_args!() macro, this function is used to generate the
340 /// Arguments structure.
341 #[doc(hidden)] #[inline]
342 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
344 pub fn new_v1(pieces: &'a [&'a str],
345 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
353 /// This function is used to specify nonstandard formatting parameters.
354 /// The `pieces` array must be at least as long as `fmt` to construct
355 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
356 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
357 /// created with `argumentusize`. However, failing to do so doesn't cause
358 /// unsafety, but will ignore invalid .
359 #[doc(hidden)] #[inline]
360 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
362 pub fn new_v1_formatted(pieces: &'a [&'a str],
363 args: &'a [ArgumentV1<'a>],
364 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
372 /// Estimates the length of the formatted text.
374 /// This is intended to be used for setting initial `String` capacity
375 /// when using `format!`. Note: this is neither the lower nor upper bound.
376 #[doc(hidden)] #[inline]
377 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
379 pub fn estimated_capacity(&self) -> usize {
380 let pieces_length: usize = self.pieces.iter()
381 .map(|x| x.len()).sum();
383 if self.args.is_empty() {
385 } else if self.pieces[0] == "" && pieces_length < 16 {
386 // If the format string starts with an argument,
387 // don't preallocate anything, unless length
388 // of pieces is significant.
391 // There are some arguments, so any additional push
392 // will reallocate the string. To avoid that,
393 // we're "pre-doubling" the capacity here.
394 pieces_length.checked_mul(2).unwrap_or(0)
399 /// This structure represents a safely precompiled version of a format string
400 /// and its arguments. This cannot be generated at runtime because it cannot
401 /// safely be done, so no constructors are given and the fields are private
402 /// to prevent modification.
404 /// The [`format_args!`] macro will safely create an instance of this structure.
405 /// The macro validates the format string at compile-time so usage of the
406 /// [`write`] and [`format`] functions can be safely performed.
408 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
409 /// and `Display` contexts as seen below. The example also shows that `Debug`
410 /// and `Display` format to the same thing: the interpolated format string
411 /// in `format_args!`.
414 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
415 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
416 /// assert_eq!("1 foo 2", display);
417 /// assert_eq!(display, debug);
420 /// [`format_args!`]: ../../std/macro.format_args.html
421 /// [`format`]: ../../std/fmt/fn.format.html
422 /// [`write`]: ../../std/fmt/fn.write.html
423 #[stable(feature = "rust1", since = "1.0.0")]
424 #[derive(Copy, Clone)]
425 pub struct Arguments<'a> {
426 // Format string pieces to print.
427 pieces: &'a [&'a str],
429 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
430 fmt: Option<&'a [rt::v1::Argument]>,
432 // Dynamic arguments for interpolation, to be interleaved with string
433 // pieces. (Every argument is preceded by a string piece.)
434 args: &'a [ArgumentV1<'a>],
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl Debug for Arguments<'_> {
439 fn fmt(&self, fmt: &mut Formatter) -> Result {
440 Display::fmt(self, fmt)
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl Display for Arguments<'_> {
446 fn fmt(&self, fmt: &mut Formatter) -> Result {
447 write(fmt.buf, *self)
453 /// `Debug` should format the output in a programmer-facing, debugging context.
455 /// Generally speaking, you should just `derive` a `Debug` implementation.
457 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
459 /// For more information on formatters, see [the module-level documentation][module].
461 /// [module]: ../../std/fmt/index.html
463 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
464 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
465 /// comma-separated list of each field's name and `Debug` value, then `}`. For
466 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
467 /// `Debug` values of the fields, then `)`.
471 /// Deriving an implementation:
480 /// let origin = Point { x: 0, y: 0 };
482 /// println!("The origin is: {:?}", origin);
485 /// Manually implementing:
495 /// impl fmt::Debug for Point {
496 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
497 /// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
501 /// let origin = Point { x: 0, y: 0 };
503 /// println!("The origin is: {:?}", origin);
509 /// The origin is: Point { x: 0, y: 0 }
512 /// There are a number of `debug_*` methods on [`Formatter`] to help you with manual
513 /// implementations, such as [`debug_struct`][debug_struct].
515 /// `Debug` implementations using either `derive` or the debug builder API
516 /// on [`Formatter`] support pretty printing using the alternate flag: `{:#?}`.
518 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
519 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
521 /// Pretty printing with `#?`:
530 /// let origin = Point { x: 0, y: 0 };
532 /// println!("The origin is: {:#?}", origin);
538 /// The origin is: Point {
543 #[stable(feature = "rust1", since = "1.0.0")]
544 #[rustc_on_unimplemented(
545 on(crate_local, label="`{Self}` cannot be formatted using `{{:?}}`",
546 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 #[lang = "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 /// write!(f, "({:?}, {:?})", self.longitude, self.latitude)
571 /// assert_eq!("(1.987, 2.983)".to_owned(),
572 /// format!("{:?}", Position { longitude: 1.987, latitude: 2.983, }));
574 #[stable(feature = "rust1", since = "1.0.0")]
575 fn fmt(&self, f: &mut Formatter) -> Result;
578 /// Format trait for an empty format, `{}`.
580 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
581 /// output, and so cannot be derived.
583 /// [debug]: trait.Debug.html
585 /// For more information on formatters, see [the module-level documentation][module].
587 /// [module]: ../../std/fmt/index.html
591 /// Implementing `Display` on a type:
601 /// impl fmt::Display for Point {
602 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
603 /// write!(f, "({}, {})", self.x, self.y)
607 /// let origin = Point { x: 0, y: 0 };
609 /// println!("The origin is: {}", origin);
611 #[rustc_on_unimplemented(
612 message="`{Self}` doesn't implement `{Display}`",
613 label="`{Self}` cannot be formatted with the default formatter",
614 note="in format strings you may be able to use `{{:?}}` \
615 (or {{:#?}} for pretty-print) instead",
618 #[stable(feature = "rust1", since = "1.0.0")]
620 /// Formats the value using the given formatter.
627 /// struct Position {
632 /// impl fmt::Display for Position {
633 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
634 /// write!(f, "({}, {})", self.longitude, self.latitude)
638 /// assert_eq!("(1.987, 2.983)".to_owned(),
639 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
641 #[stable(feature = "rust1", since = "1.0.0")]
642 fn fmt(&self, f: &mut Formatter) -> Result;
647 /// The `Octal` trait should format its output as a number in base-8.
649 /// For primitive signed integers (`i8` to `i128`, and `isize`),
650 /// negative values are formatted as the two’s complement representation.
652 /// The alternate flag, `#`, adds a `0o` in front of the output.
654 /// For more information on formatters, see [the module-level documentation][module].
656 /// [module]: ../../std/fmt/index.html
660 /// Basic usage with `i32`:
663 /// let x = 42; // 42 is '52' in octal
665 /// assert_eq!(format!("{:o}", x), "52");
666 /// assert_eq!(format!("{:#o}", x), "0o52");
668 /// assert_eq!(format!("{:o}", -16), "37777777760");
671 /// Implementing `Octal` on a type:
676 /// struct Length(i32);
678 /// impl fmt::Octal for Length {
679 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
680 /// let val = self.0;
682 /// write!(f, "{:o}", val) // delegate to i32's implementation
686 /// let l = Length(9);
688 /// println!("l as octal is: {:o}", l);
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 /// write!(f, "{:b}", val) // delegate to i32's implementation
736 /// let l = Length(107);
738 /// println!("l as binary is: {:b}", l);
741 /// [module]: ../../std/fmt/index.html
742 /// [`i8`]: ../../std/primitive.i8.html
743 /// [`i128`]: ../../std/primitive.i128.html
744 /// [`isize`]: ../../std/primitive.isize.html
745 /// [`i32`]: ../../std/primitive.i32.html
746 #[stable(feature = "rust1", since = "1.0.0")]
748 /// Formats the value using the given formatter.
749 #[stable(feature = "rust1", since = "1.0.0")]
750 fn fmt(&self, f: &mut Formatter) -> Result;
755 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
758 /// For primitive signed integers (`i8` to `i128`, and `isize`),
759 /// negative values are formatted as the two’s complement representation.
761 /// The alternate flag, `#`, adds a `0x` in front of the output.
763 /// For more information on formatters, see [the module-level documentation][module].
765 /// [module]: ../../std/fmt/index.html
769 /// Basic usage with `i32`:
772 /// let x = 42; // 42 is '2a' in hex
774 /// assert_eq!(format!("{:x}", x), "2a");
775 /// assert_eq!(format!("{:#x}", x), "0x2a");
777 /// assert_eq!(format!("{:x}", -16), "fffffff0");
780 /// Implementing `LowerHex` on a type:
785 /// struct Length(i32);
787 /// impl fmt::LowerHex for Length {
788 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
789 /// let val = self.0;
791 /// write!(f, "{:x}", val) // delegate to i32's implementation
795 /// let l = Length(9);
797 /// println!("l as hex is: {:x}", l);
799 #[stable(feature = "rust1", since = "1.0.0")]
801 /// Formats the value using the given formatter.
802 #[stable(feature = "rust1", since = "1.0.0")]
803 fn fmt(&self, f: &mut Formatter) -> Result;
808 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
811 /// For primitive signed integers (`i8` to `i128`, and `isize`),
812 /// negative values are formatted as the two’s complement representation.
814 /// The alternate flag, `#`, adds a `0x` in front of the output.
816 /// For more information on formatters, see [the module-level documentation][module].
818 /// [module]: ../../std/fmt/index.html
822 /// Basic usage with `i32`:
825 /// let x = 42; // 42 is '2A' in hex
827 /// assert_eq!(format!("{:X}", x), "2A");
828 /// assert_eq!(format!("{:#X}", x), "0x2A");
830 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
833 /// Implementing `UpperHex` on a type:
838 /// struct Length(i32);
840 /// impl fmt::UpperHex for Length {
841 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
842 /// let val = self.0;
844 /// write!(f, "{:X}", val) // delegate to i32's implementation
848 /// let l = Length(9);
850 /// println!("l as hex is: {:X}", l);
852 #[stable(feature = "rust1", since = "1.0.0")]
854 /// Formats the value using the given formatter.
855 #[stable(feature = "rust1", since = "1.0.0")]
856 fn fmt(&self, f: &mut Formatter) -> Result;
861 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
864 /// For more information on formatters, see [the module-level documentation][module].
866 /// [module]: ../../std/fmt/index.html
870 /// Basic usage with `&i32`:
875 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
878 /// Implementing `Pointer` on a type:
883 /// struct Length(i32);
885 /// impl fmt::Pointer for Length {
886 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
887 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
889 /// write!(f, "{:p}", self as *const Length)
893 /// let l = Length(42);
895 /// println!("l is in memory here: {:p}", l);
897 #[stable(feature = "rust1", since = "1.0.0")]
899 /// Formats the value using the given formatter.
900 #[stable(feature = "rust1", since = "1.0.0")]
901 fn fmt(&self, f: &mut Formatter) -> Result;
906 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
908 /// For more information on formatters, see [the module-level documentation][module].
910 /// [module]: ../../std/fmt/index.html
914 /// Basic usage with `i32`:
917 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
919 /// assert_eq!(format!("{:e}", x), "4.2e1");
922 /// Implementing `LowerExp` on a type:
927 /// struct Length(i32);
929 /// impl fmt::LowerExp for Length {
930 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
931 /// let val = self.0;
932 /// write!(f, "{}e1", val / 10)
936 /// let l = Length(100);
938 /// println!("l in scientific notation is: {:e}", l);
940 #[stable(feature = "rust1", since = "1.0.0")]
942 /// Formats the value using the given formatter.
943 #[stable(feature = "rust1", since = "1.0.0")]
944 fn fmt(&self, f: &mut Formatter) -> Result;
949 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
951 /// For more information on formatters, see [the module-level documentation][module].
953 /// [module]: ../../std/fmt/index.html
957 /// Basic usage with `f32`:
960 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
962 /// assert_eq!(format!("{:E}", x), "4.2E1");
965 /// Implementing `UpperExp` on a type:
970 /// struct Length(i32);
972 /// impl fmt::UpperExp for Length {
973 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
974 /// let val = self.0;
975 /// write!(f, "{}E1", val / 10)
979 /// let l = Length(100);
981 /// println!("l in scientific notation is: {:E}", l);
983 #[stable(feature = "rust1", since = "1.0.0")]
985 /// Formats the value using the given formatter.
986 #[stable(feature = "rust1", since = "1.0.0")]
987 fn fmt(&self, f: &mut Formatter) -> Result;
990 /// The `write` function takes an output stream, and an `Arguments` struct
991 /// that can be precompiled with the `format_args!` macro.
993 /// The arguments will be formatted according to the specified format string
994 /// into the output stream provided.
1003 /// let mut output = String::new();
1004 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1005 /// .expect("Error occurred while trying to write in String");
1006 /// assert_eq!(output, "Hello world!");
1009 /// Please note that using [`write!`] might be preferable. Example:
1012 /// use std::fmt::Write;
1014 /// let mut output = String::new();
1015 /// write!(&mut output, "Hello {}!", "world")
1016 /// .expect("Error occurred while trying to write in String");
1017 /// assert_eq!(output, "Hello world!");
1020 /// [`write!`]: ../../std/macro.write.html
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub fn write(output: &mut dyn Write, args: Arguments) -> Result {
1023 let mut formatter = Formatter {
1028 align: rt::v1::Alignment::Unknown,
1031 curarg: args.args.iter(),
1034 let mut pieces = args.pieces.iter();
1038 // We can use default formatting parameters for all arguments.
1039 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
1040 formatter.buf.write_str(*piece)?;
1041 (arg.formatter)(arg.value, &mut formatter)?;
1045 // Every spec has a corresponding argument that is preceded by
1047 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
1048 formatter.buf.write_str(*piece)?;
1049 formatter.run(arg)?;
1054 // There can be only one trailing string piece left.
1055 if let Some(piece) = pieces.next() {
1056 formatter.buf.write_str(*piece)?;
1062 impl<'a> Formatter<'a> {
1063 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1064 where 'b: 'c, F: FnOnce(&'b mut (dyn Write+'b)) -> &'c mut (dyn Write+'c)
1067 // We want to change this
1068 buf: wrap(self.buf),
1070 // And preserve these
1075 precision: self.precision,
1077 // These only exist in the struct for the `run` method,
1078 // which won’t be used together with this method.
1079 curarg: self.curarg.clone(),
1084 // First up is the collection of functions used to execute a format string
1085 // at runtime. This consumes all of the compile-time statics generated by
1086 // the format! syntax extension.
1087 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1088 // Fill in the format parameters into the formatter
1089 self.fill = arg.format.fill;
1090 self.align = arg.format.align;
1091 self.flags = arg.format.flags;
1092 self.width = self.getcount(&arg.format.width);
1093 self.precision = self.getcount(&arg.format.precision);
1095 // Extract the correct argument
1096 let value = match arg.position {
1097 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1098 rt::v1::Position::At(i) => self.args[i],
1101 // Then actually do some printing
1102 (value.formatter)(value.value, self)
1105 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1107 rt::v1::Count::Is(n) => Some(n),
1108 rt::v1::Count::Implied => None,
1109 rt::v1::Count::Param(i) => {
1110 self.args[i].as_usize()
1112 rt::v1::Count::NextParam => {
1113 self.curarg.next().and_then(|arg| arg.as_usize())
1118 // Helper methods used for padding and processing formatting arguments that
1119 // all formatting traits can use.
1121 /// Performs the correct padding for an integer which has already been
1122 /// emitted into a str. The str should *not* contain the sign for the
1123 /// integer, that will be added by this method.
1127 /// * is_nonnegative - whether the original integer was either positive or zero.
1128 /// * prefix - if the '#' character (Alternate) is provided, this
1129 /// is the prefix to put in front of the number.
1130 /// * buf - the byte array that the number has been formatted into
1132 /// This function will correctly account for the flags provided as well as
1133 /// the minimum width. It will not take precision into account.
1140 /// struct Foo { nb: i32 };
1143 /// fn new(nb: i32) -> Foo {
1150 /// impl fmt::Display for Foo {
1151 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1152 /// // We need to remove "-" from the number output.
1153 /// let tmp = self.nb.abs().to_string();
1155 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1159 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1160 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1161 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1162 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 pub fn pad_integral(&mut self,
1166 is_nonnegative: bool,
1170 let mut width = buf.len();
1172 let mut sign = None;
1173 if !is_nonnegative {
1174 sign = Some('-'); width += 1;
1175 } else if self.sign_plus() {
1176 sign = Some('+'); width += 1;
1179 let mut prefixed = false;
1180 if self.alternate() {
1181 prefixed = true; width += prefix.chars().count();
1184 // Writes the sign if it exists, and then the prefix if it was requested
1185 let write_prefix = |f: &mut Formatter| {
1186 if let Some(c) = sign {
1187 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
1189 if prefixed { f.buf.write_str(prefix) }
1193 // The `width` field is more of a `min-width` parameter at this point.
1195 // If there's no minimum length requirements then we can just
1198 write_prefix(self)?; self.buf.write_str(buf)
1200 // Check if we're over the minimum width, if so then we can also
1201 // just write the bytes.
1202 Some(min) if width >= min => {
1203 write_prefix(self)?; self.buf.write_str(buf)
1205 // The sign and prefix goes before the padding if the fill character
1207 Some(min) if self.sign_aware_zero_pad() => {
1209 self.align = rt::v1::Alignment::Right;
1210 write_prefix(self)?;
1211 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1212 f.buf.write_str(buf)
1215 // Otherwise, the sign and prefix goes after the padding
1217 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1218 write_prefix(f)?; f.buf.write_str(buf)
1224 /// This function takes a string slice and emits it to the internal buffer
1225 /// after applying the relevant formatting flags specified. The flags
1226 /// recognized for generic strings are:
1228 /// * width - the minimum width of what to emit
1229 /// * fill/align - what to emit and where to emit it if the string
1230 /// provided needs to be padded
1231 /// * precision - the maximum length to emit, the string is truncated if it
1232 /// is longer than this length
1234 /// Notably this function ignores the `flag` parameters.
1243 /// impl fmt::Display for Foo {
1244 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1245 /// formatter.pad("Foo")
1249 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1250 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 pub fn pad(&mut self, s: &str) -> Result {
1254 // Make sure there's a fast path up front
1255 if self.width.is_none() && self.precision.is_none() {
1256 return self.buf.write_str(s);
1258 // The `precision` field can be interpreted as a `max-width` for the
1259 // string being formatted.
1260 let s = if let Some(max) = self.precision {
1261 // If our string is longer that the precision, then we must have
1262 // truncation. However other flags like `fill`, `width` and `align`
1263 // must act as always.
1264 if let Some((i, _)) = s.char_indices().nth(max) {
1265 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1266 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1267 // `unsafe` and otherwise don't emit any panic-related code
1269 s.get(..i).unwrap_or(&s)
1276 // The `width` field is more of a `min-width` parameter at this point.
1278 // If we're under the maximum length, and there's no minimum length
1279 // requirements, then we can just emit the string
1280 None => self.buf.write_str(s),
1281 // If we're under the maximum width, check if we're over the minimum
1282 // width, if so it's as easy as just emitting the string.
1283 Some(width) if s.chars().count() >= width => {
1284 self.buf.write_str(s)
1286 // If we're under both the maximum and the minimum width, then fill
1287 // up the minimum width with the specified string + some alignment.
1289 let align = rt::v1::Alignment::Left;
1290 self.with_padding(width - s.chars().count(), align, |me| {
1297 /// Runs a callback, emitting the correct padding either before or
1298 /// afterwards depending on whether right or left alignment is requested.
1299 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1301 where F: FnOnce(&mut Formatter) -> Result,
1303 let align = match self.align {
1304 rt::v1::Alignment::Unknown => default,
1308 let (pre_pad, post_pad) = match align {
1309 rt::v1::Alignment::Left => (0, padding),
1310 rt::v1::Alignment::Right |
1311 rt::v1::Alignment::Unknown => (padding, 0),
1312 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1315 let mut fill = [0; 4];
1316 let fill = self.fill.encode_utf8(&mut fill);
1318 for _ in 0..pre_pad {
1319 self.buf.write_str(fill)?;
1324 for _ in 0..post_pad {
1325 self.buf.write_str(fill)?;
1331 /// Takes the formatted parts and applies the padding.
1332 /// Assumes that the caller already has rendered the parts with required precision,
1333 /// so that `self.precision` can be ignored.
1334 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1335 if let Some(mut width) = self.width {
1336 // for the sign-aware zero padding, we render the sign first and
1337 // behave as if we had no sign from the beginning.
1338 let mut formatted = formatted.clone();
1339 let old_fill = self.fill;
1340 let old_align = self.align;
1341 let mut align = old_align;
1342 if self.sign_aware_zero_pad() {
1343 // a sign always goes first
1344 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1345 self.buf.write_str(sign)?;
1347 // remove the sign from the formatted parts
1348 formatted.sign = b"";
1349 width = if width < sign.len() { 0 } else { width - sign.len() };
1350 align = rt::v1::Alignment::Right;
1352 self.align = rt::v1::Alignment::Right;
1355 // remaining parts go through the ordinary padding process.
1356 let len = formatted.len();
1357 let ret = if width <= len { // no padding
1358 self.write_formatted_parts(&formatted)
1360 self.with_padding(width - len, align, |f| {
1361 f.write_formatted_parts(&formatted)
1364 self.fill = old_fill;
1365 self.align = old_align;
1368 // this is the common case and we take a shortcut
1369 self.write_formatted_parts(formatted)
1373 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1374 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1375 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1378 if !formatted.sign.is_empty() {
1379 write_bytes(self.buf, formatted.sign)?;
1381 for part in formatted.parts {
1383 flt2dec::Part::Zero(mut nzeroes) => {
1384 const ZEROES: &'static str = // 64 zeroes
1385 "0000000000000000000000000000000000000000000000000000000000000000";
1386 while nzeroes > ZEROES.len() {
1387 self.buf.write_str(ZEROES)?;
1388 nzeroes -= ZEROES.len();
1391 self.buf.write_str(&ZEROES[..nzeroes])?;
1394 flt2dec::Part::Num(mut v) => {
1396 let len = part.len();
1397 for c in s[..len].iter_mut().rev() {
1398 *c = b'0' + (v % 10) as u8;
1401 write_bytes(self.buf, &s[..len])?;
1403 flt2dec::Part::Copy(buf) => {
1404 write_bytes(self.buf, buf)?;
1411 /// Writes some data to the underlying buffer contained within this
1421 /// impl fmt::Display for Foo {
1422 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1423 /// formatter.write_str("Foo")
1424 /// // This is equivalent to:
1425 /// // write!(formatter, "Foo")
1429 /// assert_eq!(&format!("{}", Foo), "Foo");
1430 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 pub fn write_str(&mut self, data: &str) -> Result {
1434 self.buf.write_str(data)
1437 /// Writes some formatted information into this instance.
1444 /// struct Foo(i32);
1446 /// impl fmt::Display for Foo {
1447 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1448 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1452 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1453 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1457 write(self.buf, fmt)
1460 /// Flags for formatting
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 #[rustc_deprecated(since = "1.24.0",
1463 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1464 or `sign_aware_zero_pad` methods instead")]
1465 pub fn flags(&self) -> u32 { self.flags }
1467 /// Character used as 'fill' whenever there is alignment.
1476 /// impl fmt::Display for Foo {
1477 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1478 /// let c = formatter.fill();
1479 /// if let Some(width) = formatter.width() {
1480 /// for _ in 0..width {
1481 /// write!(formatter, "{}", c)?;
1485 /// write!(formatter, "{}", c)
1490 /// // We set alignment to the left with ">".
1491 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1492 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1494 #[stable(feature = "fmt_flags", since = "1.5.0")]
1495 pub fn fill(&self) -> char { self.fill }
1497 /// Flag indicating what form of alignment was requested.
1502 /// extern crate core;
1504 /// use std::fmt::{self, Alignment};
1508 /// impl fmt::Display for Foo {
1509 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1510 /// let s = if let Some(s) = formatter.align() {
1512 /// Alignment::Left => "left",
1513 /// Alignment::Right => "right",
1514 /// Alignment::Center => "center",
1519 /// write!(formatter, "{}", s)
1524 /// assert_eq!(&format!("{:<}", Foo), "left");
1525 /// assert_eq!(&format!("{:>}", Foo), "right");
1526 /// assert_eq!(&format!("{:^}", Foo), "center");
1527 /// assert_eq!(&format!("{}", Foo), "into the void");
1530 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1531 pub fn align(&self) -> Option<Alignment> {
1533 rt::v1::Alignment::Left => Some(Alignment::Left),
1534 rt::v1::Alignment::Right => Some(Alignment::Right),
1535 rt::v1::Alignment::Center => Some(Alignment::Center),
1536 rt::v1::Alignment::Unknown => None,
1540 /// Optionally specified integer width that the output should be.
1547 /// struct Foo(i32);
1549 /// impl fmt::Display for Foo {
1550 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1551 /// if let Some(width) = formatter.width() {
1552 /// // If we received a width, we use it
1553 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1555 /// // Otherwise we do nothing special
1556 /// write!(formatter, "Foo({})", self.0)
1561 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1562 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1564 #[stable(feature = "fmt_flags", since = "1.5.0")]
1565 pub fn width(&self) -> Option<usize> { self.width }
1567 /// Optionally specified precision for numeric types.
1574 /// struct Foo(f32);
1576 /// impl fmt::Display for Foo {
1577 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1578 /// if let Some(precision) = formatter.precision() {
1579 /// // If we received a precision, we use it.
1580 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1582 /// // Otherwise we default to 2.
1583 /// write!(formatter, "Foo({:.2})", self.0)
1588 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1589 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1591 #[stable(feature = "fmt_flags", since = "1.5.0")]
1592 pub fn precision(&self) -> Option<usize> { self.precision }
1594 /// Determines if the `+` flag was specified.
1601 /// struct Foo(i32);
1603 /// impl fmt::Display for Foo {
1604 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1605 /// if formatter.sign_plus() {
1606 /// write!(formatter,
1608 /// if self.0 < 0 { '-' } else { '+' },
1611 /// write!(formatter, "Foo({})", self.0)
1616 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1617 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1619 #[stable(feature = "fmt_flags", since = "1.5.0")]
1620 pub fn sign_plus(&self) -> bool {
1621 self.flags & (1 << FlagV1::SignPlus as u32) != 0
1624 /// Determines if the `-` flag was specified.
1631 /// struct Foo(i32);
1633 /// impl fmt::Display for Foo {
1634 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1635 /// if formatter.sign_minus() {
1636 /// // You want a minus sign? Have one!
1637 /// write!(formatter, "-Foo({})", self.0)
1639 /// write!(formatter, "Foo({})", self.0)
1644 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1645 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1647 #[stable(feature = "fmt_flags", since = "1.5.0")]
1648 pub fn sign_minus(&self) -> bool {
1649 self.flags & (1 << FlagV1::SignMinus as u32) != 0
1652 /// Determines if the `#` flag was specified.
1659 /// struct Foo(i32);
1661 /// impl fmt::Display for Foo {
1662 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1663 /// if formatter.alternate() {
1664 /// write!(formatter, "Foo({})", self.0)
1666 /// write!(formatter, "{}", self.0)
1671 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1672 /// assert_eq!(&format!("{}", Foo(23)), "23");
1674 #[stable(feature = "fmt_flags", since = "1.5.0")]
1675 pub fn alternate(&self) -> bool {
1676 self.flags & (1 << FlagV1::Alternate as u32) != 0
1679 /// Determines if the `0` flag was specified.
1686 /// struct Foo(i32);
1688 /// impl fmt::Display for Foo {
1689 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1690 /// assert!(formatter.sign_aware_zero_pad());
1691 /// assert_eq!(formatter.width(), Some(4));
1692 /// // We ignore the formatter's options.
1693 /// write!(formatter, "{}", self.0)
1697 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1699 #[stable(feature = "fmt_flags", since = "1.5.0")]
1700 pub fn sign_aware_zero_pad(&self) -> bool {
1701 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1704 // FIXME: Decide what public API we want for these two flags.
1705 // https://github.com/rust-lang/rust/issues/48584
1706 const fn debug_lower_hex(&self) -> bool {
1707 self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1710 const fn debug_upper_hex(&self) -> bool {
1711 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1714 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1715 /// [`fmt::Debug`] implementations for structs.
1717 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1718 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1724 /// use std::net::Ipv4Addr;
1732 /// impl fmt::Debug for Foo {
1733 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1734 /// fmt.debug_struct("Foo")
1735 /// .field("bar", &self.bar)
1736 /// .field("baz", &self.baz)
1737 /// .field("addr", &format_args!("{}", self.addr))
1743 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1744 /// format!("{:?}", Foo {
1746 /// baz: "Hello World".to_string(),
1747 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1751 #[stable(feature = "debug_builders", since = "1.2.0")]
1752 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1753 builders::debug_struct_new(self, name)
1756 /// Creates a `DebugTuple` builder designed to assist with creation of
1757 /// `fmt::Debug` implementations for tuple structs.
1763 /// use std::marker::PhantomData;
1765 /// struct Foo<T>(i32, String, PhantomData<T>);
1767 /// impl<T> fmt::Debug for Foo<T> {
1768 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1769 /// fmt.debug_tuple("Foo")
1772 /// .field(&format_args!("_"))
1778 /// "Foo(10, \"Hello\", _)",
1779 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1782 #[stable(feature = "debug_builders", since = "1.2.0")]
1783 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1784 builders::debug_tuple_new(self, name)
1787 /// Creates a `DebugList` builder designed to assist with creation of
1788 /// `fmt::Debug` implementations for list-like structures.
1795 /// struct Foo(Vec<i32>);
1797 /// impl fmt::Debug for Foo {
1798 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1799 /// fmt.debug_list().entries(self.0.iter()).finish()
1803 /// // prints "[10, 11]"
1804 /// println!("{:?}", Foo(vec![10, 11]));
1806 #[stable(feature = "debug_builders", since = "1.2.0")]
1807 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1808 builders::debug_list_new(self)
1811 /// Creates a `DebugSet` builder designed to assist with creation of
1812 /// `fmt::Debug` implementations for set-like structures.
1819 /// struct Foo(Vec<i32>);
1821 /// impl fmt::Debug for Foo {
1822 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1823 /// fmt.debug_set().entries(self.0.iter()).finish()
1827 /// // prints "{10, 11}"
1828 /// println!("{:?}", Foo(vec![10, 11]));
1831 /// [`format_args!`]: ../../std/macro.format_args.html
1833 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1834 /// to build a list of match arms:
1839 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1840 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1842 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1844 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1846 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1847 /// L::fmt(&(self.0).0, fmt)?;
1848 /// fmt.write_str(" => ")?;
1849 /// R::fmt(&(self.0).1, fmt)
1853 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1855 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1857 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1859 /// .entries(self.0.iter().map(Arm))
1860 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1865 #[stable(feature = "debug_builders", since = "1.2.0")]
1866 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1867 builders::debug_set_new(self)
1870 /// Creates a `DebugMap` builder designed to assist with creation of
1871 /// `fmt::Debug` implementations for map-like structures.
1878 /// struct Foo(Vec<(String, i32)>);
1880 /// impl fmt::Debug for Foo {
1881 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1882 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1886 /// // prints "{"A": 10, "B": 11}"
1887 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1889 #[stable(feature = "debug_builders", since = "1.2.0")]
1890 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1891 builders::debug_map_new(self)
1895 #[stable(since = "1.2.0", feature = "formatter_write")]
1896 impl Write for Formatter<'_> {
1897 fn write_str(&mut self, s: &str) -> Result {
1898 self.buf.write_str(s)
1901 fn write_char(&mut self, c: char) -> Result {
1902 self.buf.write_char(c)
1905 fn write_fmt(&mut self, args: Arguments) -> Result {
1906 write(self.buf, args)
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 impl Display for Error {
1912 fn fmt(&self, f: &mut Formatter) -> Result {
1913 Display::fmt("an error occurred when formatting an argument", f)
1917 // Implementations of the core formatting traits
1919 macro_rules! fmt_refs {
1920 ($($tr:ident),*) => {
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 impl<T: ?Sized + $tr> $tr for &T {
1924 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 impl<T: ?Sized + $tr> $tr for &mut T {
1928 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1934 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1936 #[unstable(feature = "never_type", issue = "35121")]
1938 fn fmt(&self, _: &mut Formatter) -> Result {
1943 #[unstable(feature = "never_type", issue = "35121")]
1944 impl Display for ! {
1945 fn fmt(&self, _: &mut Formatter) -> Result {
1950 #[stable(feature = "rust1", since = "1.0.0")]
1951 impl Debug for bool {
1953 fn fmt(&self, f: &mut Formatter) -> Result {
1954 Display::fmt(self, f)
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 impl Display for bool {
1960 fn fmt(&self, f: &mut Formatter) -> Result {
1961 Display::fmt(if *self { "true" } else { "false" }, f)
1965 #[stable(feature = "rust1", since = "1.0.0")]
1966 impl Debug for str {
1967 fn fmt(&self, f: &mut Formatter) -> Result {
1970 for (i, c) in self.char_indices() {
1971 let esc = c.escape_debug();
1972 // If char needs escaping, flush backlog so far and write, else skip
1974 f.write_str(&self[from..i])?;
1978 from = i + c.len_utf8();
1981 f.write_str(&self[from..])?;
1986 #[stable(feature = "rust1", since = "1.0.0")]
1987 impl Display for str {
1988 fn fmt(&self, f: &mut Formatter) -> Result {
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 impl Debug for char {
1995 fn fmt(&self, f: &mut Formatter) -> Result {
1996 f.write_char('\'')?;
1997 for c in self.escape_debug() {
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 impl Display for char {
2006 fn fmt(&self, f: &mut Formatter) -> Result {
2007 if f.width.is_none() && f.precision.is_none() {
2010 f.pad(self.encode_utf8(&mut [0; 4]))
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 impl<T: ?Sized> Pointer for *const T {
2017 fn fmt(&self, f: &mut Formatter) -> Result {
2018 let old_width = f.width;
2019 let old_flags = f.flags;
2021 // The alternate flag is already treated by LowerHex as being special-
2022 // it denotes whether to prefix with 0x. We use it to work out whether
2023 // or not to zero extend, and then unconditionally set it to get the
2026 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2028 if let None = f.width {
2029 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2032 f.flags |= 1 << (FlagV1::Alternate as u32);
2034 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2036 f.width = old_width;
2037 f.flags = old_flags;
2043 #[stable(feature = "rust1", since = "1.0.0")]
2044 impl<T: ?Sized> Pointer for *mut T {
2045 fn fmt(&self, f: &mut Formatter) -> Result {
2046 Pointer::fmt(&(*self as *const T), f)
2050 #[stable(feature = "rust1", since = "1.0.0")]
2051 impl<T: ?Sized> Pointer for &T {
2052 fn fmt(&self, f: &mut Formatter) -> Result {
2053 Pointer::fmt(&(*self as *const T), f)
2057 #[stable(feature = "rust1", since = "1.0.0")]
2058 impl<T: ?Sized> Pointer for &mut T {
2059 fn fmt(&self, f: &mut Formatter) -> Result {
2060 Pointer::fmt(&(&**self as *const T), f)
2064 // Implementation of Display/Debug for various core types
2066 #[stable(feature = "rust1", since = "1.0.0")]
2067 impl<T: ?Sized> Debug for *const T {
2068 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2070 #[stable(feature = "rust1", since = "1.0.0")]
2071 impl<T: ?Sized> Debug for *mut T {
2072 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2076 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2079 macro_rules! tuple {
2081 ( $($name:ident,)+ ) => (
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
2084 #[allow(non_snake_case, unused_assignments, deprecated)]
2085 fn fmt(&self, f: &mut Formatter) -> Result {
2086 let mut builder = f.debug_tuple("");
2087 let ($(ref $name,)*) = *self;
2089 builder.field(&$name);
2095 peel! { $($name,)* }
2099 macro_rules! last_type {
2100 ($a:ident,) => { $a };
2101 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2104 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 impl<T: Debug> Debug for [T] {
2108 fn fmt(&self, f: &mut Formatter) -> Result {
2109 f.debug_list().entries(self.iter()).finish()
2113 #[stable(feature = "rust1", since = "1.0.0")]
2116 fn fmt(&self, f: &mut Formatter) -> Result {
2120 #[stable(feature = "rust1", since = "1.0.0")]
2121 impl<T: ?Sized> Debug for PhantomData<T> {
2122 fn fmt(&self, f: &mut Formatter) -> Result {
2123 f.pad("PhantomData")
2127 #[stable(feature = "rust1", since = "1.0.0")]
2128 impl<T: Copy + Debug> Debug for Cell<T> {
2129 fn fmt(&self, f: &mut Formatter) -> Result {
2130 f.debug_struct("Cell")
2131 .field("value", &self.get())
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2138 fn fmt(&self, f: &mut Formatter) -> Result {
2139 match self.try_borrow() {
2141 f.debug_struct("RefCell")
2142 .field("value", &borrow)
2146 // The RefCell is mutably borrowed so we can't look at its value
2147 // here. Show a placeholder instead.
2148 struct BorrowedPlaceholder;
2150 impl Debug for BorrowedPlaceholder {
2151 fn fmt(&self, f: &mut Formatter) -> Result {
2152 f.write_str("<borrowed>")
2156 f.debug_struct("RefCell")
2157 .field("value", &BorrowedPlaceholder)
2164 #[stable(feature = "rust1", since = "1.0.0")]
2165 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2166 fn fmt(&self, f: &mut Formatter) -> Result {
2167 Debug::fmt(&**self, f)
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2173 fn fmt(&self, f: &mut Formatter) -> Result {
2174 Debug::fmt(&*(self.deref()), f)
2178 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2179 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2180 fn fmt(&self, f: &mut Formatter) -> Result {
2185 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
2186 // it's a lot easier than creating all of the rt::Piece structures here.