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 /// match write(&mut output, format_args!("Hello {}!", "world")) {
100 /// Err(fmt::Error) => panic!("An error occurred"),
104 #[stable(feature = "rust1", since = "1.0.0")]
105 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
108 /// A collection of methods that are required to format a message into a stream.
110 /// This trait is the type which this modules requires when formatting
111 /// information. This is similar to the standard library's [`io::Write`] trait,
112 /// but it is only intended for use in libcore.
114 /// This trait should generally not be implemented by consumers of the standard
115 /// library. The [`write!`] macro accepts an instance of [`io::Write`], and the
116 /// [`io::Write`] trait is favored over implementing this trait.
118 /// [`write!`]: ../../std/macro.write.html
119 /// [`io::Write`]: ../../std/io/trait.Write.html
120 #[stable(feature = "rust1", since = "1.0.0")]
122 /// Writes a slice of bytes into this writer, returning whether the write
125 /// This method can only succeed if the entire byte slice was successfully
126 /// written, and this method will not return until all data has been
127 /// written or an error occurs.
131 /// This function will return an instance of [`Error`] on error.
133 /// [`Error`]: struct.Error.html
138 /// use std::fmt::{Error, Write};
140 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
144 /// let mut buf = String::new();
145 /// writer(&mut buf, "hola").unwrap();
146 /// assert_eq!(&buf, "hola");
148 #[stable(feature = "rust1", since = "1.0.0")]
149 fn write_str(&mut self, s: &str) -> Result;
151 /// Writes a [`char`] into this writer, returning whether the write succeeded.
153 /// A single [`char`] may be encoded as more than one byte.
154 /// This method can only succeed if the entire byte sequence was successfully
155 /// written, and this method will not return until all data has been
156 /// written or an error occurs.
160 /// This function will return an instance of [`Error`] on error.
162 /// [`char`]: ../../std/primitive.char.html
163 /// [`Error`]: struct.Error.html
168 /// use std::fmt::{Error, Write};
170 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
174 /// let mut buf = String::new();
175 /// writer(&mut buf, 'a').unwrap();
176 /// writer(&mut buf, 'b').unwrap();
177 /// assert_eq!(&buf, "ab");
179 #[stable(feature = "fmt_write_char", since = "1.1.0")]
180 fn write_char(&mut self, c: char) -> Result {
181 self.write_str(c.encode_utf8(&mut [0; 4]))
184 /// Glue for usage of the [`write!`] macro with implementors of this trait.
186 /// This method should generally not be invoked manually, but rather through
187 /// the [`write!`] macro itself.
189 /// [`write!`]: ../../std/macro.write.html
194 /// use std::fmt::{Error, Write};
196 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
197 /// f.write_fmt(format_args!("{}", s))
200 /// let mut buf = String::new();
201 /// writer(&mut buf, "world").unwrap();
202 /// assert_eq!(&buf, "world");
204 #[stable(feature = "rust1", since = "1.0.0")]
205 fn write_fmt(&mut self, args: Arguments) -> Result {
206 // This Adapter is needed to allow `self` (of type `&mut
207 // Self`) to be cast to a Write (below) without
208 // requiring a `Sized` bound.
209 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
211 impl<'a, T: ?Sized> Write for Adapter<'a, T>
214 fn write_str(&mut self, s: &str) -> Result {
218 fn write_char(&mut self, c: char) -> Result {
222 fn write_fmt(&mut self, args: Arguments) -> Result {
223 self.0.write_fmt(args)
227 write(&mut Adapter(self), args)
231 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
232 impl<'a, W: Write + ?Sized> Write for &'a mut W {
233 fn write_str(&mut self, s: &str) -> Result {
234 (**self).write_str(s)
237 fn write_char(&mut self, c: char) -> Result {
238 (**self).write_char(c)
241 fn write_fmt(&mut self, args: Arguments) -> Result {
242 (**self).write_fmt(args)
246 /// A struct to represent both where to emit formatting strings to and how they
247 /// should be formatted. A mutable version of this is passed to all formatting
249 #[allow(missing_debug_implementations)]
250 #[stable(feature = "rust1", since = "1.0.0")]
251 pub struct Formatter<'a> {
254 align: rt::v1::Alignment,
255 width: Option<usize>,
256 precision: Option<usize>,
258 buf: &'a mut (Write+'a),
259 curarg: slice::Iter<'a, ArgumentV1<'a>>,
260 args: &'a [ArgumentV1<'a>],
263 // NB. Argument is essentially an optimized partially applied formatting function,
264 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
268 /// Erases all oibits, because `Void` erases the type of the object that
269 /// will be used to produce formatted output. Since we do not know what
270 /// oibits the real types have (and they can have any or none), we need to
271 /// take the most conservative approach and forbid all oibits.
273 /// It was added after #45197 showed that one could share a `!Sync`
274 /// object across threads by passing it into `format_args!`.
275 _oibit_remover: PhantomData<*mut Fn()>,
278 /// This struct represents the generic "argument" which is taken by the Xprintf
279 /// family of functions. It contains a function to format the given value. At
280 /// compile time it is ensured that the function and the value have the correct
281 /// types, and then this struct is used to canonicalize arguments to one type.
283 #[allow(missing_debug_implementations)]
284 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
287 pub struct ArgumentV1<'a> {
289 formatter: fn(&Void, &mut Formatter) -> Result,
292 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
294 impl<'a> Clone for ArgumentV1<'a> {
295 fn clone(&self) -> ArgumentV1<'a> {
300 impl<'a> ArgumentV1<'a> {
302 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
307 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
309 pub fn new<'b, T>(x: &'b T,
310 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
313 formatter: mem::transmute(f),
314 value: mem::transmute(x)
320 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
322 pub fn from_usize(x: &usize) -> ArgumentV1 {
323 ArgumentV1::new(x, ArgumentV1::show_usize)
326 fn as_usize(&self) -> Option<usize> {
327 if self.formatter as usize == ArgumentV1::show_usize as usize {
328 Some(unsafe { *(self.value as *const _ as *const usize) })
335 // flags available in the v1 format of format_args
336 #[derive(Copy, Clone)]
337 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, DebugLowerHex, DebugUpperHex }
339 impl<'a> Arguments<'a> {
340 /// When using the format_args!() macro, this function is used to generate the
341 /// Arguments structure.
342 #[doc(hidden)] #[inline]
343 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
345 pub fn new_v1(pieces: &'a [&'a str],
346 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
354 /// This function is used to specify nonstandard formatting parameters.
355 /// The `pieces` array must be at least as long as `fmt` to construct
356 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
357 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
358 /// created with `argumentusize`. However, failing to do so doesn't cause
359 /// unsafety, but will ignore invalid .
360 #[doc(hidden)] #[inline]
361 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
363 pub fn new_v1_formatted(pieces: &'a [&'a str],
364 args: &'a [ArgumentV1<'a>],
365 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
373 /// Estimates the length of the formatted text.
375 /// This is intended to be used for setting initial `String` capacity
376 /// when using `format!`. Note: this is neither the lower nor upper bound.
377 #[doc(hidden)] #[inline]
378 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
380 pub fn estimated_capacity(&self) -> usize {
381 let pieces_length: usize = self.pieces.iter()
382 .map(|x| x.len()).sum();
384 if self.args.is_empty() {
386 } else if self.pieces[0] == "" && pieces_length < 16 {
387 // If the format string starts with an argument,
388 // don't preallocate anything, unless length
389 // of pieces is significant.
392 // There are some arguments, so any additional push
393 // will reallocate the string. To avoid that,
394 // we're "pre-doubling" the capacity here.
395 pieces_length.checked_mul(2).unwrap_or(0)
400 /// This structure represents a safely precompiled version of a format string
401 /// and its arguments. This cannot be generated at runtime because it cannot
402 /// safely be done, so no constructors are given and the fields are private
403 /// to prevent modification.
405 /// The [`format_args!`] macro will safely create an instance of this structure.
406 /// The macro validates the format string at compile-time so usage of the
407 /// [`write`] and [`format`] functions can be safely performed.
409 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
410 /// and `Display` contexts as seen below. The example also shows that `Debug`
411 /// and `Display` format to the same thing: the interpolated format string
412 /// in `format_args!`.
415 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
416 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
417 /// assert_eq!("1 foo 2", display);
418 /// assert_eq!(display, debug);
421 /// [`format_args!`]: ../../std/macro.format_args.html
422 /// [`format`]: ../../std/fmt/fn.format.html
423 /// [`write`]: ../../std/fmt/fn.write.html
424 #[stable(feature = "rust1", since = "1.0.0")]
425 #[derive(Copy, Clone)]
426 pub struct Arguments<'a> {
427 // Format string pieces to print.
428 pieces: &'a [&'a str],
430 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
431 fmt: Option<&'a [rt::v1::Argument]>,
433 // Dynamic arguments for interpolation, to be interleaved with string
434 // pieces. (Every argument is preceded by a string piece.)
435 args: &'a [ArgumentV1<'a>],
438 #[stable(feature = "rust1", since = "1.0.0")]
439 impl<'a> Debug for Arguments<'a> {
440 fn fmt(&self, fmt: &mut Formatter) -> Result {
441 Display::fmt(self, fmt)
445 #[stable(feature = "rust1", since = "1.0.0")]
446 impl<'a> Display for Arguments<'a> {
447 fn fmt(&self, fmt: &mut Formatter) -> Result {
448 write(fmt.buf, *self)
454 /// `Debug` should format the output in a programmer-facing, debugging context.
456 /// Generally speaking, you should just `derive` a `Debug` implementation.
458 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
460 /// For more information on formatters, see [the module-level documentation][module].
462 /// [module]: ../../std/fmt/index.html
464 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
465 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
466 /// comma-separated list of each field's name and `Debug` value, then `}`. For
467 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
468 /// `Debug` values of the fields, then `)`.
472 /// Deriving an implementation:
481 /// let origin = Point { x: 0, y: 0 };
483 /// println!("The origin is: {:?}", origin);
486 /// Manually implementing:
496 /// impl fmt::Debug for Point {
497 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
498 /// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
502 /// let origin = Point { x: 0, y: 0 };
504 /// println!("The origin is: {:?}", origin);
510 /// The origin is: Point { x: 0, y: 0 }
513 /// There are a number of `debug_*` methods on [`Formatter`] to help you with manual
514 /// implementations, such as [`debug_struct`][debug_struct].
516 /// `Debug` implementations using either `derive` or the debug builder API
517 /// on [`Formatter`] support pretty printing using the alternate flag: `{:#?}`.
519 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
520 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
522 /// Pretty printing with `#?`:
531 /// let origin = Point { x: 0, y: 0 };
533 /// println!("The origin is: {:#?}", origin);
539 /// The origin is: Point {
544 #[stable(feature = "rust1", since = "1.0.0")]
545 #[rustc_on_unimplemented(
546 on(crate_local, label="`{Self}` cannot be formatted using `{{:?}}`",
547 note="add `#[derive(Debug)]` or manually implement `{Debug}`"),
548 message="`{Self}` doesn't implement `{Debug}`",
549 label="`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`",
551 #[doc(alias = "{:?}")]
552 #[lang = "debug_trait"]
554 /// Formats the value using the given formatter.
561 /// struct Position {
566 /// impl fmt::Debug for Position {
567 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
568 /// write!(f, "({:?}, {:?})", self.longitude, self.latitude)
572 /// assert_eq!("(1.987, 2.983)".to_owned(),
573 /// format!("{:?}", Position { longitude: 1.987, latitude: 2.983, }));
575 #[stable(feature = "rust1", since = "1.0.0")]
576 fn fmt(&self, f: &mut Formatter) -> Result;
579 /// Format trait for an empty format, `{}`.
581 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
582 /// output, and so cannot be derived.
584 /// [debug]: trait.Debug.html
586 /// For more information on formatters, see [the module-level documentation][module].
588 /// [module]: ../../std/fmt/index.html
592 /// Implementing `Display` on a type:
602 /// impl fmt::Display for Point {
603 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
604 /// write!(f, "({}, {})", self.x, self.y)
608 /// let origin = Point { x: 0, y: 0 };
610 /// println!("The origin is: {}", origin);
612 #[rustc_on_unimplemented(
613 message="`{Self}` doesn't implement `{Display}`",
614 label="`{Self}` cannot be formatted with the default formatter",
615 note="in format strings you may be able to use `{{:?}}` \
616 (or {{:#?}} for pretty-print) instead",
619 #[stable(feature = "rust1", since = "1.0.0")]
621 /// Formats the value using the given formatter.
628 /// struct Position {
633 /// impl fmt::Display for Position {
634 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
635 /// write!(f, "({}, {})", self.longitude, self.latitude)
639 /// assert_eq!("(1.987, 2.983)".to_owned(),
640 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
642 #[stable(feature = "rust1", since = "1.0.0")]
643 fn fmt(&self, f: &mut Formatter) -> Result;
648 /// The `Octal` trait should format its output as a number in base-8.
650 /// For primitive signed integers (`i8` to `i128`, and `isize`),
651 /// negative values are formatted as the two’s complement representation.
653 /// The alternate flag, `#`, adds a `0o` in front of the output.
655 /// For more information on formatters, see [the module-level documentation][module].
657 /// [module]: ../../std/fmt/index.html
661 /// Basic usage with `i32`:
664 /// let x = 42; // 42 is '52' in octal
666 /// assert_eq!(format!("{:o}", x), "52");
667 /// assert_eq!(format!("{:#o}", x), "0o52");
669 /// assert_eq!(format!("{:o}", -16), "37777777760");
672 /// Implementing `Octal` on a type:
677 /// struct Length(i32);
679 /// impl fmt::Octal for Length {
680 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
681 /// let val = self.0;
683 /// write!(f, "{:o}", val) // delegate to i32's implementation
687 /// let l = Length(9);
689 /// println!("l as octal is: {:o}", l);
691 #[stable(feature = "rust1", since = "1.0.0")]
693 /// Formats the value using the given formatter.
694 #[stable(feature = "rust1", since = "1.0.0")]
695 fn fmt(&self, f: &mut Formatter) -> Result;
700 /// The `Binary` trait should format its output as a number in binary.
702 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
703 /// negative values are formatted as the two’s complement representation.
705 /// The alternate flag, `#`, adds a `0b` in front of the output.
707 /// For more information on formatters, see [the module-level documentation][module].
711 /// Basic usage with [`i32`]:
714 /// let x = 42; // 42 is '101010' in binary
716 /// assert_eq!(format!("{:b}", x), "101010");
717 /// assert_eq!(format!("{:#b}", x), "0b101010");
719 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
722 /// Implementing `Binary` on a type:
727 /// struct Length(i32);
729 /// impl fmt::Binary for Length {
730 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
731 /// let val = self.0;
733 /// write!(f, "{:b}", val) // delegate to i32's implementation
737 /// let l = Length(107);
739 /// println!("l as binary is: {:b}", l);
742 /// [module]: ../../std/fmt/index.html
743 /// [`i8`]: ../../std/primitive.i8.html
744 /// [`i128`]: ../../std/primitive.i128.html
745 /// [`isize`]: ../../std/primitive.isize.html
746 /// [`i32`]: ../../std/primitive.i32.html
747 #[stable(feature = "rust1", since = "1.0.0")]
749 /// Formats the value using the given formatter.
750 #[stable(feature = "rust1", since = "1.0.0")]
751 fn fmt(&self, f: &mut Formatter) -> Result;
756 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
759 /// For primitive signed integers (`i8` to `i128`, and `isize`),
760 /// negative values are formatted as the two’s complement representation.
762 /// The alternate flag, `#`, adds a `0x` in front of the output.
764 /// For more information on formatters, see [the module-level documentation][module].
766 /// [module]: ../../std/fmt/index.html
770 /// Basic usage with `i32`:
773 /// let x = 42; // 42 is '2a' in hex
775 /// assert_eq!(format!("{:x}", x), "2a");
776 /// assert_eq!(format!("{:#x}", x), "0x2a");
778 /// assert_eq!(format!("{:x}", -16), "fffffff0");
781 /// Implementing `LowerHex` on a type:
786 /// struct Length(i32);
788 /// impl fmt::LowerHex for Length {
789 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
790 /// let val = self.0;
792 /// write!(f, "{:x}", val) // delegate to i32's implementation
796 /// let l = Length(9);
798 /// println!("l as hex is: {:x}", l);
800 #[stable(feature = "rust1", since = "1.0.0")]
802 /// Formats the value using the given formatter.
803 #[stable(feature = "rust1", since = "1.0.0")]
804 fn fmt(&self, f: &mut Formatter) -> Result;
809 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
812 /// For primitive signed integers (`i8` to `i128`, and `isize`),
813 /// negative values are formatted as the two’s complement representation.
815 /// The alternate flag, `#`, adds a `0x` in front of the output.
817 /// For more information on formatters, see [the module-level documentation][module].
819 /// [module]: ../../std/fmt/index.html
823 /// Basic usage with `i32`:
826 /// let x = 42; // 42 is '2A' in hex
828 /// assert_eq!(format!("{:X}", x), "2A");
829 /// assert_eq!(format!("{:#X}", x), "0x2A");
831 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
834 /// Implementing `UpperHex` on a type:
839 /// struct Length(i32);
841 /// impl fmt::UpperHex for Length {
842 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
843 /// let val = self.0;
845 /// write!(f, "{:X}", val) // delegate to i32's implementation
849 /// let l = Length(9);
851 /// println!("l as hex is: {:X}", l);
853 #[stable(feature = "rust1", since = "1.0.0")]
855 /// Formats the value using the given formatter.
856 #[stable(feature = "rust1", since = "1.0.0")]
857 fn fmt(&self, f: &mut Formatter) -> Result;
862 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
865 /// For more information on formatters, see [the module-level documentation][module].
867 /// [module]: ../../std/fmt/index.html
871 /// Basic usage with `&i32`:
876 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
879 /// Implementing `Pointer` on a type:
884 /// struct Length(i32);
886 /// impl fmt::Pointer for Length {
887 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
888 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
890 /// write!(f, "{:p}", self as *const Length)
894 /// let l = Length(42);
896 /// println!("l is in memory here: {:p}", l);
898 #[stable(feature = "rust1", since = "1.0.0")]
900 /// Formats the value using the given formatter.
901 #[stable(feature = "rust1", since = "1.0.0")]
902 fn fmt(&self, f: &mut Formatter) -> Result;
907 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
909 /// For more information on formatters, see [the module-level documentation][module].
911 /// [module]: ../../std/fmt/index.html
915 /// Basic usage with `i32`:
918 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
920 /// assert_eq!(format!("{:e}", x), "4.2e1");
923 /// Implementing `LowerExp` on a type:
928 /// struct Length(i32);
930 /// impl fmt::LowerExp for Length {
931 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
932 /// let val = self.0;
933 /// write!(f, "{}e1", val / 10)
937 /// let l = Length(100);
939 /// println!("l in scientific notation is: {:e}", l);
941 #[stable(feature = "rust1", since = "1.0.0")]
943 /// Formats the value using the given formatter.
944 #[stable(feature = "rust1", since = "1.0.0")]
945 fn fmt(&self, f: &mut Formatter) -> Result;
950 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
952 /// For more information on formatters, see [the module-level documentation][module].
954 /// [module]: ../../std/fmt/index.html
958 /// Basic usage with `f32`:
961 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
963 /// assert_eq!(format!("{:E}", x), "4.2E1");
966 /// Implementing `UpperExp` on a type:
971 /// struct Length(i32);
973 /// impl fmt::UpperExp for Length {
974 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
975 /// let val = self.0;
976 /// write!(f, "{}E1", val / 10)
980 /// let l = Length(100);
982 /// println!("l in scientific notation is: {:E}", l);
984 #[stable(feature = "rust1", since = "1.0.0")]
986 /// Formats the value using the given formatter.
987 #[stable(feature = "rust1", since = "1.0.0")]
988 fn fmt(&self, f: &mut Formatter) -> Result;
991 /// The `write` function takes an output stream, and an `Arguments` struct
992 /// that can be precompiled with the `format_args!` macro.
994 /// The arguments will be formatted according to the specified format string
995 /// into the output stream provided.
1004 /// let mut output = String::new();
1005 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1006 /// .expect("Error occurred while trying to write in String");
1007 /// assert_eq!(output, "Hello world!");
1010 /// Please note that using [`write!`] might be preferable. Example:
1013 /// use std::fmt::Write;
1015 /// let mut output = String::new();
1016 /// write!(&mut output, "Hello {}!", "world")
1017 /// .expect("Error occurred while trying to write in String");
1018 /// assert_eq!(output, "Hello world!");
1021 /// [`write!`]: ../../std/macro.write.html
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 pub fn write(output: &mut Write, args: Arguments) -> Result {
1024 let mut formatter = Formatter {
1029 align: rt::v1::Alignment::Unknown,
1032 curarg: args.args.iter(),
1035 let mut pieces = args.pieces.iter();
1039 // We can use default formatting parameters for all arguments.
1040 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
1041 formatter.buf.write_str(*piece)?;
1042 (arg.formatter)(arg.value, &mut formatter)?;
1046 // Every spec has a corresponding argument that is preceded by
1048 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
1049 formatter.buf.write_str(*piece)?;
1050 formatter.run(arg)?;
1055 // There can be only one trailing string piece left.
1056 if let Some(piece) = pieces.next() {
1057 formatter.buf.write_str(*piece)?;
1063 impl<'a> Formatter<'a> {
1064 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1065 where 'b: 'c, F: FnOnce(&'b mut (Write+'b)) -> &'c mut (Write+'c)
1068 // We want to change this
1069 buf: wrap(self.buf),
1071 // And preserve these
1076 precision: self.precision,
1078 // These only exist in the struct for the `run` method,
1079 // which won’t be used together with this method.
1080 curarg: self.curarg.clone(),
1085 // First up is the collection of functions used to execute a format string
1086 // at runtime. This consumes all of the compile-time statics generated by
1087 // the format! syntax extension.
1088 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1089 // Fill in the format parameters into the formatter
1090 self.fill = arg.format.fill;
1091 self.align = arg.format.align;
1092 self.flags = arg.format.flags;
1093 self.width = self.getcount(&arg.format.width);
1094 self.precision = self.getcount(&arg.format.precision);
1096 // Extract the correct argument
1097 let value = match arg.position {
1098 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1099 rt::v1::Position::At(i) => self.args[i],
1102 // Then actually do some printing
1103 (value.formatter)(value.value, self)
1106 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1108 rt::v1::Count::Is(n) => Some(n),
1109 rt::v1::Count::Implied => None,
1110 rt::v1::Count::Param(i) => {
1111 self.args[i].as_usize()
1113 rt::v1::Count::NextParam => {
1114 self.curarg.next().and_then(|arg| arg.as_usize())
1119 // Helper methods used for padding and processing formatting arguments that
1120 // all formatting traits can use.
1122 /// Performs the correct padding for an integer which has already been
1123 /// emitted into a str. The str should *not* contain the sign for the
1124 /// integer, that will be added by this method.
1128 /// * is_nonnegative - whether the original integer was either positive or zero.
1129 /// * prefix - if the '#' character (Alternate) is provided, this
1130 /// is the prefix to put in front of the number.
1131 /// * buf - the byte array that the number has been formatted into
1133 /// This function will correctly account for the flags provided as well as
1134 /// the minimum width. It will not take precision into account.
1135 #[stable(feature = "rust1", since = "1.0.0")]
1136 pub fn pad_integral(&mut self,
1137 is_nonnegative: bool,
1141 let mut width = buf.len();
1143 let mut sign = None;
1144 if !is_nonnegative {
1145 sign = Some('-'); width += 1;
1146 } else if self.sign_plus() {
1147 sign = Some('+'); width += 1;
1150 let mut prefixed = false;
1151 if self.alternate() {
1152 prefixed = true; width += prefix.chars().count();
1155 // Writes the sign if it exists, and then the prefix if it was requested
1156 let write_prefix = |f: &mut Formatter| {
1157 if let Some(c) = sign {
1158 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
1160 if prefixed { f.buf.write_str(prefix) }
1164 // The `width` field is more of a `min-width` parameter at this point.
1166 // If there's no minimum length requirements then we can just
1169 write_prefix(self)?; self.buf.write_str(buf)
1171 // Check if we're over the minimum width, if so then we can also
1172 // just write the bytes.
1173 Some(min) if width >= min => {
1174 write_prefix(self)?; self.buf.write_str(buf)
1176 // The sign and prefix goes before the padding if the fill character
1178 Some(min) if self.sign_aware_zero_pad() => {
1180 self.align = rt::v1::Alignment::Right;
1181 write_prefix(self)?;
1182 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1183 f.buf.write_str(buf)
1186 // Otherwise, the sign and prefix goes after the padding
1188 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1189 write_prefix(f)?; f.buf.write_str(buf)
1195 /// This function takes a string slice and emits it to the internal buffer
1196 /// after applying the relevant formatting flags specified. The flags
1197 /// recognized for generic strings are:
1199 /// * width - the minimum width of what to emit
1200 /// * fill/align - what to emit and where to emit it if the string
1201 /// provided needs to be padded
1202 /// * precision - the maximum length to emit, the string is truncated if it
1203 /// is longer than this length
1205 /// Notably this function ignores the `flag` parameters.
1214 /// impl fmt::Display for Foo {
1215 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1216 /// formatter.pad("Foo")
1220 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1221 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 pub fn pad(&mut self, s: &str) -> Result {
1225 // Make sure there's a fast path up front
1226 if self.width.is_none() && self.precision.is_none() {
1227 return self.buf.write_str(s);
1229 // The `precision` field can be interpreted as a `max-width` for the
1230 // string being formatted.
1231 let s = if let Some(max) = self.precision {
1232 // If our string is longer that the precision, then we must have
1233 // truncation. However other flags like `fill`, `width` and `align`
1234 // must act as always.
1235 if let Some((i, _)) = s.char_indices().skip(max).next() {
1236 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1237 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1238 // `unsafe` and otherwise don't emit any panic-related code
1240 s.get(..i).unwrap_or(&s)
1247 // The `width` field is more of a `min-width` parameter at this point.
1249 // If we're under the maximum length, and there's no minimum length
1250 // requirements, then we can just emit the string
1251 None => self.buf.write_str(s),
1252 // If we're under the maximum width, check if we're over the minimum
1253 // width, if so it's as easy as just emitting the string.
1254 Some(width) if s.chars().count() >= width => {
1255 self.buf.write_str(s)
1257 // If we're under both the maximum and the minimum width, then fill
1258 // up the minimum width with the specified string + some alignment.
1260 let align = rt::v1::Alignment::Left;
1261 self.with_padding(width - s.chars().count(), align, |me| {
1268 /// Runs a callback, emitting the correct padding either before or
1269 /// afterwards depending on whether right or left alignment is requested.
1270 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1272 where F: FnOnce(&mut Formatter) -> Result,
1274 let align = match self.align {
1275 rt::v1::Alignment::Unknown => default,
1279 let (pre_pad, post_pad) = match align {
1280 rt::v1::Alignment::Left => (0, padding),
1281 rt::v1::Alignment::Right |
1282 rt::v1::Alignment::Unknown => (padding, 0),
1283 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1286 let mut fill = [0; 4];
1287 let fill = self.fill.encode_utf8(&mut fill);
1289 for _ in 0..pre_pad {
1290 self.buf.write_str(fill)?;
1295 for _ in 0..post_pad {
1296 self.buf.write_str(fill)?;
1302 /// Takes the formatted parts and applies the padding.
1303 /// Assumes that the caller already has rendered the parts with required precision,
1304 /// so that `self.precision` can be ignored.
1305 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1306 if let Some(mut width) = self.width {
1307 // for the sign-aware zero padding, we render the sign first and
1308 // behave as if we had no sign from the beginning.
1309 let mut formatted = formatted.clone();
1310 let old_fill = self.fill;
1311 let old_align = self.align;
1312 let mut align = old_align;
1313 if self.sign_aware_zero_pad() {
1314 // a sign always goes first
1315 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1316 self.buf.write_str(sign)?;
1318 // remove the sign from the formatted parts
1319 formatted.sign = b"";
1320 width = if width < sign.len() { 0 } else { width - sign.len() };
1321 align = rt::v1::Alignment::Right;
1323 self.align = rt::v1::Alignment::Right;
1326 // remaining parts go through the ordinary padding process.
1327 let len = formatted.len();
1328 let ret = if width <= len { // no padding
1329 self.write_formatted_parts(&formatted)
1331 self.with_padding(width - len, align, |f| {
1332 f.write_formatted_parts(&formatted)
1335 self.fill = old_fill;
1336 self.align = old_align;
1339 // this is the common case and we take a shortcut
1340 self.write_formatted_parts(formatted)
1344 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1345 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1346 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1349 if !formatted.sign.is_empty() {
1350 write_bytes(self.buf, formatted.sign)?;
1352 for part in formatted.parts {
1354 flt2dec::Part::Zero(mut nzeroes) => {
1355 const ZEROES: &'static str = // 64 zeroes
1356 "0000000000000000000000000000000000000000000000000000000000000000";
1357 while nzeroes > ZEROES.len() {
1358 self.buf.write_str(ZEROES)?;
1359 nzeroes -= ZEROES.len();
1362 self.buf.write_str(&ZEROES[..nzeroes])?;
1365 flt2dec::Part::Num(mut v) => {
1367 let len = part.len();
1368 for c in s[..len].iter_mut().rev() {
1369 *c = b'0' + (v % 10) as u8;
1372 write_bytes(self.buf, &s[..len])?;
1374 flt2dec::Part::Copy(buf) => {
1375 write_bytes(self.buf, buf)?;
1382 /// Writes some data to the underlying buffer contained within this
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 pub fn write_str(&mut self, data: &str) -> Result {
1386 self.buf.write_str(data)
1389 /// Writes some formatted information into this instance.
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1392 write(self.buf, fmt)
1395 /// Flags for formatting
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 #[rustc_deprecated(since = "1.24.0",
1398 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1399 or `sign_aware_zero_pad` methods instead")]
1400 pub fn flags(&self) -> u32 { self.flags }
1402 /// Character used as 'fill' whenever there is alignment.
1411 /// impl fmt::Display for Foo {
1412 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1413 /// let c = formatter.fill();
1414 /// if let Some(width) = formatter.width() {
1415 /// for _ in 0..width {
1416 /// write!(formatter, "{}", c)?;
1420 /// write!(formatter, "{}", c)
1425 /// // We set alignment to the left with ">".
1426 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1427 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1429 #[stable(feature = "fmt_flags", since = "1.5.0")]
1430 pub fn fill(&self) -> char { self.fill }
1432 /// Flag indicating what form of alignment was requested.
1437 /// extern crate core;
1439 /// use std::fmt::{self, Alignment};
1443 /// impl fmt::Display for Foo {
1444 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1445 /// let s = if let Some(s) = formatter.align() {
1447 /// Alignment::Left => "left",
1448 /// Alignment::Right => "right",
1449 /// Alignment::Center => "center",
1454 /// write!(formatter, "{}", s)
1459 /// assert_eq!(&format!("{:<}", Foo), "left");
1460 /// assert_eq!(&format!("{:>}", Foo), "right");
1461 /// assert_eq!(&format!("{:^}", Foo), "center");
1462 /// assert_eq!(&format!("{}", Foo), "into the void");
1465 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1466 pub fn align(&self) -> Option<Alignment> {
1468 rt::v1::Alignment::Left => Some(Alignment::Left),
1469 rt::v1::Alignment::Right => Some(Alignment::Right),
1470 rt::v1::Alignment::Center => Some(Alignment::Center),
1471 rt::v1::Alignment::Unknown => None,
1475 /// Optionally specified integer width that the output should be.
1482 /// struct Foo(i32);
1484 /// impl fmt::Display for Foo {
1485 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1486 /// if let Some(width) = formatter.width() {
1487 /// // If we received a width, we use it
1488 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1490 /// // Otherwise we do nothing special
1491 /// write!(formatter, "Foo({})", self.0)
1496 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1497 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1499 #[stable(feature = "fmt_flags", since = "1.5.0")]
1500 pub fn width(&self) -> Option<usize> { self.width }
1502 /// Optionally specified precision for numeric types.
1509 /// struct Foo(f32);
1511 /// impl fmt::Display for Foo {
1512 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1513 /// if let Some(precision) = formatter.precision() {
1514 /// // If we received a precision, we use it.
1515 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1517 /// // Otherwise we default to 2.
1518 /// write!(formatter, "Foo({:.2})", self.0)
1523 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1524 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1526 #[stable(feature = "fmt_flags", since = "1.5.0")]
1527 pub fn precision(&self) -> Option<usize> { self.precision }
1529 /// Determines if the `+` flag was specified.
1536 /// struct Foo(i32);
1538 /// impl fmt::Display for Foo {
1539 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1540 /// if formatter.sign_plus() {
1541 /// write!(formatter,
1543 /// if self.0 < 0 { '-' } else { '+' },
1546 /// write!(formatter, "Foo({})", self.0)
1551 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1552 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1554 #[stable(feature = "fmt_flags", since = "1.5.0")]
1555 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1557 /// Determines if the `-` flag was specified.
1564 /// struct Foo(i32);
1566 /// impl fmt::Display for Foo {
1567 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1568 /// if formatter.sign_minus() {
1569 /// // You want a minus sign? Have one!
1570 /// write!(formatter, "-Foo({})", self.0)
1572 /// write!(formatter, "Foo({})", self.0)
1577 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1578 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1580 #[stable(feature = "fmt_flags", since = "1.5.0")]
1581 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1583 /// Determines if the `#` flag was specified.
1590 /// struct Foo(i32);
1592 /// impl fmt::Display for Foo {
1593 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1594 /// if formatter.alternate() {
1595 /// write!(formatter, "Foo({})", self.0)
1597 /// write!(formatter, "{}", self.0)
1602 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1603 /// assert_eq!(&format!("{}", Foo(23)), "23");
1605 #[stable(feature = "fmt_flags", since = "1.5.0")]
1606 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1608 /// Determines if the `0` flag was specified.
1615 /// struct Foo(i32);
1617 /// impl fmt::Display for Foo {
1618 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1619 /// assert!(formatter.sign_aware_zero_pad());
1620 /// assert_eq!(formatter.width(), Some(4));
1621 /// // We ignore the formatter's options.
1622 /// write!(formatter, "{}", self.0)
1626 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1628 #[stable(feature = "fmt_flags", since = "1.5.0")]
1629 pub fn sign_aware_zero_pad(&self) -> bool {
1630 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1633 // FIXME: Decide what public API we want for these two flags.
1634 // https://github.com/rust-lang/rust/issues/48584
1635 fn debug_lower_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0 }
1637 fn debug_upper_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0 }
1639 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1640 /// [`fmt::Debug`] implementations for structs.
1642 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1643 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1649 /// use std::net::Ipv4Addr;
1657 /// impl fmt::Debug for Foo {
1658 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1659 /// fmt.debug_struct("Foo")
1660 /// .field("bar", &self.bar)
1661 /// .field("baz", &self.baz)
1662 /// .field("addr", &format_args!("{}", self.addr))
1668 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1669 /// format!("{:?}", Foo {
1671 /// baz: "Hello World".to_string(),
1672 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1676 #[stable(feature = "debug_builders", since = "1.2.0")]
1677 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1678 builders::debug_struct_new(self, name)
1681 /// Creates a `DebugTuple` builder designed to assist with creation of
1682 /// `fmt::Debug` implementations for tuple structs.
1688 /// use std::marker::PhantomData;
1690 /// struct Foo<T>(i32, String, PhantomData<T>);
1692 /// impl<T> fmt::Debug for Foo<T> {
1693 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1694 /// fmt.debug_tuple("Foo")
1697 /// .field(&format_args!("_"))
1703 /// "Foo(10, \"Hello\", _)",
1704 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1707 #[stable(feature = "debug_builders", since = "1.2.0")]
1708 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1709 builders::debug_tuple_new(self, name)
1712 /// Creates a `DebugList` builder designed to assist with creation of
1713 /// `fmt::Debug` implementations for list-like structures.
1720 /// struct Foo(Vec<i32>);
1722 /// impl fmt::Debug for Foo {
1723 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1724 /// fmt.debug_list().entries(self.0.iter()).finish()
1728 /// // prints "[10, 11]"
1729 /// println!("{:?}", Foo(vec![10, 11]));
1731 #[stable(feature = "debug_builders", since = "1.2.0")]
1732 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1733 builders::debug_list_new(self)
1736 /// Creates a `DebugSet` builder designed to assist with creation of
1737 /// `fmt::Debug` implementations for set-like structures.
1744 /// struct Foo(Vec<i32>);
1746 /// impl fmt::Debug for Foo {
1747 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1748 /// fmt.debug_set().entries(self.0.iter()).finish()
1752 /// // prints "{10, 11}"
1753 /// println!("{:?}", Foo(vec![10, 11]));
1756 /// [`format_args!`]: ../../std/macro.format_args.html
1758 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1759 /// to build a list of match arms:
1764 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1765 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1767 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1769 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1771 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1772 /// L::fmt(&(self.0).0, fmt)?;
1773 /// fmt.write_str(" => ")?;
1774 /// R::fmt(&(self.0).1, fmt)
1778 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1780 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1782 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1784 /// .entries(self.0.iter().map(Arm))
1785 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1790 #[stable(feature = "debug_builders", since = "1.2.0")]
1791 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1792 builders::debug_set_new(self)
1795 /// Creates a `DebugMap` builder designed to assist with creation of
1796 /// `fmt::Debug` implementations for map-like structures.
1803 /// struct Foo(Vec<(String, i32)>);
1805 /// impl fmt::Debug for Foo {
1806 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1807 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1811 /// // prints "{"A": 10, "B": 11}"
1812 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1814 #[stable(feature = "debug_builders", since = "1.2.0")]
1815 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1816 builders::debug_map_new(self)
1820 #[stable(since = "1.2.0", feature = "formatter_write")]
1821 impl<'a> Write for Formatter<'a> {
1822 fn write_str(&mut self, s: &str) -> Result {
1823 self.buf.write_str(s)
1826 fn write_char(&mut self, c: char) -> Result {
1827 self.buf.write_char(c)
1830 fn write_fmt(&mut self, args: Arguments) -> Result {
1831 write(self.buf, args)
1835 #[stable(feature = "rust1", since = "1.0.0")]
1836 impl Display for Error {
1837 fn fmt(&self, f: &mut Formatter) -> Result {
1838 Display::fmt("an error occurred when formatting an argument", f)
1842 // Implementations of the core formatting traits
1844 macro_rules! fmt_refs {
1845 ($($tr:ident),*) => {
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 impl<'a, T: ?Sized + $tr> $tr for &'a T {
1849 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1851 #[stable(feature = "rust1", since = "1.0.0")]
1852 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1853 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1859 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1861 #[unstable(feature = "never_type", issue = "35121")]
1863 fn fmt(&self, _: &mut Formatter) -> Result {
1868 #[unstable(feature = "never_type", issue = "35121")]
1869 impl Display for ! {
1870 fn fmt(&self, _: &mut Formatter) -> Result {
1875 #[stable(feature = "rust1", since = "1.0.0")]
1876 impl Debug for bool {
1878 fn fmt(&self, f: &mut Formatter) -> Result {
1879 Display::fmt(self, f)
1883 #[stable(feature = "rust1", since = "1.0.0")]
1884 impl Display for bool {
1885 fn fmt(&self, f: &mut Formatter) -> Result {
1886 Display::fmt(if *self { "true" } else { "false" }, f)
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 impl Debug for str {
1892 fn fmt(&self, f: &mut Formatter) -> Result {
1895 for (i, c) in self.char_indices() {
1896 let esc = c.escape_debug();
1897 // If char needs escaping, flush backlog so far and write, else skip
1899 f.write_str(&self[from..i])?;
1903 from = i + c.len_utf8();
1906 f.write_str(&self[from..])?;
1911 #[stable(feature = "rust1", since = "1.0.0")]
1912 impl Display for str {
1913 fn fmt(&self, f: &mut Formatter) -> Result {
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 impl Debug for char {
1920 fn fmt(&self, f: &mut Formatter) -> Result {
1921 f.write_char('\'')?;
1922 for c in self.escape_debug() {
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 impl Display for char {
1931 fn fmt(&self, f: &mut Formatter) -> Result {
1932 if f.width.is_none() && f.precision.is_none() {
1935 f.pad(self.encode_utf8(&mut [0; 4]))
1940 #[stable(feature = "rust1", since = "1.0.0")]
1941 impl<T: ?Sized> Pointer for *const T {
1942 fn fmt(&self, f: &mut Formatter) -> Result {
1943 let old_width = f.width;
1944 let old_flags = f.flags;
1946 // The alternate flag is already treated by LowerHex as being special-
1947 // it denotes whether to prefix with 0x. We use it to work out whether
1948 // or not to zero extend, and then unconditionally set it to get the
1951 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1953 if let None = f.width {
1954 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
1957 f.flags |= 1 << (FlagV1::Alternate as u32);
1959 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
1961 f.width = old_width;
1962 f.flags = old_flags;
1968 #[stable(feature = "rust1", since = "1.0.0")]
1969 impl<T: ?Sized> Pointer for *mut T {
1970 fn fmt(&self, f: &mut Formatter) -> Result {
1971 Pointer::fmt(&(*self as *const T), f)
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 impl<'a, T: ?Sized> Pointer for &'a T {
1977 fn fmt(&self, f: &mut Formatter) -> Result {
1978 Pointer::fmt(&(*self as *const T), f)
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 impl<'a, T: ?Sized> Pointer for &'a mut T {
1984 fn fmt(&self, f: &mut Formatter) -> Result {
1985 Pointer::fmt(&(&**self as *const T), f)
1989 // Implementation of Display/Debug for various core types
1991 #[stable(feature = "rust1", since = "1.0.0")]
1992 impl<T: ?Sized> Debug for *const T {
1993 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 impl<T: ?Sized> Debug for *mut T {
1997 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2001 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2004 macro_rules! tuple {
2006 ( $($name:ident,)+ ) => (
2007 #[stable(feature = "rust1", since = "1.0.0")]
2008 impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
2009 #[allow(non_snake_case, unused_assignments, deprecated)]
2010 fn fmt(&self, f: &mut Formatter) -> Result {
2011 let mut builder = f.debug_tuple("");
2012 let ($(ref $name,)*) = *self;
2014 builder.field(&$name);
2020 peel! { $($name,)* }
2024 macro_rules! last_type {
2025 ($a:ident,) => { $a };
2026 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2029 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 impl<T: Debug> Debug for [T] {
2033 fn fmt(&self, f: &mut Formatter) -> Result {
2034 f.debug_list().entries(self.iter()).finish()
2038 #[stable(feature = "rust1", since = "1.0.0")]
2041 fn fmt(&self, f: &mut Formatter) -> Result {
2045 #[stable(feature = "rust1", since = "1.0.0")]
2046 impl<T: ?Sized> Debug for PhantomData<T> {
2047 fn fmt(&self, f: &mut Formatter) -> Result {
2048 f.pad("PhantomData")
2052 #[stable(feature = "rust1", since = "1.0.0")]
2053 impl<T: Copy + Debug> Debug for Cell<T> {
2054 fn fmt(&self, f: &mut Formatter) -> Result {
2055 f.debug_struct("Cell")
2056 .field("value", &self.get())
2061 #[stable(feature = "rust1", since = "1.0.0")]
2062 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2063 fn fmt(&self, f: &mut Formatter) -> Result {
2064 match self.try_borrow() {
2066 f.debug_struct("RefCell")
2067 .field("value", &borrow)
2071 // The RefCell is mutably borrowed so we can't look at its value
2072 // here. Show a placeholder instead.
2073 struct BorrowedPlaceholder;
2075 impl Debug for BorrowedPlaceholder {
2076 fn fmt(&self, f: &mut Formatter) -> Result {
2077 f.write_str("<borrowed>")
2081 f.debug_struct("RefCell")
2082 .field("value", &BorrowedPlaceholder)
2089 #[stable(feature = "rust1", since = "1.0.0")]
2090 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
2091 fn fmt(&self, f: &mut Formatter) -> Result {
2092 Debug::fmt(&**self, f)
2096 #[stable(feature = "rust1", since = "1.0.0")]
2097 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
2098 fn fmt(&self, f: &mut Formatter) -> Result {
2099 Debug::fmt(&*(self.deref()), f)
2103 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2104 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2105 fn fmt(&self, f: &mut Formatter) -> Result {
2110 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
2111 // it's a lot easier than creating all of the rt::Piece structures here.