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(
613 _Self="std::path::Path",
614 label="`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
615 note="call `.display()` or `.to_string_lossy()` to safely print paths, \
616 as they may contain non-Unicode data"
618 message="`{Self}` doesn't implement `{Display}`",
619 label="`{Self}` cannot be formatted with the default formatter",
620 note="in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead",
623 #[stable(feature = "rust1", since = "1.0.0")]
625 /// Formats the value using the given formatter.
632 /// struct Position {
637 /// impl fmt::Display for Position {
638 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
639 /// write!(f, "({}, {})", self.longitude, self.latitude)
643 /// assert_eq!("(1.987, 2.983)".to_owned(),
644 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
646 #[stable(feature = "rust1", since = "1.0.0")]
647 fn fmt(&self, f: &mut Formatter) -> Result;
652 /// The `Octal` trait should format its output as a number in base-8.
654 /// For primitive signed integers (`i8` to `i128`, and `isize`),
655 /// negative values are formatted as the two’s complement representation.
657 /// The alternate flag, `#`, adds a `0o` in front of the output.
659 /// For more information on formatters, see [the module-level documentation][module].
661 /// [module]: ../../std/fmt/index.html
665 /// Basic usage with `i32`:
668 /// let x = 42; // 42 is '52' in octal
670 /// assert_eq!(format!("{:o}", x), "52");
671 /// assert_eq!(format!("{:#o}", x), "0o52");
673 /// assert_eq!(format!("{:o}", -16), "37777777760");
676 /// Implementing `Octal` on a type:
681 /// struct Length(i32);
683 /// impl fmt::Octal for Length {
684 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
685 /// let val = self.0;
687 /// write!(f, "{:o}", val) // delegate to i32's implementation
691 /// let l = Length(9);
693 /// println!("l as octal is: {:o}", l);
695 #[stable(feature = "rust1", since = "1.0.0")]
697 /// Formats the value using the given formatter.
698 #[stable(feature = "rust1", since = "1.0.0")]
699 fn fmt(&self, f: &mut Formatter) -> Result;
704 /// The `Binary` trait should format its output as a number in binary.
706 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
707 /// negative values are formatted as the two’s complement representation.
709 /// The alternate flag, `#`, adds a `0b` in front of the output.
711 /// For more information on formatters, see [the module-level documentation][module].
715 /// Basic usage with [`i32`]:
718 /// let x = 42; // 42 is '101010' in binary
720 /// assert_eq!(format!("{:b}", x), "101010");
721 /// assert_eq!(format!("{:#b}", x), "0b101010");
723 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
726 /// Implementing `Binary` on a type:
731 /// struct Length(i32);
733 /// impl fmt::Binary for Length {
734 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
735 /// let val = self.0;
737 /// write!(f, "{:b}", val) // delegate to i32's implementation
741 /// let l = Length(107);
743 /// println!("l as binary is: {:b}", l);
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 /// write!(f, "{:x}", val) // delegate to i32's implementation
800 /// let l = Length(9);
802 /// println!("l as hex is: {:x}", l);
804 #[stable(feature = "rust1", since = "1.0.0")]
806 /// Formats the value using the given formatter.
807 #[stable(feature = "rust1", since = "1.0.0")]
808 fn fmt(&self, f: &mut Formatter) -> Result;
813 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
816 /// For primitive signed integers (`i8` to `i128`, and `isize`),
817 /// negative values are formatted as the two’s complement representation.
819 /// The alternate flag, `#`, adds a `0x` in front of the output.
821 /// For more information on formatters, see [the module-level documentation][module].
823 /// [module]: ../../std/fmt/index.html
827 /// Basic usage with `i32`:
830 /// let x = 42; // 42 is '2A' in hex
832 /// assert_eq!(format!("{:X}", x), "2A");
833 /// assert_eq!(format!("{:#X}", x), "0x2A");
835 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
838 /// Implementing `UpperHex` on a type:
843 /// struct Length(i32);
845 /// impl fmt::UpperHex for Length {
846 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
847 /// let val = self.0;
849 /// write!(f, "{:X}", val) // delegate to i32's implementation
853 /// let l = Length(9);
855 /// println!("l as hex is: {:X}", l);
857 #[stable(feature = "rust1", since = "1.0.0")]
859 /// Formats the value using the given formatter.
860 #[stable(feature = "rust1", since = "1.0.0")]
861 fn fmt(&self, f: &mut Formatter) -> Result;
866 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
869 /// For more information on formatters, see [the module-level documentation][module].
871 /// [module]: ../../std/fmt/index.html
875 /// Basic usage with `&i32`:
880 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
883 /// Implementing `Pointer` on a type:
888 /// struct Length(i32);
890 /// impl fmt::Pointer for Length {
891 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
892 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
894 /// write!(f, "{:p}", self as *const Length)
898 /// let l = Length(42);
900 /// println!("l is in memory here: {:p}", l);
902 #[stable(feature = "rust1", since = "1.0.0")]
904 /// Formats the value using the given formatter.
905 #[stable(feature = "rust1", since = "1.0.0")]
906 fn fmt(&self, f: &mut Formatter) -> Result;
911 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
913 /// For more information on formatters, see [the module-level documentation][module].
915 /// [module]: ../../std/fmt/index.html
919 /// Basic usage with `i32`:
922 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
924 /// assert_eq!(format!("{:e}", x), "4.2e1");
927 /// Implementing `LowerExp` on a type:
932 /// struct Length(i32);
934 /// impl fmt::LowerExp for Length {
935 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
936 /// let val = self.0;
937 /// write!(f, "{}e1", val / 10)
941 /// let l = Length(100);
943 /// println!("l in scientific notation is: {:e}", l);
945 #[stable(feature = "rust1", since = "1.0.0")]
947 /// Formats the value using the given formatter.
948 #[stable(feature = "rust1", since = "1.0.0")]
949 fn fmt(&self, f: &mut Formatter) -> Result;
954 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
956 /// For more information on formatters, see [the module-level documentation][module].
958 /// [module]: ../../std/fmt/index.html
962 /// Basic usage with `f32`:
965 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
967 /// assert_eq!(format!("{:E}", x), "4.2E1");
970 /// Implementing `UpperExp` on a type:
975 /// struct Length(i32);
977 /// impl fmt::UpperExp for Length {
978 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
979 /// let val = self.0;
980 /// write!(f, "{}E1", val / 10)
984 /// let l = Length(100);
986 /// println!("l in scientific notation is: {:E}", l);
988 #[stable(feature = "rust1", since = "1.0.0")]
990 /// Formats the value using the given formatter.
991 #[stable(feature = "rust1", since = "1.0.0")]
992 fn fmt(&self, f: &mut Formatter) -> Result;
995 /// The `write` function takes an output stream, and an `Arguments` struct
996 /// that can be precompiled with the `format_args!` macro.
998 /// The arguments will be formatted according to the specified format string
999 /// into the output stream provided.
1008 /// let mut output = String::new();
1009 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1010 /// .expect("Error occurred while trying to write in String");
1011 /// assert_eq!(output, "Hello world!");
1014 /// Please note that using [`write!`] might be preferable. Example:
1017 /// use std::fmt::Write;
1019 /// let mut output = String::new();
1020 /// write!(&mut output, "Hello {}!", "world")
1021 /// .expect("Error occurred while trying to write in String");
1022 /// assert_eq!(output, "Hello world!");
1025 /// [`write!`]: ../../std/macro.write.html
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 pub fn write(output: &mut dyn Write, args: Arguments) -> Result {
1028 let mut formatter = Formatter {
1033 align: rt::v1::Alignment::Unknown,
1036 curarg: args.args.iter(),
1039 let mut pieces = args.pieces.iter();
1043 // We can use default formatting parameters for all arguments.
1044 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
1045 formatter.buf.write_str(*piece)?;
1046 (arg.formatter)(arg.value, &mut formatter)?;
1050 // Every spec has a corresponding argument that is preceded by
1052 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
1053 formatter.buf.write_str(*piece)?;
1054 formatter.run(arg)?;
1059 // There can be only one trailing string piece left.
1060 if let Some(piece) = pieces.next() {
1061 formatter.buf.write_str(*piece)?;
1067 impl<'a> Formatter<'a> {
1068 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1069 where 'b: 'c, F: FnOnce(&'b mut (dyn Write+'b)) -> &'c mut (dyn Write+'c)
1072 // We want to change this
1073 buf: wrap(self.buf),
1075 // And preserve these
1080 precision: self.precision,
1082 // These only exist in the struct for the `run` method,
1083 // which won’t be used together with this method.
1084 curarg: self.curarg.clone(),
1089 // First up is the collection of functions used to execute a format string
1090 // at runtime. This consumes all of the compile-time statics generated by
1091 // the format! syntax extension.
1092 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1093 // Fill in the format parameters into the formatter
1094 self.fill = arg.format.fill;
1095 self.align = arg.format.align;
1096 self.flags = arg.format.flags;
1097 self.width = self.getcount(&arg.format.width);
1098 self.precision = self.getcount(&arg.format.precision);
1100 // Extract the correct argument
1101 let value = match arg.position {
1102 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1103 rt::v1::Position::At(i) => self.args[i],
1106 // Then actually do some printing
1107 (value.formatter)(value.value, self)
1110 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1112 rt::v1::Count::Is(n) => Some(n),
1113 rt::v1::Count::Implied => None,
1114 rt::v1::Count::Param(i) => {
1115 self.args[i].as_usize()
1117 rt::v1::Count::NextParam => {
1118 self.curarg.next().and_then(|arg| arg.as_usize())
1123 // Helper methods used for padding and processing formatting arguments that
1124 // all formatting traits can use.
1126 /// Performs the correct padding for an integer which has already been
1127 /// emitted into a str. The str should *not* contain the sign for the
1128 /// integer, that will be added by this method.
1132 /// * is_nonnegative - whether the original integer was either positive or zero.
1133 /// * prefix - if the '#' character (Alternate) is provided, this
1134 /// is the prefix to put in front of the number.
1135 /// * buf - the byte array that the number has been formatted into
1137 /// This function will correctly account for the flags provided as well as
1138 /// the minimum width. It will not take precision into account.
1145 /// struct Foo { nb: i32 };
1148 /// fn new(nb: i32) -> Foo {
1155 /// impl fmt::Display for Foo {
1156 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1157 /// // We need to remove "-" from the number output.
1158 /// let tmp = self.nb.abs().to_string();
1160 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1164 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1165 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1166 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1167 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 pub fn pad_integral(&mut self,
1171 is_nonnegative: bool,
1175 let mut width = buf.len();
1177 let mut sign = None;
1178 if !is_nonnegative {
1179 sign = Some('-'); width += 1;
1180 } else if self.sign_plus() {
1181 sign = Some('+'); width += 1;
1184 let mut prefixed = false;
1185 if self.alternate() {
1186 prefixed = true; width += prefix.chars().count();
1189 // Writes the sign if it exists, and then the prefix if it was requested
1190 let write_prefix = |f: &mut Formatter| {
1191 if let Some(c) = sign {
1192 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
1194 if prefixed { f.buf.write_str(prefix) }
1198 // The `width` field is more of a `min-width` parameter at this point.
1200 // If there's no minimum length requirements then we can just
1203 write_prefix(self)?; self.buf.write_str(buf)
1205 // Check if we're over the minimum width, if so then we can also
1206 // just write the bytes.
1207 Some(min) if width >= min => {
1208 write_prefix(self)?; self.buf.write_str(buf)
1210 // The sign and prefix goes before the padding if the fill character
1212 Some(min) if self.sign_aware_zero_pad() => {
1214 self.align = rt::v1::Alignment::Right;
1215 write_prefix(self)?;
1216 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1217 f.buf.write_str(buf)
1220 // Otherwise, the sign and prefix goes after the padding
1222 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1223 write_prefix(f)?; f.buf.write_str(buf)
1229 /// This function takes a string slice and emits it to the internal buffer
1230 /// after applying the relevant formatting flags specified. The flags
1231 /// recognized for generic strings are:
1233 /// * width - the minimum width of what to emit
1234 /// * fill/align - what to emit and where to emit it if the string
1235 /// provided needs to be padded
1236 /// * precision - the maximum length to emit, the string is truncated if it
1237 /// is longer than this length
1239 /// Notably this function ignores the `flag` parameters.
1248 /// impl fmt::Display for Foo {
1249 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1250 /// formatter.pad("Foo")
1254 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1255 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 pub fn pad(&mut self, s: &str) -> Result {
1259 // Make sure there's a fast path up front
1260 if self.width.is_none() && self.precision.is_none() {
1261 return self.buf.write_str(s);
1263 // The `precision` field can be interpreted as a `max-width` for the
1264 // string being formatted.
1265 let s = if let Some(max) = self.precision {
1266 // If our string is longer that the precision, then we must have
1267 // truncation. However other flags like `fill`, `width` and `align`
1268 // must act as always.
1269 if let Some((i, _)) = s.char_indices().nth(max) {
1270 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1271 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1272 // `unsafe` and otherwise don't emit any panic-related code
1274 s.get(..i).unwrap_or(&s)
1281 // The `width` field is more of a `min-width` parameter at this point.
1283 // If we're under the maximum length, and there's no minimum length
1284 // requirements, then we can just emit the string
1285 None => self.buf.write_str(s),
1286 // If we're under the maximum width, check if we're over the minimum
1287 // width, if so it's as easy as just emitting the string.
1288 Some(width) if s.chars().count() >= width => {
1289 self.buf.write_str(s)
1291 // If we're under both the maximum and the minimum width, then fill
1292 // up the minimum width with the specified string + some alignment.
1294 let align = rt::v1::Alignment::Left;
1295 self.with_padding(width - s.chars().count(), align, |me| {
1302 /// Runs a callback, emitting the correct padding either before or
1303 /// afterwards depending on whether right or left alignment is requested.
1304 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1306 where F: FnOnce(&mut Formatter) -> Result,
1308 let align = match self.align {
1309 rt::v1::Alignment::Unknown => default,
1313 let (pre_pad, post_pad) = match align {
1314 rt::v1::Alignment::Left => (0, padding),
1315 rt::v1::Alignment::Right |
1316 rt::v1::Alignment::Unknown => (padding, 0),
1317 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1320 let mut fill = [0; 4];
1321 let fill = self.fill.encode_utf8(&mut fill);
1323 for _ in 0..pre_pad {
1324 self.buf.write_str(fill)?;
1329 for _ in 0..post_pad {
1330 self.buf.write_str(fill)?;
1336 /// Takes the formatted parts and applies the padding.
1337 /// Assumes that the caller already has rendered the parts with required precision,
1338 /// so that `self.precision` can be ignored.
1339 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1340 if let Some(mut width) = self.width {
1341 // for the sign-aware zero padding, we render the sign first and
1342 // behave as if we had no sign from the beginning.
1343 let mut formatted = formatted.clone();
1344 let old_fill = self.fill;
1345 let old_align = self.align;
1346 let mut align = old_align;
1347 if self.sign_aware_zero_pad() {
1348 // a sign always goes first
1349 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1350 self.buf.write_str(sign)?;
1352 // remove the sign from the formatted parts
1353 formatted.sign = b"";
1354 width = if width < sign.len() { 0 } else { width - sign.len() };
1355 align = rt::v1::Alignment::Right;
1357 self.align = rt::v1::Alignment::Right;
1360 // remaining parts go through the ordinary padding process.
1361 let len = formatted.len();
1362 let ret = if width <= len { // no padding
1363 self.write_formatted_parts(&formatted)
1365 self.with_padding(width - len, align, |f| {
1366 f.write_formatted_parts(&formatted)
1369 self.fill = old_fill;
1370 self.align = old_align;
1373 // this is the common case and we take a shortcut
1374 self.write_formatted_parts(formatted)
1378 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1379 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1380 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1383 if !formatted.sign.is_empty() {
1384 write_bytes(self.buf, formatted.sign)?;
1386 for part in formatted.parts {
1388 flt2dec::Part::Zero(mut nzeroes) => {
1389 const ZEROES: &str = // 64 zeroes
1390 "0000000000000000000000000000000000000000000000000000000000000000";
1391 while nzeroes > ZEROES.len() {
1392 self.buf.write_str(ZEROES)?;
1393 nzeroes -= ZEROES.len();
1396 self.buf.write_str(&ZEROES[..nzeroes])?;
1399 flt2dec::Part::Num(mut v) => {
1401 let len = part.len();
1402 for c in s[..len].iter_mut().rev() {
1403 *c = b'0' + (v % 10) as u8;
1406 write_bytes(self.buf, &s[..len])?;
1408 flt2dec::Part::Copy(buf) => {
1409 write_bytes(self.buf, buf)?;
1416 /// Writes some data to the underlying buffer contained within this
1426 /// impl fmt::Display for Foo {
1427 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1428 /// formatter.write_str("Foo")
1429 /// // This is equivalent to:
1430 /// // write!(formatter, "Foo")
1434 /// assert_eq!(&format!("{}", Foo), "Foo");
1435 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 pub fn write_str(&mut self, data: &str) -> Result {
1439 self.buf.write_str(data)
1442 /// Writes some formatted information into this instance.
1449 /// struct Foo(i32);
1451 /// impl fmt::Display for Foo {
1452 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1453 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1457 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1458 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1462 write(self.buf, fmt)
1465 /// Flags for formatting
1466 #[stable(feature = "rust1", since = "1.0.0")]
1467 #[rustc_deprecated(since = "1.24.0",
1468 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1469 or `sign_aware_zero_pad` methods instead")]
1470 pub fn flags(&self) -> u32 { self.flags }
1472 /// Character used as 'fill' whenever there is alignment.
1481 /// impl fmt::Display for Foo {
1482 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1483 /// let c = formatter.fill();
1484 /// if let Some(width) = formatter.width() {
1485 /// for _ in 0..width {
1486 /// write!(formatter, "{}", c)?;
1490 /// write!(formatter, "{}", c)
1495 /// // We set alignment to the left with ">".
1496 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1497 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1499 #[stable(feature = "fmt_flags", since = "1.5.0")]
1500 pub fn fill(&self) -> char { self.fill }
1502 /// Flag indicating what form of alignment was requested.
1507 /// extern crate core;
1509 /// use std::fmt::{self, Alignment};
1513 /// impl fmt::Display for Foo {
1514 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1515 /// let s = if let Some(s) = formatter.align() {
1517 /// Alignment::Left => "left",
1518 /// Alignment::Right => "right",
1519 /// Alignment::Center => "center",
1524 /// write!(formatter, "{}", s)
1529 /// assert_eq!(&format!("{:<}", Foo), "left");
1530 /// assert_eq!(&format!("{:>}", Foo), "right");
1531 /// assert_eq!(&format!("{:^}", Foo), "center");
1532 /// assert_eq!(&format!("{}", Foo), "into the void");
1535 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1536 pub fn align(&self) -> Option<Alignment> {
1538 rt::v1::Alignment::Left => Some(Alignment::Left),
1539 rt::v1::Alignment::Right => Some(Alignment::Right),
1540 rt::v1::Alignment::Center => Some(Alignment::Center),
1541 rt::v1::Alignment::Unknown => None,
1545 /// Optionally specified integer width that the output should be.
1552 /// struct Foo(i32);
1554 /// impl fmt::Display for Foo {
1555 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1556 /// if let Some(width) = formatter.width() {
1557 /// // If we received a width, we use it
1558 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1560 /// // Otherwise we do nothing special
1561 /// write!(formatter, "Foo({})", self.0)
1566 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1567 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1569 #[stable(feature = "fmt_flags", since = "1.5.0")]
1570 pub fn width(&self) -> Option<usize> { self.width }
1572 /// Optionally specified precision for numeric types.
1579 /// struct Foo(f32);
1581 /// impl fmt::Display for Foo {
1582 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1583 /// if let Some(precision) = formatter.precision() {
1584 /// // If we received a precision, we use it.
1585 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1587 /// // Otherwise we default to 2.
1588 /// write!(formatter, "Foo({:.2})", self.0)
1593 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1594 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1596 #[stable(feature = "fmt_flags", since = "1.5.0")]
1597 pub fn precision(&self) -> Option<usize> { self.precision }
1599 /// Determines if the `+` flag was specified.
1606 /// struct Foo(i32);
1608 /// impl fmt::Display for Foo {
1609 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1610 /// if formatter.sign_plus() {
1611 /// write!(formatter,
1613 /// if self.0 < 0 { '-' } else { '+' },
1616 /// write!(formatter, "Foo({})", self.0)
1621 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1622 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1624 #[stable(feature = "fmt_flags", since = "1.5.0")]
1625 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1627 /// Determines if the `-` flag was specified.
1634 /// struct Foo(i32);
1636 /// impl fmt::Display for Foo {
1637 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1638 /// if formatter.sign_minus() {
1639 /// // You want a minus sign? Have one!
1640 /// write!(formatter, "-Foo({})", self.0)
1642 /// write!(formatter, "Foo({})", self.0)
1647 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1648 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1650 #[stable(feature = "fmt_flags", since = "1.5.0")]
1651 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1653 /// Determines if the `#` flag was specified.
1660 /// struct Foo(i32);
1662 /// impl fmt::Display for Foo {
1663 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1664 /// if formatter.alternate() {
1665 /// write!(formatter, "Foo({})", self.0)
1667 /// write!(formatter, "{}", self.0)
1672 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1673 /// assert_eq!(&format!("{}", Foo(23)), "23");
1675 #[stable(feature = "fmt_flags", since = "1.5.0")]
1676 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1678 /// Determines if the `0` flag was specified.
1685 /// struct Foo(i32);
1687 /// impl fmt::Display for Foo {
1688 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1689 /// assert!(formatter.sign_aware_zero_pad());
1690 /// assert_eq!(formatter.width(), Some(4));
1691 /// // We ignore the formatter's options.
1692 /// write!(formatter, "{}", self.0)
1696 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1698 #[stable(feature = "fmt_flags", since = "1.5.0")]
1699 pub fn sign_aware_zero_pad(&self) -> bool {
1700 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1703 // FIXME: Decide what public API we want for these two flags.
1704 // https://github.com/rust-lang/rust/issues/48584
1705 fn debug_lower_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0 }
1707 fn debug_upper_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0 }
1709 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1710 /// [`fmt::Debug`] implementations for structs.
1712 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1713 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1719 /// use std::net::Ipv4Addr;
1727 /// impl fmt::Debug for Foo {
1728 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1729 /// fmt.debug_struct("Foo")
1730 /// .field("bar", &self.bar)
1731 /// .field("baz", &self.baz)
1732 /// .field("addr", &format_args!("{}", self.addr))
1738 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1739 /// format!("{:?}", Foo {
1741 /// baz: "Hello World".to_string(),
1742 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1746 #[stable(feature = "debug_builders", since = "1.2.0")]
1747 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1748 builders::debug_struct_new(self, name)
1751 /// Creates a `DebugTuple` builder designed to assist with creation of
1752 /// `fmt::Debug` implementations for tuple structs.
1758 /// use std::marker::PhantomData;
1760 /// struct Foo<T>(i32, String, PhantomData<T>);
1762 /// impl<T> fmt::Debug for Foo<T> {
1763 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1764 /// fmt.debug_tuple("Foo")
1767 /// .field(&format_args!("_"))
1773 /// "Foo(10, \"Hello\", _)",
1774 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1777 #[stable(feature = "debug_builders", since = "1.2.0")]
1778 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1779 builders::debug_tuple_new(self, name)
1782 /// Creates a `DebugList` builder designed to assist with creation of
1783 /// `fmt::Debug` implementations for list-like structures.
1790 /// struct Foo(Vec<i32>);
1792 /// impl fmt::Debug for Foo {
1793 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1794 /// fmt.debug_list().entries(self.0.iter()).finish()
1798 /// // prints "[10, 11]"
1799 /// println!("{:?}", Foo(vec![10, 11]));
1801 #[stable(feature = "debug_builders", since = "1.2.0")]
1802 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1803 builders::debug_list_new(self)
1806 /// Creates a `DebugSet` builder designed to assist with creation of
1807 /// `fmt::Debug` implementations for set-like structures.
1814 /// struct Foo(Vec<i32>);
1816 /// impl fmt::Debug for Foo {
1817 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1818 /// fmt.debug_set().entries(self.0.iter()).finish()
1822 /// // prints "{10, 11}"
1823 /// println!("{:?}", Foo(vec![10, 11]));
1826 /// [`format_args!`]: ../../std/macro.format_args.html
1828 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1829 /// to build a list of match arms:
1834 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1835 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1837 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1839 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1841 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1842 /// L::fmt(&(self.0).0, fmt)?;
1843 /// fmt.write_str(" => ")?;
1844 /// R::fmt(&(self.0).1, fmt)
1848 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1850 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1852 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1854 /// .entries(self.0.iter().map(Arm))
1855 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1860 #[stable(feature = "debug_builders", since = "1.2.0")]
1861 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1862 builders::debug_set_new(self)
1865 /// Creates a `DebugMap` builder designed to assist with creation of
1866 /// `fmt::Debug` implementations for map-like structures.
1873 /// struct Foo(Vec<(String, i32)>);
1875 /// impl fmt::Debug for Foo {
1876 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1877 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1881 /// // prints "{"A": 10, "B": 11}"
1882 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1884 #[stable(feature = "debug_builders", since = "1.2.0")]
1885 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1886 builders::debug_map_new(self)
1890 #[stable(since = "1.2.0", feature = "formatter_write")]
1891 impl Write for Formatter<'_> {
1892 fn write_str(&mut self, s: &str) -> Result {
1893 self.buf.write_str(s)
1896 fn write_char(&mut self, c: char) -> Result {
1897 self.buf.write_char(c)
1900 fn write_fmt(&mut self, args: Arguments) -> Result {
1901 write(self.buf, args)
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 impl Display for Error {
1907 fn fmt(&self, f: &mut Formatter) -> Result {
1908 Display::fmt("an error occurred when formatting an argument", f)
1912 // Implementations of the core formatting traits
1914 macro_rules! fmt_refs {
1915 ($($tr:ident),*) => {
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 impl<T: ?Sized + $tr> $tr for &T {
1919 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl<T: ?Sized + $tr> $tr for &mut T {
1923 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1929 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1931 #[unstable(feature = "never_type", issue = "35121")]
1933 fn fmt(&self, _: &mut Formatter) -> Result {
1938 #[unstable(feature = "never_type", issue = "35121")]
1939 impl Display for ! {
1940 fn fmt(&self, _: &mut Formatter) -> Result {
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 impl Debug for bool {
1948 fn fmt(&self, f: &mut Formatter) -> Result {
1949 Display::fmt(self, f)
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 impl Display for bool {
1955 fn fmt(&self, f: &mut Formatter) -> Result {
1956 Display::fmt(if *self { "true" } else { "false" }, f)
1960 #[stable(feature = "rust1", since = "1.0.0")]
1961 impl Debug for str {
1962 fn fmt(&self, f: &mut Formatter) -> Result {
1965 for (i, c) in self.char_indices() {
1966 let esc = c.escape_debug();
1967 // If char needs escaping, flush backlog so far and write, else skip
1969 f.write_str(&self[from..i])?;
1973 from = i + c.len_utf8();
1976 f.write_str(&self[from..])?;
1981 #[stable(feature = "rust1", since = "1.0.0")]
1982 impl Display for str {
1983 fn fmt(&self, f: &mut Formatter) -> Result {
1988 #[stable(feature = "rust1", since = "1.0.0")]
1989 impl Debug for char {
1990 fn fmt(&self, f: &mut Formatter) -> Result {
1991 f.write_char('\'')?;
1992 for c in self.escape_debug() {
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 impl Display for char {
2001 fn fmt(&self, f: &mut Formatter) -> Result {
2002 if f.width.is_none() && f.precision.is_none() {
2005 f.pad(self.encode_utf8(&mut [0; 4]))
2010 #[stable(feature = "rust1", since = "1.0.0")]
2011 impl<T: ?Sized> Pointer for *const T {
2012 fn fmt(&self, f: &mut Formatter) -> Result {
2013 let old_width = f.width;
2014 let old_flags = f.flags;
2016 // The alternate flag is already treated by LowerHex as being special-
2017 // it denotes whether to prefix with 0x. We use it to work out whether
2018 // or not to zero extend, and then unconditionally set it to get the
2021 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2023 if let None = f.width {
2024 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2027 f.flags |= 1 << (FlagV1::Alternate as u32);
2029 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2031 f.width = old_width;
2032 f.flags = old_flags;
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 impl<T: ?Sized> Pointer for *mut T {
2040 fn fmt(&self, f: &mut Formatter) -> Result {
2041 Pointer::fmt(&(*self as *const T), f)
2045 #[stable(feature = "rust1", since = "1.0.0")]
2046 impl<T: ?Sized> Pointer for &T {
2047 fn fmt(&self, f: &mut Formatter) -> Result {
2048 Pointer::fmt(&(*self as *const T), f)
2052 #[stable(feature = "rust1", since = "1.0.0")]
2053 impl<T: ?Sized> Pointer for &mut T {
2054 fn fmt(&self, f: &mut Formatter) -> Result {
2055 Pointer::fmt(&(&**self as *const T), f)
2059 // Implementation of Display/Debug for various core types
2061 #[stable(feature = "rust1", since = "1.0.0")]
2062 impl<T: ?Sized> Debug for *const T {
2063 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2065 #[stable(feature = "rust1", since = "1.0.0")]
2066 impl<T: ?Sized> Debug for *mut T {
2067 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2071 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2074 macro_rules! tuple {
2076 ( $($name:ident,)+ ) => (
2077 #[stable(feature = "rust1", since = "1.0.0")]
2078 impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
2079 #[allow(non_snake_case, unused_assignments, deprecated)]
2080 fn fmt(&self, f: &mut Formatter) -> Result {
2081 let mut builder = f.debug_tuple("");
2082 let ($(ref $name,)*) = *self;
2084 builder.field(&$name);
2090 peel! { $($name,)* }
2094 macro_rules! last_type {
2095 ($a:ident,) => { $a };
2096 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2099 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2101 #[stable(feature = "rust1", since = "1.0.0")]
2102 impl<T: Debug> Debug for [T] {
2103 fn fmt(&self, f: &mut Formatter) -> Result {
2104 f.debug_list().entries(self.iter()).finish()
2108 #[stable(feature = "rust1", since = "1.0.0")]
2111 fn fmt(&self, f: &mut Formatter) -> Result {
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 impl<T: ?Sized> Debug for PhantomData<T> {
2117 fn fmt(&self, f: &mut Formatter) -> Result {
2118 f.pad("PhantomData")
2122 #[stable(feature = "rust1", since = "1.0.0")]
2123 impl<T: Copy + Debug> Debug for Cell<T> {
2124 fn fmt(&self, f: &mut Formatter) -> Result {
2125 f.debug_struct("Cell")
2126 .field("value", &self.get())
2131 #[stable(feature = "rust1", since = "1.0.0")]
2132 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2133 fn fmt(&self, f: &mut Formatter) -> Result {
2134 match self.try_borrow() {
2136 f.debug_struct("RefCell")
2137 .field("value", &borrow)
2141 // The RefCell is mutably borrowed so we can't look at its value
2142 // here. Show a placeholder instead.
2143 struct BorrowedPlaceholder;
2145 impl Debug for BorrowedPlaceholder {
2146 fn fmt(&self, f: &mut Formatter) -> Result {
2147 f.write_str("<borrowed>")
2151 f.debug_struct("RefCell")
2152 .field("value", &BorrowedPlaceholder)
2159 #[stable(feature = "rust1", since = "1.0.0")]
2160 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2161 fn fmt(&self, f: &mut Formatter) -> Result {
2162 Debug::fmt(&**self, f)
2166 #[stable(feature = "rust1", since = "1.0.0")]
2167 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2168 fn fmt(&self, f: &mut Formatter) -> Result {
2169 Debug::fmt(&*(self.deref()), f)
2173 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2174 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2175 fn fmt(&self, f: &mut Formatter) -> Result {
2180 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
2181 // it's a lot easier than creating all of the rt::Piece structures here.