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 #[unstable(feature = "fmt_flags_align", issue = "27726")]
29 /// Possible alignments returned by `Formatter::align`
32 /// Indication that contents should be left-aligned.
34 /// Indication that contents should be right-aligned.
36 /// Indication that contents should be center-aligned.
38 /// No alignment was requested.
42 #[stable(feature = "debug_builders", since = "1.2.0")]
43 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
45 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
52 /// The type returned by formatter methods.
66 /// impl fmt::Display for Triangle {
67 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
72 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
74 /// println!("{}", pythagorean_triple);
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub type Result = result::Result<(), Error>;
79 /// The error type which is returned from formatting a message into a stream.
81 /// This type does not support transmission of an error other than that an error
82 /// occurred. Any extra information must be arranged to be transmitted through
85 /// An important thing to remember is that the type `fmt::Error` should not be
86 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
89 /// [`std::io::Error`]: ../../std/io/struct.Error.html
90 /// [`std::error::Error`]: ../../std/error/trait.Error.html
95 /// use std::fmt::{self, write};
97 /// let mut output = String::new();
98 /// match write(&mut output, format_args!("Hello {}!", "world")) {
99 /// Err(fmt::Error) => 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<'a, T: ?Sized> Write for Adapter<'a, 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<'a, W: Write + ?Sized> Write for &'a 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 (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 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<'a> Clone for ArgumentV1<'a> {
294 fn clone(&self) -> ArgumentV1<'a> {
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, }
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 /// and pass it to a function or closure, passed as the first argument. The
406 /// macro validates the format string at compile-time so usage of the [`write`]
407 /// and [`format`] functions can be safely performed.
409 /// [`format_args!`]: ../../std/macro.format_args.html
410 /// [`format`]: ../../std/fmt/fn.format.html
411 /// [`write`]: ../../std/fmt/fn.write.html
412 #[stable(feature = "rust1", since = "1.0.0")]
413 #[derive(Copy, Clone)]
414 pub struct Arguments<'a> {
415 // Format string pieces to print.
416 pieces: &'a [&'a str],
418 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
419 fmt: Option<&'a [rt::v1::Argument]>,
421 // Dynamic arguments for interpolation, to be interleaved with string
422 // pieces. (Every argument is preceded by a string piece.)
423 args: &'a [ArgumentV1<'a>],
426 #[stable(feature = "rust1", since = "1.0.0")]
427 impl<'a> Debug for Arguments<'a> {
428 fn fmt(&self, fmt: &mut Formatter) -> Result {
429 Display::fmt(self, fmt)
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl<'a> Display for Arguments<'a> {
435 fn fmt(&self, fmt: &mut Formatter) -> Result {
436 write(fmt.buf, *self)
442 /// `Debug` should format the output in a programmer-facing, debugging context.
444 /// Generally speaking, you should just `derive` a `Debug` implementation.
446 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
448 /// For more information on formatters, see [the module-level documentation][module].
450 /// [module]: ../../std/fmt/index.html
452 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
453 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
454 /// comma-separated list of each field's name and `Debug` value, then `}`. For
455 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
456 /// `Debug` values of the fields, then `)`.
460 /// Deriving an implementation:
469 /// let origin = Point { x: 0, y: 0 };
471 /// println!("The origin is: {:?}", origin);
474 /// Manually implementing:
484 /// impl fmt::Debug for Point {
485 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
486 /// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
490 /// let origin = Point { x: 0, y: 0 };
492 /// println!("The origin is: {:?}", origin);
498 /// The origin is: Point { x: 0, y: 0 }
501 /// There are a number of `debug_*` methods on [`Formatter`] to help you with manual
502 /// implementations, such as [`debug_struct`][debug_struct].
504 /// `Debug` implementations using either `derive` or the debug builder API
505 /// on [`Formatter`] support pretty printing using the alternate flag: `{:#?}`.
507 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
508 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
510 /// Pretty printing with `#?`:
519 /// let origin = Point { x: 0, y: 0 };
521 /// println!("The origin is: {:#?}", origin);
527 /// The origin is: Point {
532 #[stable(feature = "rust1", since = "1.0.0")]
533 #[rustc_on_unimplemented(
534 on(crate_local, label="`{Self}` cannot be formatted using `:?`; \
535 add `#[derive(Debug)]` or manually implement `{Debug}`"),
536 message="`{Self}` doesn't implement `{Debug}`",
537 label="`{Self}` cannot be formatted using `:?` because it doesn't implement `{Debug}`",
539 #[lang = "debug_trait"]
541 /// Formats the value using the given formatter.
548 /// struct Position {
553 /// impl fmt::Debug for Position {
554 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
555 /// write!(f, "({:?}, {:?})", self.longitude, self.latitude)
559 /// assert_eq!("(1.987, 2.983)".to_owned(),
560 /// format!("{:?}", Position { longitude: 1.987, latitude: 2.983, }));
562 #[stable(feature = "rust1", since = "1.0.0")]
563 fn fmt(&self, f: &mut Formatter) -> Result;
566 /// Format trait for an empty format, `{}`.
568 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
569 /// output, and so cannot be derived.
571 /// [debug]: trait.Debug.html
573 /// For more information on formatters, see [the module-level documentation][module].
575 /// [module]: ../../std/fmt/index.html
579 /// Implementing `Display` on a type:
589 /// impl fmt::Display for Point {
590 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
591 /// write!(f, "({}, {})", self.x, self.y)
595 /// let origin = Point { x: 0, y: 0 };
597 /// println!("The origin is: {}", origin);
599 #[rustc_on_unimplemented(
600 message="`{Self}` doesn't implement `{Display}`",
601 label="`{Self}` cannot be formatted with the default formatter; \
602 try using `:?` instead if you are using a format string",
604 #[stable(feature = "rust1", since = "1.0.0")]
606 /// Formats the value using the given formatter.
613 /// struct Position {
618 /// impl fmt::Display for Position {
619 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
620 /// write!(f, "({}, {})", self.longitude, self.latitude)
624 /// assert_eq!("(1.987, 2.983)".to_owned(),
625 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
627 #[stable(feature = "rust1", since = "1.0.0")]
628 fn fmt(&self, f: &mut Formatter) -> Result;
633 /// The `Octal` trait should format its output as a number in base-8.
635 /// For primitive signed integers (`i8` to `i128`, and `isize`),
636 /// negative values are formatted as the two’s complement representation.
638 /// The alternate flag, `#`, adds a `0o` in front of the output.
640 /// For more information on formatters, see [the module-level documentation][module].
642 /// [module]: ../../std/fmt/index.html
646 /// Basic usage with `i32`:
649 /// let x = 42; // 42 is '52' in octal
651 /// assert_eq!(format!("{:o}", x), "52");
652 /// assert_eq!(format!("{:#o}", x), "0o52");
654 /// assert_eq!(format!("{:o}", -16), "37777777760");
657 /// Implementing `Octal` on a type:
662 /// struct Length(i32);
664 /// impl fmt::Octal for Length {
665 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
666 /// let val = self.0;
668 /// write!(f, "{:o}", val) // delegate to i32's implementation
672 /// let l = Length(9);
674 /// println!("l as octal is: {:o}", l);
676 #[stable(feature = "rust1", since = "1.0.0")]
678 /// Formats the value using the given formatter.
679 #[stable(feature = "rust1", since = "1.0.0")]
680 fn fmt(&self, f: &mut Formatter) -> Result;
685 /// The `Binary` trait should format its output as a number in binary.
687 /// For primitive signed integers (`i8` to `i128`, and `isize`),
688 /// negative values are formatted as the two’s complement representation.
690 /// The alternate flag, `#`, adds a `0b` in front of the output.
692 /// For more information on formatters, see [the module-level documentation][module].
694 /// [module]: ../../std/fmt/index.html
698 /// Basic usage with `i32`:
701 /// let x = 42; // 42 is '101010' in binary
703 /// assert_eq!(format!("{:b}", x), "101010");
704 /// assert_eq!(format!("{:#b}", x), "0b101010");
706 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
709 /// Implementing `Binary` on a type:
714 /// struct Length(i32);
716 /// impl fmt::Binary for Length {
717 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
718 /// let val = self.0;
720 /// write!(f, "{:b}", val) // delegate to i32's implementation
724 /// let l = Length(107);
726 /// println!("l as binary is: {:b}", l);
728 #[stable(feature = "rust1", since = "1.0.0")]
730 /// Formats the value using the given formatter.
731 #[stable(feature = "rust1", since = "1.0.0")]
732 fn fmt(&self, f: &mut Formatter) -> Result;
737 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
740 /// For primitive signed integers (`i8` to `i128`, and `isize`),
741 /// negative values are formatted as the two’s complement representation.
743 /// The alternate flag, `#`, adds a `0x` in front of the output.
745 /// For more information on formatters, see [the module-level documentation][module].
747 /// [module]: ../../std/fmt/index.html
751 /// Basic usage with `i32`:
754 /// let x = 42; // 42 is '2a' in hex
756 /// assert_eq!(format!("{:x}", x), "2a");
757 /// assert_eq!(format!("{:#x}", x), "0x2a");
759 /// assert_eq!(format!("{:x}", -16), "fffffff0");
762 /// Implementing `LowerHex` on a type:
767 /// struct Length(i32);
769 /// impl fmt::LowerHex for Length {
770 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
771 /// let val = self.0;
773 /// write!(f, "{:x}", val) // delegate to i32's implementation
777 /// let l = Length(9);
779 /// println!("l as hex is: {:x}", l);
781 #[stable(feature = "rust1", since = "1.0.0")]
783 /// Formats the value using the given formatter.
784 #[stable(feature = "rust1", since = "1.0.0")]
785 fn fmt(&self, f: &mut Formatter) -> Result;
790 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
793 /// For primitive signed integers (`i8` to `i128`, and `isize`),
794 /// negative values are formatted as the two’s complement representation.
796 /// The alternate flag, `#`, adds a `0x` in front of the output.
798 /// For more information on formatters, see [the module-level documentation][module].
800 /// [module]: ../../std/fmt/index.html
804 /// Basic usage with `i32`:
807 /// let x = 42; // 42 is '2A' in hex
809 /// assert_eq!(format!("{:X}", x), "2A");
810 /// assert_eq!(format!("{:#X}", x), "0x2A");
812 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
815 /// Implementing `UpperHex` on a type:
820 /// struct Length(i32);
822 /// impl fmt::UpperHex for Length {
823 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
824 /// let val = self.0;
826 /// write!(f, "{:X}", val) // delegate to i32's implementation
830 /// let l = Length(9);
832 /// println!("l as hex is: {:X}", l);
834 #[stable(feature = "rust1", since = "1.0.0")]
836 /// Formats the value using the given formatter.
837 #[stable(feature = "rust1", since = "1.0.0")]
838 fn fmt(&self, f: &mut Formatter) -> Result;
843 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
846 /// For more information on formatters, see [the module-level documentation][module].
848 /// [module]: ../../std/fmt/index.html
852 /// Basic usage with `&i32`:
857 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
860 /// Implementing `Pointer` on a type:
865 /// struct Length(i32);
867 /// impl fmt::Pointer for Length {
868 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
869 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
871 /// write!(f, "{:p}", self as *const Length)
875 /// let l = Length(42);
877 /// println!("l is in memory here: {:p}", l);
879 #[stable(feature = "rust1", since = "1.0.0")]
881 /// Formats the value using the given formatter.
882 #[stable(feature = "rust1", since = "1.0.0")]
883 fn fmt(&self, f: &mut Formatter) -> Result;
888 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
890 /// For more information on formatters, see [the module-level documentation][module].
892 /// [module]: ../../std/fmt/index.html
896 /// Basic usage with `i32`:
899 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
901 /// assert_eq!(format!("{:e}", x), "4.2e1");
904 /// Implementing `LowerExp` on a type:
909 /// struct Length(i32);
911 /// impl fmt::LowerExp for Length {
912 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
913 /// let val = self.0;
914 /// write!(f, "{}e1", val / 10)
918 /// let l = Length(100);
920 /// println!("l in scientific notation is: {:e}", l);
922 #[stable(feature = "rust1", since = "1.0.0")]
924 /// Formats the value using the given formatter.
925 #[stable(feature = "rust1", since = "1.0.0")]
926 fn fmt(&self, f: &mut Formatter) -> Result;
931 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
933 /// For more information on formatters, see [the module-level documentation][module].
935 /// [module]: ../../std/fmt/index.html
939 /// Basic usage with `f32`:
942 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
944 /// assert_eq!(format!("{:E}", x), "4.2E1");
947 /// Implementing `UpperExp` on a type:
952 /// struct Length(i32);
954 /// impl fmt::UpperExp for Length {
955 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
956 /// let val = self.0;
957 /// write!(f, "{}E1", val / 10)
961 /// let l = Length(100);
963 /// println!("l in scientific notation is: {:E}", l);
965 #[stable(feature = "rust1", since = "1.0.0")]
967 /// Formats the value using the given formatter.
968 #[stable(feature = "rust1", since = "1.0.0")]
969 fn fmt(&self, f: &mut Formatter) -> Result;
972 /// The `write` function takes an output stream, and an `Arguments` struct
973 /// that can be precompiled with the `format_args!` macro.
975 /// The arguments will be formatted according to the specified format string
976 /// into the output stream provided.
985 /// let mut output = String::new();
986 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
987 /// .expect("Error occurred while trying to write in String");
988 /// assert_eq!(output, "Hello world!");
991 /// Please note that using [`write!`] might be preferable. Example:
994 /// use std::fmt::Write;
996 /// let mut output = String::new();
997 /// write!(&mut output, "Hello {}!", "world")
998 /// .expect("Error occurred while trying to write in String");
999 /// assert_eq!(output, "Hello world!");
1002 /// [`write!`]: ../../std/macro.write.html
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 pub fn write(output: &mut Write, args: Arguments) -> Result {
1005 let mut formatter = Formatter {
1010 align: rt::v1::Alignment::Unknown,
1013 curarg: args.args.iter(),
1016 let mut pieces = args.pieces.iter();
1020 // We can use default formatting parameters for all arguments.
1021 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
1022 formatter.buf.write_str(*piece)?;
1023 (arg.formatter)(arg.value, &mut formatter)?;
1027 // Every spec has a corresponding argument that is preceded by
1029 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
1030 formatter.buf.write_str(*piece)?;
1031 formatter.run(arg)?;
1036 // There can be only one trailing string piece left.
1037 if let Some(piece) = pieces.next() {
1038 formatter.buf.write_str(*piece)?;
1044 impl<'a> Formatter<'a> {
1045 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1046 where 'b: 'c, F: FnOnce(&'b mut (Write+'b)) -> &'c mut (Write+'c)
1049 // We want to change this
1050 buf: wrap(self.buf),
1052 // And preserve these
1057 precision: self.precision,
1059 // These only exist in the struct for the `run` method,
1060 // which won’t be used together with this method.
1061 curarg: self.curarg.clone(),
1066 // First up is the collection of functions used to execute a format string
1067 // at runtime. This consumes all of the compile-time statics generated by
1068 // the format! syntax extension.
1069 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1070 // Fill in the format parameters into the formatter
1071 self.fill = arg.format.fill;
1072 self.align = arg.format.align;
1073 self.flags = arg.format.flags;
1074 self.width = self.getcount(&arg.format.width);
1075 self.precision = self.getcount(&arg.format.precision);
1077 // Extract the correct argument
1078 let value = match arg.position {
1079 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1080 rt::v1::Position::At(i) => self.args[i],
1083 // Then actually do some printing
1084 (value.formatter)(value.value, self)
1087 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1089 rt::v1::Count::Is(n) => Some(n),
1090 rt::v1::Count::Implied => None,
1091 rt::v1::Count::Param(i) => {
1092 self.args[i].as_usize()
1094 rt::v1::Count::NextParam => {
1095 self.curarg.next().and_then(|arg| arg.as_usize())
1100 // Helper methods used for padding and processing formatting arguments that
1101 // all formatting traits can use.
1103 /// Performs the correct padding for an integer which has already been
1104 /// emitted into a str. The str should *not* contain the sign for the
1105 /// integer, that will be added by this method.
1109 /// * is_nonnegative - whether the original integer was either positive or zero.
1110 /// * prefix - if the '#' character (Alternate) is provided, this
1111 /// is the prefix to put in front of the number.
1112 /// * buf - the byte array that the number has been formatted into
1114 /// This function will correctly account for the flags provided as well as
1115 /// the minimum width. It will not take precision into account.
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 pub fn pad_integral(&mut self,
1118 is_nonnegative: bool,
1122 let mut width = buf.len();
1124 let mut sign = None;
1125 if !is_nonnegative {
1126 sign = Some('-'); width += 1;
1127 } else if self.sign_plus() {
1128 sign = Some('+'); width += 1;
1131 let mut prefixed = false;
1132 if self.alternate() {
1133 prefixed = true; width += prefix.chars().count();
1136 // Writes the sign if it exists, and then the prefix if it was requested
1137 let write_prefix = |f: &mut Formatter| {
1138 if let Some(c) = sign {
1139 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
1141 if prefixed { f.buf.write_str(prefix) }
1145 // The `width` field is more of a `min-width` parameter at this point.
1147 // If there's no minimum length requirements then we can just
1150 write_prefix(self)?; self.buf.write_str(buf)
1152 // Check if we're over the minimum width, if so then we can also
1153 // just write the bytes.
1154 Some(min) if width >= min => {
1155 write_prefix(self)?; self.buf.write_str(buf)
1157 // The sign and prefix goes before the padding if the fill character
1159 Some(min) if self.sign_aware_zero_pad() => {
1161 self.align = rt::v1::Alignment::Right;
1162 write_prefix(self)?;
1163 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1164 f.buf.write_str(buf)
1167 // Otherwise, the sign and prefix goes after the padding
1169 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1170 write_prefix(f)?; f.buf.write_str(buf)
1176 /// This function takes a string slice and emits it to the internal buffer
1177 /// after applying the relevant formatting flags specified. The flags
1178 /// recognized for generic strings are:
1180 /// * width - the minimum width of what to emit
1181 /// * fill/align - what to emit and where to emit it if the string
1182 /// provided needs to be padded
1183 /// * precision - the maximum length to emit, the string is truncated if it
1184 /// is longer than this length
1186 /// Notably this function ignores the `flag` parameters.
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 pub fn pad(&mut self, s: &str) -> Result {
1189 // Make sure there's a fast path up front
1190 if self.width.is_none() && self.precision.is_none() {
1191 return self.buf.write_str(s);
1193 // The `precision` field can be interpreted as a `max-width` for the
1194 // string being formatted.
1195 let s = if let Some(max) = self.precision {
1196 // If our string is longer that the precision, then we must have
1197 // truncation. However other flags like `fill`, `width` and `align`
1198 // must act as always.
1199 if let Some((i, _)) = s.char_indices().skip(max).next() {
1207 // The `width` field is more of a `min-width` parameter at this point.
1209 // If we're under the maximum length, and there's no minimum length
1210 // requirements, then we can just emit the string
1211 None => self.buf.write_str(s),
1212 // If we're under the maximum width, check if we're over the minimum
1213 // width, if so it's as easy as just emitting the string.
1214 Some(width) if s.chars().count() >= width => {
1215 self.buf.write_str(s)
1217 // If we're under both the maximum and the minimum width, then fill
1218 // up the minimum width with the specified string + some alignment.
1220 let align = rt::v1::Alignment::Left;
1221 self.with_padding(width - s.chars().count(), align, |me| {
1228 /// Runs a callback, emitting the correct padding either before or
1229 /// afterwards depending on whether right or left alignment is requested.
1230 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1232 where F: FnOnce(&mut Formatter) -> Result,
1234 let align = match self.align {
1235 rt::v1::Alignment::Unknown => default,
1239 let (pre_pad, post_pad) = match align {
1240 rt::v1::Alignment::Left => (0, padding),
1241 rt::v1::Alignment::Right |
1242 rt::v1::Alignment::Unknown => (padding, 0),
1243 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1246 let mut fill = [0; 4];
1247 let fill = self.fill.encode_utf8(&mut fill);
1249 for _ in 0..pre_pad {
1250 self.buf.write_str(fill)?;
1255 for _ in 0..post_pad {
1256 self.buf.write_str(fill)?;
1262 /// Takes the formatted parts and applies the padding.
1263 /// Assumes that the caller already has rendered the parts with required precision,
1264 /// so that `self.precision` can be ignored.
1265 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1266 if let Some(mut width) = self.width {
1267 // for the sign-aware zero padding, we render the sign first and
1268 // behave as if we had no sign from the beginning.
1269 let mut formatted = formatted.clone();
1270 let old_fill = self.fill;
1271 let old_align = self.align;
1272 let mut align = old_align;
1273 if self.sign_aware_zero_pad() {
1274 // a sign always goes first
1275 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1276 self.buf.write_str(sign)?;
1278 // remove the sign from the formatted parts
1279 formatted.sign = b"";
1280 width = if width < sign.len() { 0 } else { width - sign.len() };
1281 align = rt::v1::Alignment::Right;
1283 self.align = rt::v1::Alignment::Right;
1286 // remaining parts go through the ordinary padding process.
1287 let len = formatted.len();
1288 let ret = if width <= len { // no padding
1289 self.write_formatted_parts(&formatted)
1291 self.with_padding(width - len, align, |f| {
1292 f.write_formatted_parts(&formatted)
1295 self.fill = old_fill;
1296 self.align = old_align;
1299 // this is the common case and we take a shortcut
1300 self.write_formatted_parts(formatted)
1304 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1305 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1306 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1309 if !formatted.sign.is_empty() {
1310 write_bytes(self.buf, formatted.sign)?;
1312 for part in formatted.parts {
1314 flt2dec::Part::Zero(mut nzeroes) => {
1315 const ZEROES: &'static str = // 64 zeroes
1316 "0000000000000000000000000000000000000000000000000000000000000000";
1317 while nzeroes > ZEROES.len() {
1318 self.buf.write_str(ZEROES)?;
1319 nzeroes -= ZEROES.len();
1322 self.buf.write_str(&ZEROES[..nzeroes])?;
1325 flt2dec::Part::Num(mut v) => {
1327 let len = part.len();
1328 for c in s[..len].iter_mut().rev() {
1329 *c = b'0' + (v % 10) as u8;
1332 write_bytes(self.buf, &s[..len])?;
1334 flt2dec::Part::Copy(buf) => {
1335 write_bytes(self.buf, buf)?;
1342 /// Writes some data to the underlying buffer contained within this
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 pub fn write_str(&mut self, data: &str) -> Result {
1346 self.buf.write_str(data)
1349 /// Writes some formatted information into this instance
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1352 write(self.buf, fmt)
1355 /// Flags for formatting
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 #[rustc_deprecated(since = "1.24.0",
1358 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1359 or `sign_aware_zero_pad` methods instead")]
1360 pub fn flags(&self) -> u32 { self.flags }
1362 /// Character used as 'fill' whenever there is alignment
1363 #[stable(feature = "fmt_flags", since = "1.5.0")]
1364 pub fn fill(&self) -> char { self.fill }
1366 /// Flag indicating what form of alignment was requested
1367 #[unstable(feature = "fmt_flags_align", reason = "method was just created",
1369 pub fn align(&self) -> Alignment {
1371 rt::v1::Alignment::Left => Alignment::Left,
1372 rt::v1::Alignment::Right => Alignment::Right,
1373 rt::v1::Alignment::Center => Alignment::Center,
1374 rt::v1::Alignment::Unknown => Alignment::Unknown,
1378 /// Optionally specified integer width that the output should be
1379 #[stable(feature = "fmt_flags", since = "1.5.0")]
1380 pub fn width(&self) -> Option<usize> { self.width }
1382 /// Optionally specified precision for numeric types
1383 #[stable(feature = "fmt_flags", since = "1.5.0")]
1384 pub fn precision(&self) -> Option<usize> { self.precision }
1386 /// Determines if the `+` flag was specified.
1387 #[stable(feature = "fmt_flags", since = "1.5.0")]
1388 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1390 /// Determines if the `-` flag was specified.
1391 #[stable(feature = "fmt_flags", since = "1.5.0")]
1392 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1394 /// Determines if the `#` flag was specified.
1395 #[stable(feature = "fmt_flags", since = "1.5.0")]
1396 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1398 /// Determines if the `0` flag was specified.
1399 #[stable(feature = "fmt_flags", since = "1.5.0")]
1400 pub fn sign_aware_zero_pad(&self) -> bool {
1401 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1404 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1405 /// [`fmt::Debug`] implementations for structs.
1407 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1408 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1420 /// impl fmt::Debug for Foo {
1421 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1422 /// fmt.debug_struct("Foo")
1423 /// .field("bar", &self.bar)
1424 /// .field("baz", &self.baz)
1429 /// // prints "Foo { bar: 10, baz: "Hello World" }"
1430 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1432 #[stable(feature = "debug_builders", since = "1.2.0")]
1433 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1434 builders::debug_struct_new(self, name)
1437 /// Creates a `DebugTuple` builder designed to assist with creation of
1438 /// `fmt::Debug` implementations for tuple structs.
1445 /// struct Foo(i32, String);
1447 /// impl fmt::Debug for Foo {
1448 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1449 /// fmt.debug_tuple("Foo")
1456 /// // prints "Foo(10, "Hello World")"
1457 /// println!("{:?}", Foo(10, "Hello World".to_string()));
1459 #[stable(feature = "debug_builders", since = "1.2.0")]
1460 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1461 builders::debug_tuple_new(self, name)
1464 /// Creates a `DebugList` builder designed to assist with creation of
1465 /// `fmt::Debug` implementations for list-like structures.
1472 /// struct Foo(Vec<i32>);
1474 /// impl fmt::Debug for Foo {
1475 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1476 /// fmt.debug_list().entries(self.0.iter()).finish()
1480 /// // prints "[10, 11]"
1481 /// println!("{:?}", Foo(vec![10, 11]));
1483 #[stable(feature = "debug_builders", since = "1.2.0")]
1484 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1485 builders::debug_list_new(self)
1488 /// Creates a `DebugSet` builder designed to assist with creation of
1489 /// `fmt::Debug` implementations for set-like structures.
1496 /// struct Foo(Vec<i32>);
1498 /// impl fmt::Debug for Foo {
1499 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1500 /// fmt.debug_set().entries(self.0.iter()).finish()
1504 /// // prints "{10, 11}"
1505 /// println!("{:?}", Foo(vec![10, 11]));
1507 #[stable(feature = "debug_builders", since = "1.2.0")]
1508 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1509 builders::debug_set_new(self)
1512 /// Creates a `DebugMap` builder designed to assist with creation of
1513 /// `fmt::Debug` implementations for map-like structures.
1520 /// struct Foo(Vec<(String, i32)>);
1522 /// impl fmt::Debug for Foo {
1523 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1524 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1528 /// // prints "{"A": 10, "B": 11}"
1529 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1531 #[stable(feature = "debug_builders", since = "1.2.0")]
1532 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1533 builders::debug_map_new(self)
1537 #[stable(since = "1.2.0", feature = "formatter_write")]
1538 impl<'a> Write for Formatter<'a> {
1539 fn write_str(&mut self, s: &str) -> Result {
1540 self.buf.write_str(s)
1543 fn write_char(&mut self, c: char) -> Result {
1544 self.buf.write_char(c)
1547 fn write_fmt(&mut self, args: Arguments) -> Result {
1548 write(self.buf, args)
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 impl Display for Error {
1554 fn fmt(&self, f: &mut Formatter) -> Result {
1555 Display::fmt("an error occurred when formatting an argument", f)
1559 // Implementations of the core formatting traits
1561 macro_rules! fmt_refs {
1562 ($($tr:ident),*) => {
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 impl<'a, T: ?Sized + $tr> $tr for &'a T {
1566 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1570 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1576 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1578 #[unstable(feature = "never_type", issue = "35121")]
1580 fn fmt(&self, _: &mut Formatter) -> Result {
1585 #[unstable(feature = "never_type", issue = "35121")]
1586 impl Display for ! {
1587 fn fmt(&self, _: &mut Formatter) -> Result {
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl Debug for bool {
1595 fn fmt(&self, f: &mut Formatter) -> Result {
1596 Display::fmt(self, f)
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl Display for bool {
1602 fn fmt(&self, f: &mut Formatter) -> Result {
1603 Display::fmt(if *self { "true" } else { "false" }, f)
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 impl Debug for str {
1609 fn fmt(&self, f: &mut Formatter) -> Result {
1612 for (i, c) in self.char_indices() {
1613 let esc = c.escape_debug();
1614 // If char needs escaping, flush backlog so far and write, else skip
1616 f.write_str(&self[from..i])?;
1620 from = i + c.len_utf8();
1623 f.write_str(&self[from..])?;
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 impl Display for str {
1630 fn fmt(&self, f: &mut Formatter) -> Result {
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 impl Debug for char {
1637 fn fmt(&self, f: &mut Formatter) -> Result {
1638 f.write_char('\'')?;
1639 for c in self.escape_debug() {
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl Display for char {
1648 fn fmt(&self, f: &mut Formatter) -> Result {
1649 if f.width.is_none() && f.precision.is_none() {
1652 f.pad(self.encode_utf8(&mut [0; 4]))
1657 #[stable(feature = "rust1", since = "1.0.0")]
1658 impl<T: ?Sized> Pointer for *const T {
1659 fn fmt(&self, f: &mut Formatter) -> Result {
1660 let old_width = f.width;
1661 let old_flags = f.flags;
1663 // The alternate flag is already treated by LowerHex as being special-
1664 // it denotes whether to prefix with 0x. We use it to work out whether
1665 // or not to zero extend, and then unconditionally set it to get the
1668 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1670 if let None = f.width {
1671 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
1674 f.flags |= 1 << (FlagV1::Alternate as u32);
1676 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
1678 f.width = old_width;
1679 f.flags = old_flags;
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 impl<T: ?Sized> Pointer for *mut T {
1687 fn fmt(&self, f: &mut Formatter) -> Result {
1688 Pointer::fmt(&(*self as *const T), f)
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 impl<'a, T: ?Sized> Pointer for &'a T {
1694 fn fmt(&self, f: &mut Formatter) -> Result {
1695 Pointer::fmt(&(*self as *const T), f)
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl<'a, T: ?Sized> Pointer for &'a mut T {
1701 fn fmt(&self, f: &mut Formatter) -> Result {
1702 Pointer::fmt(&(&**self as *const T), f)
1706 // Implementation of Display/Debug for various core types
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 impl<T: ?Sized> Debug for *const T {
1710 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1712 #[stable(feature = "rust1", since = "1.0.0")]
1713 impl<T: ?Sized> Debug for *mut T {
1714 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1718 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1721 macro_rules! tuple {
1723 ( $($name:ident,)+ ) => (
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
1726 #[allow(non_snake_case, unused_assignments, deprecated)]
1727 fn fmt(&self, f: &mut Formatter) -> Result {
1728 let mut builder = f.debug_tuple("");
1729 let ($(ref $name,)*) = *self;
1731 builder.field(&$name);
1737 peel! { $($name,)* }
1741 macro_rules! last_type {
1742 ($a:ident,) => { $a };
1743 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
1746 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1748 #[stable(feature = "rust1", since = "1.0.0")]
1749 impl<T: Debug> Debug for [T] {
1750 fn fmt(&self, f: &mut Formatter) -> Result {
1751 f.debug_list().entries(self.iter()).finish()
1755 #[stable(feature = "rust1", since = "1.0.0")]
1758 fn fmt(&self, f: &mut Formatter) -> Result {
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl<T: ?Sized> Debug for PhantomData<T> {
1764 fn fmt(&self, f: &mut Formatter) -> Result {
1765 f.pad("PhantomData")
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 impl<T: Copy + Debug> Debug for Cell<T> {
1771 fn fmt(&self, f: &mut Formatter) -> Result {
1772 f.debug_struct("Cell")
1773 .field("value", &self.get())
1778 #[stable(feature = "rust1", since = "1.0.0")]
1779 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1780 fn fmt(&self, f: &mut Formatter) -> Result {
1781 match self.try_borrow() {
1783 f.debug_struct("RefCell")
1784 .field("value", &borrow)
1788 // The RefCell is mutably borrowed so we can't look at its value
1789 // here. Show a placeholder instead.
1790 struct BorrowedPlaceholder;
1792 impl Debug for BorrowedPlaceholder {
1793 fn fmt(&self, f: &mut Formatter) -> Result {
1794 f.write_str("<borrowed>")
1798 f.debug_struct("RefCell")
1799 .field("value", &BorrowedPlaceholder)
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1808 fn fmt(&self, f: &mut Formatter) -> Result {
1809 Debug::fmt(&**self, f)
1813 #[stable(feature = "rust1", since = "1.0.0")]
1814 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1815 fn fmt(&self, f: &mut Formatter) -> Result {
1816 Debug::fmt(&*(self.deref()), f)
1820 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1821 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
1822 fn fmt(&self, f: &mut Formatter) -> Result {
1827 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1828 // it's a lot easier than creating all of the rt::Piece structures here.