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, BorrowState}
;
16 use marker
::PhantomData
;
24 #[unstable(feature = "fmt_flags_align", issue = "27726")]
25 /// Possible alignments returned by `Formatter::align`
28 /// Indication that contents should be left-aligned.
30 /// Indication that contents should be right-aligned.
32 /// Indication that contents should be center-aligned.
34 /// No alignment was requested.
38 #[stable(feature = "debug_builders", since = "1.2.0")]
39 pub use self::builders
::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap}
;
44 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
51 #[stable(feature = "rust1", since = "1.0.0")]
52 /// The type returned by formatter methods.
53 pub type Result
= result
::Result
<(), Error
>;
55 /// The error type which is returned from formatting a message into a stream.
57 /// This type does not support transmission of an error other than that an error
58 /// occurred. Any extra information must be arranged to be transmitted through
60 #[stable(feature = "rust1", since = "1.0.0")]
61 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
64 /// A collection of methods that are required to format a message into a stream.
66 /// This trait is the type which this modules requires when formatting
67 /// information. This is similar to the standard library's `io::Write` trait,
68 /// but it is only intended for use in libcore.
70 /// This trait should generally not be implemented by consumers of the standard
71 /// library. The `write!` macro accepts an instance of `io::Write`, and the
72 /// `io::Write` trait is favored over implementing this trait.
73 #[stable(feature = "rust1", since = "1.0.0")]
75 /// Writes a slice of bytes into this writer, returning whether the write
78 /// This method can only succeed if the entire byte slice was successfully
79 /// written, and this method will not return until all data has been
80 /// written or an error occurs.
84 /// This function will return an instance of `Error` on error.
85 #[stable(feature = "rust1", since = "1.0.0")]
86 fn write_str(&mut self, s
: &str) -> Result
;
88 /// Writes a `char` into this writer, returning whether the write succeeded.
90 /// A single `char` may be encoded as more than one byte.
91 /// This method can only succeed if the entire byte sequence was successfully
92 /// written, and this method will not return until all data has been
93 /// written or an error occurs.
97 /// This function will return an instance of `Error` on error.
98 #[stable(feature = "fmt_write_char", since = "1.1.0")]
99 fn write_char(&mut self, c
: char) -> Result
{
100 self.write_str(unsafe {
101 str::from_utf8_unchecked(c
.encode_utf8().as_slice())
105 /// Glue for usage of the `write!` macro with implementors of this trait.
107 /// This method should generally not be invoked manually, but rather through
108 /// the `write!` macro itself.
109 #[stable(feature = "rust1", since = "1.0.0")]
110 fn write_fmt(&mut self, args
: Arguments
) -> Result
{
111 // This Adapter is needed to allow `self` (of type `&mut
112 // Self`) to be cast to a Write (below) without
113 // requiring a `Sized` bound.
114 struct Adapter
<'a
,T
: ?Sized
+'a
>(&'a
mut T
);
116 impl<'a
, T
: ?Sized
> Write
for Adapter
<'a
, T
>
119 fn write_str(&mut self, s
: &str) -> Result
{
123 fn write_char(&mut self, c
: char) -> Result
{
127 fn write_fmt(&mut self, args
: Arguments
) -> Result
{
128 self.0.write_fmt(args
)
132 write(&mut Adapter(self), args
)
136 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
137 impl<'a
, W
: Write
+ ?Sized
> Write
for &'a
mut W
{
138 fn write_str(&mut self, s
: &str) -> Result
{
139 (**self).write_str(s
)
142 fn write_char(&mut self, c
: char) -> Result
{
143 (**self).write_char(c
)
146 fn write_fmt(&mut self, args
: Arguments
) -> Result
{
147 (**self).write_fmt(args
)
151 /// A struct to represent both where to emit formatting strings to and how they
152 /// should be formatted. A mutable version of this is passed to all formatting
154 #[allow(missing_debug_implementations)]
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub struct Formatter
<'a
> {
159 align
: rt
::v1
::Alignment
,
160 width
: Option
<usize>,
161 precision
: Option
<usize>,
163 buf
: &'a
mut (Write
+'a
),
164 curarg
: slice
::Iter
<'a
, ArgumentV1
<'a
>>,
165 args
: &'a
[ArgumentV1
<'a
>],
168 // NB. Argument is essentially an optimized partially applied formatting function,
169 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
173 /// This struct represents the generic "argument" which is taken by the Xprintf
174 /// family of functions. It contains a function to format the given value. At
175 /// compile time it is ensured that the function and the value have the correct
176 /// types, and then this struct is used to canonicalize arguments to one type.
178 #[allow(missing_debug_implementations)]
179 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
182 pub struct ArgumentV1
<'a
> {
184 formatter
: fn(&Void
, &mut Formatter
) -> Result
,
187 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
189 impl<'a
> Clone
for ArgumentV1
<'a
> {
190 fn clone(&self) -> ArgumentV1
<'a
> {
195 impl<'a
> ArgumentV1
<'a
> {
197 fn show_usize(x
: &usize, f
: &mut Formatter
) -> Result
{
202 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
204 pub fn new
<'b
, T
>(x
: &'b T
,
205 f
: fn(&T
, &mut Formatter
) -> Result
) -> ArgumentV1
<'b
> {
208 formatter
: mem
::transmute(f
),
209 value
: mem
::transmute(x
)
215 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
217 pub fn from_usize(x
: &usize) -> ArgumentV1
{
218 ArgumentV1
::new(x
, ArgumentV1
::show_usize
)
221 fn as_usize(&self) -> Option
<usize> {
222 if self.formatter
as usize == ArgumentV1
::show_usize
as usize {
223 Some(unsafe { *(self.value as *const _ as *const usize) }
)
230 // flags available in the v1 format of format_args
231 #[derive(Copy, Clone)]
232 #[allow(dead_code)] // SignMinus isn't currently used
233 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
235 impl<'a
> Arguments
<'a
> {
236 /// When using the format_args!() macro, this function is used to generate the
237 /// Arguments structure.
238 #[doc(hidden)] #[inline]
239 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
241 pub fn new_v1(pieces
: &'a
[&'a
str],
242 args
: &'a
[ArgumentV1
<'a
>]) -> Arguments
<'a
> {
250 /// This function is used to specify nonstandard formatting parameters.
251 /// The `pieces` array must be at least as long as `fmt` to construct
252 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
253 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
254 /// created with `argumentusize`. However, failing to do so doesn't cause
255 /// unsafety, but will ignore invalid .
256 #[doc(hidden)] #[inline]
257 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
259 pub fn new_v1_formatted(pieces
: &'a
[&'a
str],
260 args
: &'a
[ArgumentV1
<'a
>],
261 fmt
: &'a
[rt
::v1
::Argument
]) -> Arguments
<'a
> {
270 /// This structure represents a safely precompiled version of a format string
271 /// and its arguments. This cannot be generated at runtime because it cannot
272 /// safely be done so, so no constructors are given and the fields are private
273 /// to prevent modification.
275 /// The [`format_args!`] macro will safely create an instance of this structure
276 /// and pass it to a function or closure, passed as the first argument. The
277 /// macro validates the format string at compile-time so usage of the [`write`]
278 /// and [`format`] functions can be safely performed.
280 /// [`format_args!`]: ../../std/macro.format_args.html
281 /// [`format`]: ../../std/fmt/fn.format.html
282 /// [`write`]: ../../std/fmt/fn.write.html
283 #[stable(feature = "rust1", since = "1.0.0")]
284 #[derive(Copy, Clone)]
285 pub struct Arguments
<'a
> {
286 // Format string pieces to print.
287 pieces
: &'a
[&'a
str],
289 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
290 fmt
: Option
<&'a
[rt
::v1
::Argument
]>,
292 // Dynamic arguments for interpolation, to be interleaved with string
293 // pieces. (Every argument is preceded by a string piece.)
294 args
: &'a
[ArgumentV1
<'a
>],
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl<'a
> Debug
for Arguments
<'a
> {
299 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
300 Display
::fmt(self, fmt
)
304 #[stable(feature = "rust1", since = "1.0.0")]
305 impl<'a
> Display
for Arguments
<'a
> {
306 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
307 write(fmt
.buf
, *self)
311 /// Format trait for the `?` character.
313 /// `Debug` should format the output in a programmer-facing, debugging context.
315 /// Generally speaking, you should just `derive` a `Debug` implementation.
317 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
319 /// For more information on formatters, see [the module-level documentation][module].
321 /// [module]: ../../std/fmt/index.html
323 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
324 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
325 /// comma-separated list of each field's name and `Debug` value, then `}`. For
326 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
327 /// `Debug` values of the fields, then `)`.
331 /// Deriving an implementation:
340 /// let origin = Point { x: 0, y: 0 };
342 /// println!("The origin is: {:?}", origin);
345 /// Manually implementing:
355 /// impl fmt::Debug for Point {
356 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
357 /// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
361 /// let origin = Point { x: 0, y: 0 };
363 /// println!("The origin is: {:?}", origin);
369 /// The origin is: Point { x: 0, y: 0 }
372 /// There are a number of `debug_*` methods on `Formatter` to help you with manual
373 /// implementations, such as [`debug_struct`][debug_struct].
375 /// `Debug` implementations using either `derive` or the debug builder API
376 /// on `Formatter` support pretty printing using the alternate flag: `{:#?}`.
378 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
380 /// Pretty printing with `#?`:
389 /// let origin = Point { x: 0, y: 0 };
391 /// println!("The origin is: {:#?}", origin);
397 /// The origin is: Point {
402 #[stable(feature = "rust1", since = "1.0.0")]
403 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
404 defined in your crate, add `#[derive(Debug)]` or \
405 manually implement it"]
406 #[lang = "debug_trait"]
408 /// Formats the value using the given formatter.
409 #[stable(feature = "rust1", since = "1.0.0")]
410 fn fmt(&self, &mut Formatter
) -> Result
;
413 /// Format trait for an empty format, `{}`.
415 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
416 /// output, and so cannot be derived.
418 /// [debug]: trait.Debug.html
420 /// For more information on formatters, see [the module-level documentation][module].
422 /// [module]: ../../std/fmt/index.html
426 /// Implementing `Display` on a type:
436 /// impl fmt::Display for Point {
437 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
438 /// write!(f, "({}, {})", self.x, self.y)
442 /// let origin = Point { x: 0, y: 0 };
444 /// println!("The origin is: {}", origin);
446 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
447 formatter; try using `:?` instead if you are using \
449 #[stable(feature = "rust1", since = "1.0.0")]
451 /// Formats the value using the given formatter.
452 #[stable(feature = "rust1", since = "1.0.0")]
453 fn fmt(&self, &mut Formatter
) -> Result
;
456 /// Format trait for the `o` character.
458 /// The `Octal` trait should format its output as a number in base-8.
460 /// The alternate flag, `#`, adds a `0o` in front of the output.
462 /// For more information on formatters, see [the module-level documentation][module].
464 /// [module]: ../../std/fmt/index.html
468 /// Basic usage with `i32`:
471 /// let x = 42; // 42 is '52' in octal
473 /// assert_eq!(format!("{:o}", x), "52");
474 /// assert_eq!(format!("{:#o}", x), "0o52");
477 /// Implementing `Octal` on a type:
482 /// struct Length(i32);
484 /// impl fmt::Octal for Length {
485 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
486 /// let val = self.0;
488 /// write!(f, "{:o}", val) // delegate to i32's implementation
492 /// let l = Length(9);
494 /// println!("l as octal is: {:o}", l);
496 #[stable(feature = "rust1", since = "1.0.0")]
498 /// Formats the value using the given formatter.
499 #[stable(feature = "rust1", since = "1.0.0")]
500 fn fmt(&self, &mut Formatter
) -> Result
;
503 /// Format trait for the `b` character.
505 /// The `Binary` trait should format its output as a number in binary.
507 /// The alternate flag, `#`, adds a `0b` in front of the output.
509 /// For more information on formatters, see [the module-level documentation][module].
511 /// [module]: ../../std/fmt/index.html
515 /// Basic usage with `i32`:
518 /// let x = 42; // 42 is '101010' in binary
520 /// assert_eq!(format!("{:b}", x), "101010");
521 /// assert_eq!(format!("{:#b}", x), "0b101010");
524 /// Implementing `Binary` on a type:
529 /// struct Length(i32);
531 /// impl fmt::Binary for Length {
532 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
533 /// let val = self.0;
535 /// write!(f, "{:b}", val) // delegate to i32's implementation
539 /// let l = Length(107);
541 /// println!("l as binary is: {:b}", l);
543 #[stable(feature = "rust1", since = "1.0.0")]
545 /// Formats the value using the given formatter.
546 #[stable(feature = "rust1", since = "1.0.0")]
547 fn fmt(&self, &mut Formatter
) -> Result
;
550 /// Format trait for the `x` character.
552 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
555 /// The alternate flag, `#`, adds a `0x` in front of the output.
557 /// For more information on formatters, see [the module-level documentation][module].
559 /// [module]: ../../std/fmt/index.html
563 /// Basic usage with `i32`:
566 /// let x = 42; // 42 is '2a' in hex
568 /// assert_eq!(format!("{:x}", x), "2a");
569 /// assert_eq!(format!("{:#x}", x), "0x2a");
572 /// Implementing `LowerHex` on a type:
577 /// struct Length(i32);
579 /// impl fmt::LowerHex for Length {
580 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
581 /// let val = self.0;
583 /// write!(f, "{:x}", val) // delegate to i32's implementation
587 /// let l = Length(9);
589 /// println!("l as hex is: {:x}", l);
591 #[stable(feature = "rust1", since = "1.0.0")]
593 /// Formats the value using the given formatter.
594 #[stable(feature = "rust1", since = "1.0.0")]
595 fn fmt(&self, &mut Formatter
) -> Result
;
598 /// Format trait for the `X` character.
600 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
603 /// The alternate flag, `#`, adds a `0x` in front of the output.
605 /// For more information on formatters, see [the module-level documentation][module].
607 /// [module]: ../../std/fmt/index.html
611 /// Basic usage with `i32`:
614 /// let x = 42; // 42 is '2A' in hex
616 /// assert_eq!(format!("{:X}", x), "2A");
617 /// assert_eq!(format!("{:#X}", x), "0x2A");
620 /// Implementing `UpperHex` on a type:
625 /// struct Length(i32);
627 /// impl fmt::UpperHex for Length {
628 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
629 /// let val = self.0;
631 /// write!(f, "{:X}", val) // delegate to i32's implementation
635 /// let l = Length(9);
637 /// println!("l as hex is: {:X}", l);
639 #[stable(feature = "rust1", since = "1.0.0")]
641 /// Formats the value using the given formatter.
642 #[stable(feature = "rust1", since = "1.0.0")]
643 fn fmt(&self, &mut Formatter
) -> Result
;
646 /// Format trait for the `p` character.
648 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
651 /// For more information on formatters, see [the module-level documentation][module].
653 /// [module]: ../../std/fmt/index.html
657 /// Basic usage with `&i32`:
662 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
665 /// Implementing `Pointer` on a type:
670 /// struct Length(i32);
672 /// impl fmt::Pointer for Length {
673 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
674 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
676 /// write!(f, "{:p}", self as *const Length)
680 /// let l = Length(42);
682 /// println!("l is in memory here: {:p}", l);
684 #[stable(feature = "rust1", since = "1.0.0")]
686 /// Formats the value using the given formatter.
687 #[stable(feature = "rust1", since = "1.0.0")]
688 fn fmt(&self, &mut Formatter
) -> Result
;
691 /// Format trait for the `e` character.
693 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
695 /// For more information on formatters, see [the module-level documentation][module].
697 /// [module]: ../../std/fmt/index.html
701 /// Basic usage with `i32`:
704 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
706 /// assert_eq!(format!("{:e}", x), "4.2e1");
709 /// Implementing `LowerExp` on a type:
714 /// struct Length(i32);
716 /// impl fmt::LowerExp for Length {
717 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
718 /// let val = self.0;
719 /// write!(f, "{}e1", val / 10)
723 /// let l = Length(100);
725 /// println!("l in scientific notation is: {:e}", l);
727 #[stable(feature = "rust1", since = "1.0.0")]
729 /// Formats the value using the given formatter.
730 #[stable(feature = "rust1", since = "1.0.0")]
731 fn fmt(&self, &mut Formatter
) -> Result
;
734 /// Format trait for the `E` character.
736 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
738 /// For more information on formatters, see [the module-level documentation][module].
740 /// [module]: ../../std/fmt/index.html
744 /// Basic usage with `f32`:
747 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
749 /// assert_eq!(format!("{:E}", x), "4.2E1");
752 /// Implementing `UpperExp` on a type:
757 /// struct Length(i32);
759 /// impl fmt::UpperExp for Length {
760 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
761 /// let val = self.0;
762 /// write!(f, "{}E1", val / 10)
766 /// let l = Length(100);
768 /// println!("l in scientific notation is: {:E}", l);
770 #[stable(feature = "rust1", since = "1.0.0")]
772 /// Formats the value using the given formatter.
773 #[stable(feature = "rust1", since = "1.0.0")]
774 fn fmt(&self, &mut Formatter
) -> Result
;
777 /// The `write` function takes an output stream, a precompiled format string,
778 /// and a list of arguments. The arguments will be formatted according to the
779 /// specified format string into the output stream provided.
783 /// * output - the buffer to write output to
784 /// * args - the precompiled arguments generated by `format_args!`
793 /// let mut output = String::new();
794 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
795 /// .expect("Error occurred while trying to write in String");
796 /// assert_eq!(output, "Hello world!");
799 /// Please note that using [`write!`][write_macro] might be preferrable. Example:
802 /// use std::fmt::Write;
804 /// let mut output = String::new();
805 /// write!(&mut output, "Hello {}!", "world")
806 /// .expect("Error occurred while trying to write in String");
807 /// assert_eq!(output, "Hello world!");
810 /// [write_macro]: ../../std/macro.write!.html
811 #[stable(feature = "rust1", since = "1.0.0")]
812 pub fn write(output
: &mut Write
, args
: Arguments
) -> Result
{
813 let mut formatter
= Formatter
{
818 align
: rt
::v1
::Alignment
::Unknown
,
821 curarg
: args
.args
.iter(),
824 let mut pieces
= args
.pieces
.iter();
828 // We can use default formatting parameters for all arguments.
829 for (arg
, piece
) in args
.args
.iter().zip(pieces
.by_ref()) {
830 formatter
.buf
.write_str(*piece
)?
;
831 (arg
.formatter
)(arg
.value
, &mut formatter
)?
;
835 // Every spec has a corresponding argument that is preceded by
837 for (arg
, piece
) in fmt
.iter().zip(pieces
.by_ref()) {
838 formatter
.buf
.write_str(*piece
)?
;
844 // There can be only one trailing string piece left.
845 if let Some(piece
) = pieces
.next() {
846 formatter
.buf
.write_str(*piece
)?
;
852 impl<'a
> Formatter
<'a
> {
854 // First up is the collection of functions used to execute a format string
855 // at runtime. This consumes all of the compile-time statics generated by
856 // the format! syntax extension.
857 fn run(&mut self, arg
: &rt
::v1
::Argument
) -> Result
{
858 // Fill in the format parameters into the formatter
859 self.fill
= arg
.format
.fill
;
860 self.align
= arg
.format
.align
;
861 self.flags
= arg
.format
.flags
;
862 self.width
= self.getcount(&arg
.format
.width
);
863 self.precision
= self.getcount(&arg
.format
.precision
);
865 // Extract the correct argument
866 let value
= match arg
.position
{
867 rt
::v1
::Position
::Next
=> { *self.curarg.next().unwrap() }
868 rt
::v1
::Position
::At(i
) => self.args
[i
],
871 // Then actually do some printing
872 (value
.formatter
)(value
.value
, self)
875 fn getcount(&mut self, cnt
: &rt
::v1
::Count
) -> Option
<usize> {
877 rt
::v1
::Count
::Is(n
) => Some(n
),
878 rt
::v1
::Count
::Implied
=> None
,
879 rt
::v1
::Count
::Param(i
) => {
880 self.args
[i
].as_usize()
882 rt
::v1
::Count
::NextParam
=> {
883 self.curarg
.next().and_then(|arg
| arg
.as_usize())
888 // Helper methods used for padding and processing formatting arguments that
889 // all formatting traits can use.
891 /// Performs the correct padding for an integer which has already been
892 /// emitted into a str. The str should *not* contain the sign for the
893 /// integer, that will be added by this method.
897 /// * is_nonnegative - whether the original integer was either positive or zero.
898 /// * prefix - if the '#' character (Alternate) is provided, this
899 /// is the prefix to put in front of the number.
900 /// * buf - the byte array that the number has been formatted into
902 /// This function will correctly account for the flags provided as well as
903 /// the minimum width. It will not take precision into account.
904 #[stable(feature = "rust1", since = "1.0.0")]
905 pub fn pad_integral(&mut self,
906 is_nonnegative
: bool
,
910 let mut width
= buf
.len();
914 sign
= Some('
-'
); width
+= 1;
915 } else if self.sign_plus() {
916 sign
= Some('
+'
); width
+= 1;
919 let mut prefixed
= false;
920 if self.alternate() {
921 prefixed
= true; width
+= prefix
.chars().count();
924 // Writes the sign if it exists, and then the prefix if it was requested
925 let write_prefix
= |f
: &mut Formatter
| {
926 if let Some(c
) = sign
{
927 f
.buf
.write_str(unsafe {
928 str::from_utf8_unchecked(c
.encode_utf8().as_slice())
931 if prefixed { f.buf.write_str(prefix) }
935 // The `width` field is more of a `min-width` parameter at this point.
937 // If there's no minimum length requirements then we can just
940 write_prefix(self)?
; self.buf
.write_str(buf
)
942 // Check if we're over the minimum width, if so then we can also
943 // just write the bytes.
944 Some(min
) if width
>= min
=> {
945 write_prefix(self)?
; self.buf
.write_str(buf
)
947 // The sign and prefix goes before the padding if the fill character
949 Some(min
) if self.sign_aware_zero_pad() => {
952 self.with_padding(min
- width
, rt
::v1
::Alignment
::Right
, |f
| {
956 // Otherwise, the sign and prefix goes after the padding
958 self.with_padding(min
- width
, rt
::v1
::Alignment
::Right
, |f
| {
959 write_prefix(f
)?
; f
.buf
.write_str(buf
)
965 /// This function takes a string slice and emits it to the internal buffer
966 /// after applying the relevant formatting flags specified. The flags
967 /// recognized for generic strings are:
969 /// * width - the minimum width of what to emit
970 /// * fill/align - what to emit and where to emit it if the string
971 /// provided needs to be padded
972 /// * precision - the maximum length to emit, the string is truncated if it
973 /// is longer than this length
975 /// Notably this function ignored the `flag` parameters
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub fn pad(&mut self, s
: &str) -> Result
{
978 // Make sure there's a fast path up front
979 if self.width
.is_none() && self.precision
.is_none() {
980 return self.buf
.write_str(s
);
982 // The `precision` field can be interpreted as a `max-width` for the
983 // string being formatted.
984 let s
= if let Some(max
) = self.precision
{
985 // If our string is longer that the precision, then we must have
986 // truncation. However other flags like `fill`, `width` and `align`
987 // must act as always.
988 if let Some((i
, _
)) = s
.char_indices().skip(max
).next() {
996 // The `width` field is more of a `min-width` parameter at this point.
998 // If we're under the maximum length, and there's no minimum length
999 // requirements, then we can just emit the string
1000 None
=> self.buf
.write_str(s
),
1001 // If we're under the maximum width, check if we're over the minimum
1002 // width, if so it's as easy as just emitting the string.
1003 Some(width
) if s
.chars().count() >= width
=> {
1004 self.buf
.write_str(s
)
1006 // If we're under both the maximum and the minimum width, then fill
1007 // up the minimum width with the specified string + some alignment.
1009 let align
= rt
::v1
::Alignment
::Left
;
1010 self.with_padding(width
- s
.chars().count(), align
, |me
| {
1017 /// Runs a callback, emitting the correct padding either before or
1018 /// afterwards depending on whether right or left alignment is requested.
1019 fn with_padding
<F
>(&mut self, padding
: usize, default: rt
::v1
::Alignment
,
1021 where F
: FnOnce(&mut Formatter
) -> Result
,
1023 let align
= match self.align
{
1024 rt
::v1
::Alignment
::Unknown
=> default,
1028 let (pre_pad
, post_pad
) = match align
{
1029 rt
::v1
::Alignment
::Left
=> (0, padding
),
1030 rt
::v1
::Alignment
::Right
|
1031 rt
::v1
::Alignment
::Unknown
=> (padding
, 0),
1032 rt
::v1
::Alignment
::Center
=> (padding
/ 2, (padding
+ 1) / 2),
1035 let fill
= self.fill
.encode_utf8();
1037 str::from_utf8_unchecked(fill
.as_slice())
1040 for _
in 0..pre_pad
{
1041 self.buf
.write_str(fill
)?
;
1046 for _
in 0..post_pad
{
1047 self.buf
.write_str(fill
)?
;
1053 /// Takes the formatted parts and applies the padding.
1054 /// Assumes that the caller already has rendered the parts with required precision,
1055 /// so that `self.precision` can be ignored.
1056 fn pad_formatted_parts(&mut self, formatted
: &flt2dec
::Formatted
) -> Result
{
1057 if let Some(mut width
) = self.width
{
1058 // for the sign-aware zero padding, we render the sign first and
1059 // behave as if we had no sign from the beginning.
1060 let mut formatted
= formatted
.clone();
1061 let mut align
= self.align
;
1062 let old_fill
= self.fill
;
1063 if self.sign_aware_zero_pad() {
1064 // a sign always goes first
1065 let sign
= unsafe { str::from_utf8_unchecked(formatted.sign) }
;
1066 self.buf
.write_str(sign
)?
;
1068 // remove the sign from the formatted parts
1069 formatted
.sign
= b
"";
1070 width
= if width
< sign
.len() { 0 }
else { width - sign.len() }
;
1071 align
= rt
::v1
::Alignment
::Right
;
1075 // remaining parts go through the ordinary padding process.
1076 let len
= formatted
.len();
1077 let ret
= if width
<= len
{ // no padding
1078 self.write_formatted_parts(&formatted
)
1080 self.with_padding(width
- len
, align
, |f
| {
1081 f
.write_formatted_parts(&formatted
)
1084 self.fill
= old_fill
;
1087 // this is the common case and we take a shortcut
1088 self.write_formatted_parts(formatted
)
1092 fn write_formatted_parts(&mut self, formatted
: &flt2dec
::Formatted
) -> Result
{
1093 fn write_bytes(buf
: &mut Write
, s
: &[u8]) -> Result
{
1094 buf
.write_str(unsafe { str::from_utf8_unchecked(s) }
)
1097 if !formatted
.sign
.is_empty() {
1098 write_bytes(self.buf
, formatted
.sign
)?
;
1100 for part
in formatted
.parts
{
1102 flt2dec
::Part
::Zero(mut nzeroes
) => {
1103 const ZEROES
: &'
static str = // 64 zeroes
1104 "0000000000000000000000000000000000000000000000000000000000000000";
1105 while nzeroes
> ZEROES
.len() {
1106 self.buf
.write_str(ZEROES
)?
;
1107 nzeroes
-= ZEROES
.len();
1110 self.buf
.write_str(&ZEROES
[..nzeroes
])?
;
1113 flt2dec
::Part
::Num(mut v
) => {
1115 let len
= part
.len();
1116 for c
in s
[..len
].iter_mut().rev() {
1117 *c
= b'
0'
+ (v
% 10) as u8;
1120 write_bytes(self.buf
, &s
[..len
])?
;
1122 flt2dec
::Part
::Copy(buf
) => {
1123 write_bytes(self.buf
, buf
)?
;
1130 /// Writes some data to the underlying buffer contained within this
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 pub fn write_str(&mut self, data
: &str) -> Result
{
1134 self.buf
.write_str(data
)
1137 /// Writes some formatted information into this instance
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 pub fn write_fmt(&mut self, fmt
: Arguments
) -> Result
{
1140 write(self.buf
, fmt
)
1143 /// Flags for formatting (packed version of rt::Flag)
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 pub fn flags(&self) -> u32 { self.flags }
1147 /// Character used as 'fill' whenever there is alignment
1148 #[stable(feature = "fmt_flags", since = "1.5.0")]
1149 pub fn fill(&self) -> char { self.fill }
1151 /// Flag indicating what form of alignment was requested
1152 #[unstable(feature = "fmt_flags_align", reason = "method was just created",
1154 pub fn align(&self) -> Alignment
{
1156 rt
::v1
::Alignment
::Left
=> Alignment
::Left
,
1157 rt
::v1
::Alignment
::Right
=> Alignment
::Right
,
1158 rt
::v1
::Alignment
::Center
=> Alignment
::Center
,
1159 rt
::v1
::Alignment
::Unknown
=> Alignment
::Unknown
,
1163 /// Optionally specified integer width that the output should be
1164 #[stable(feature = "fmt_flags", since = "1.5.0")]
1165 pub fn width(&self) -> Option
<usize> { self.width }
1167 /// Optionally specified precision for numeric types
1168 #[stable(feature = "fmt_flags", since = "1.5.0")]
1169 pub fn precision(&self) -> Option
<usize> { self.precision }
1171 /// Determines if the `+` flag was specified.
1172 #[stable(feature = "fmt_flags", since = "1.5.0")]
1173 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1175 /// Determines if the `-` flag was specified.
1176 #[stable(feature = "fmt_flags", since = "1.5.0")]
1177 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1179 /// Determines if the `#` flag was specified.
1180 #[stable(feature = "fmt_flags", since = "1.5.0")]
1181 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1183 /// Determines if the `0` flag was specified.
1184 #[stable(feature = "fmt_flags", since = "1.5.0")]
1185 pub fn sign_aware_zero_pad(&self) -> bool
{
1186 self.flags
& (1 << FlagV1
::SignAwareZeroPad
as u32) != 0
1189 /// Creates a `DebugStruct` builder designed to assist with creation of
1190 /// `fmt::Debug` implementations for structs.
1202 /// impl fmt::Debug for Foo {
1203 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1204 /// fmt.debug_struct("Foo")
1205 /// .field("bar", &self.bar)
1206 /// .field("baz", &self.baz)
1211 /// // prints "Foo { bar: 10, baz: "Hello World" }"
1212 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1214 #[stable(feature = "debug_builders", since = "1.2.0")]
1216 pub fn debug_struct
<'b
>(&'b
mut self, name
: &str) -> DebugStruct
<'b
, 'a
> {
1217 builders
::debug_struct_new(self, name
)
1220 /// Creates a `DebugTuple` builder designed to assist with creation of
1221 /// `fmt::Debug` implementations for tuple structs.
1228 /// struct Foo(i32, String);
1230 /// impl fmt::Debug for Foo {
1231 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1232 /// fmt.debug_tuple("Foo")
1239 /// // prints "Foo(10, "Hello World")"
1240 /// println!("{:?}", Foo(10, "Hello World".to_string()));
1242 #[stable(feature = "debug_builders", since = "1.2.0")]
1244 pub fn debug_tuple
<'b
>(&'b
mut self, name
: &str) -> DebugTuple
<'b
, 'a
> {
1245 builders
::debug_tuple_new(self, name
)
1248 /// Creates a `DebugList` builder designed to assist with creation of
1249 /// `fmt::Debug` implementations for list-like structures.
1256 /// struct Foo(Vec<i32>);
1258 /// impl fmt::Debug for Foo {
1259 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1260 /// fmt.debug_list().entries(self.0.iter()).finish()
1264 /// // prints "[10, 11]"
1265 /// println!("{:?}", Foo(vec![10, 11]));
1267 #[stable(feature = "debug_builders", since = "1.2.0")]
1269 pub fn debug_list
<'b
>(&'b
mut self) -> DebugList
<'b
, 'a
> {
1270 builders
::debug_list_new(self)
1273 /// Creates a `DebugSet` builder designed to assist with creation of
1274 /// `fmt::Debug` implementations for set-like structures.
1281 /// struct Foo(Vec<i32>);
1283 /// impl fmt::Debug for Foo {
1284 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1285 /// fmt.debug_set().entries(self.0.iter()).finish()
1289 /// // prints "{10, 11}"
1290 /// println!("{:?}", Foo(vec![10, 11]));
1292 #[stable(feature = "debug_builders", since = "1.2.0")]
1294 pub fn debug_set
<'b
>(&'b
mut self) -> DebugSet
<'b
, 'a
> {
1295 builders
::debug_set_new(self)
1298 /// Creates a `DebugMap` builder designed to assist with creation of
1299 /// `fmt::Debug` implementations for map-like structures.
1306 /// struct Foo(Vec<(String, i32)>);
1308 /// impl fmt::Debug for Foo {
1309 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1310 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1314 /// // prints "{"A": 10, "B": 11}"
1315 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1317 #[stable(feature = "debug_builders", since = "1.2.0")]
1319 pub fn debug_map
<'b
>(&'b
mut self) -> DebugMap
<'b
, 'a
> {
1320 builders
::debug_map_new(self)
1324 #[stable(since = "1.2.0", feature = "formatter_write")]
1325 impl<'a
> Write
for Formatter
<'a
> {
1326 fn write_str(&mut self, s
: &str) -> Result
{
1327 self.buf
.write_str(s
)
1330 fn write_char(&mut self, c
: char) -> Result
{
1331 self.buf
.write_char(c
)
1334 fn write_fmt(&mut self, args
: Arguments
) -> Result
{
1335 write(self.buf
, args
)
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl Display
for Error
{
1341 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1342 Display
::fmt("an error occurred when formatting an argument", f
)
1346 // Implementations of the core formatting traits
1348 macro_rules
! fmt_refs
{
1349 ($
($tr
:ident
),*) => {
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 impl<'a
, T
: ?Sized
+ $tr
> $tr
for &'a T
{
1353 fn fmt(&self, f
: &mut Formatter
) -> Result { $tr::fmt(&**self, f) }
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 impl<'a
, T
: ?Sized
+ $tr
> $tr
for &'a
mut T
{
1357 fn fmt(&self, f
: &mut Formatter
) -> Result { $tr::fmt(&**self, f) }
1363 fmt_refs
! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1365 #[unstable(feature = "never_type", issue = "35121")]
1367 fn fmt(&self, _
: &mut Formatter
) -> Result
{
1372 #[unstable(feature = "never_type", issue = "35121")]
1373 impl Display
for ! {
1374 fn fmt(&self, _
: &mut Formatter
) -> Result
{
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl Debug
for bool
{
1381 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1382 Display
::fmt(self, f
)
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 impl Display
for bool
{
1388 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1389 Display
::fmt(if *self { "true" }
else { "false" }
, f
)
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 impl Debug
for str {
1395 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1398 for (i, c) in self.char_indices() {
1399 let esc = c.escape_debug();
1400 // If char needs escaping, flush backlog so far and write, else skip
1402 f.write_str(&self[from..i])?;
1406 from = i + c.len_utf8();
1409 f.write_str(&self[from..])?;
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 impl Display
for str {
1416 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 impl Debug
for char {
1423 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1424 f
.write_char('
\''
)?
;
1425 for c
in self.escape_debug() {
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl Display
for char {
1434 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1435 if f
.width
.is_none() && f
.precision
.is_none() {
1439 str::from_utf8_unchecked(self.encode_utf8().as_slice())
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 impl<T
: ?Sized
> Pointer
for *const T
{
1447 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1448 let old_width
= f
.width
;
1449 let old_flags
= f
.flags
;
1451 // The alternate flag is already treated by LowerHex as being special-
1452 // it denotes whether to prefix with 0x. We use it to work out whether
1453 // or not to zero extend, and then unconditionally set it to get the
1456 f
.flags
|= 1 << (FlagV1
::SignAwareZeroPad
as u32);
1458 if let None
= f
.width
{
1459 f
.width
= Some(((mem
::size_of
::<usize>() * 8) / 4) + 2);
1462 f
.flags
|= 1 << (FlagV1
::Alternate
as u32);
1464 let ret
= LowerHex
::fmt(&(*self as *const () as usize), f
);
1466 f
.width
= old_width
;
1467 f
.flags
= old_flags
;
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<T
: ?Sized
> Pointer
for *mut T
{
1475 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1476 Pointer
::fmt(&(*self as *const T
), f
)
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 impl<'a
, T
: ?Sized
> Pointer
for &'a T
{
1482 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1483 Pointer
::fmt(&(*self as *const T
), f
)
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 impl<'a
, T
: ?Sized
> Pointer
for &'a
mut T
{
1489 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1490 Pointer
::fmt(&(&**self as *const T
), f
)
1494 // Common code of floating point Debug and Display.
1495 fn float_to_decimal_common
<T
>(fmt
: &mut Formatter
, num
: &T
, negative_zero
: bool
) -> Result
1496 where T
: flt2dec
::DecodableFloat
1498 let force_sign
= fmt
.sign_plus();
1499 let sign
= match (force_sign
, negative_zero
) {
1500 (false, false) => flt2dec
::Sign
::Minus
,
1501 (false, true) => flt2dec
::Sign
::MinusRaw
,
1502 (true, false) => flt2dec
::Sign
::MinusPlus
,
1503 (true, true) => flt2dec
::Sign
::MinusPlusRaw
,
1506 let mut buf
= [0; 1024]; // enough for f32 and f64
1507 let mut parts
= [flt2dec
::Part
::Zero(0); 16];
1508 let formatted
= if let Some(precision
) = fmt
.precision
{
1509 flt2dec
::to_exact_fixed_str(flt2dec
::strategy
::grisu
::format_exact
, *num
, sign
,
1510 precision
, false, &mut buf
, &mut parts
)
1512 flt2dec
::to_shortest_str(flt2dec
::strategy
::grisu
::format_shortest
, *num
, sign
,
1513 0, false, &mut buf
, &mut parts
)
1515 fmt
.pad_formatted_parts(&formatted
)
1518 // Common code of floating point LowerExp and UpperExp.
1519 fn float_to_exponential_common
<T
>(fmt
: &mut Formatter
, num
: &T
, upper
: bool
) -> Result
1520 where T
: flt2dec
::DecodableFloat
1522 let force_sign
= fmt
.sign_plus();
1523 let sign
= match force_sign
{
1524 false => flt2dec
::Sign
::Minus
,
1525 true => flt2dec
::Sign
::MinusPlus
,
1528 let mut buf
= [0; 1024]; // enough for f32 and f64
1529 let mut parts
= [flt2dec
::Part
::Zero(0); 16];
1530 let formatted
= if let Some(precision
) = fmt
.precision
{
1531 // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1532 flt2dec
::to_exact_exp_str(flt2dec
::strategy
::grisu
::format_exact
, *num
, sign
,
1533 precision
+ 1, upper
, &mut buf
, &mut parts
)
1535 flt2dec
::to_shortest_exp_str(flt2dec
::strategy
::grisu
::format_shortest
, *num
, sign
,
1536 (0, 0), upper
, &mut buf
, &mut parts
)
1538 fmt
.pad_formatted_parts(&formatted
)
1541 macro_rules
! floating
{ ($ty
:ident
) => {
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl Debug
for $ty
{
1545 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
1546 float_to_decimal_common(fmt
, self, true)
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 impl Display
for $ty
{
1552 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
1553 float_to_decimal_common(fmt
, self, false)
1557 #[stable(feature = "rust1", since = "1.0.0")]
1558 impl LowerExp
for $ty
{
1559 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
1560 float_to_exponential_common(fmt
, self, false)
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 impl UpperExp
for $ty
{
1566 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
1567 float_to_exponential_common(fmt
, self, true)
1574 // Implementation of Display/Debug for various core types
1576 #[stable(feature = "rust1", since = "1.0.0")]
1577 impl<T
> Debug
for *const T
{
1578 fn fmt(&self, f
: &mut Formatter
) -> Result { Pointer::fmt(self, f) }
1580 #[stable(feature = "rust1", since = "1.0.0")]
1581 impl<T
> Debug
for *mut T
{
1582 fn fmt(&self, f
: &mut Formatter
) -> Result { Pointer::fmt(self, f) }
1586 ($name
:ident
, $
($other
:ident
,)*) => (tuple
! { $($other,)* }
)
1589 macro_rules
! tuple
{
1591 ( $
($name
:ident
,)+ ) => (
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl<$
($name
:Debug
),*> Debug
for ($
($name
,)*) {
1594 #[allow(non_snake_case, unused_assignments, deprecated)]
1595 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1596 let mut builder
= f
.debug_tuple("");
1597 let ($
(ref $name
,)*) = *self;
1599 builder
.field($name
);
1605 peel
! { $($name,)* }
1609 tuple
! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1611 #[stable(feature = "rust1", since = "1.0.0")]
1612 impl<T
: Debug
> Debug
for [T
] {
1613 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1614 f
.debug_list().entries(self.iter()).finish()
1618 #[stable(feature = "rust1", since = "1.0.0")]
1620 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl<T
: ?Sized
> Debug
for PhantomData
<T
> {
1626 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1627 f
.pad("PhantomData")
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 impl<T
: Copy
+ Debug
> Debug
for Cell
<T
> {
1633 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1634 f
.debug_struct("Cell")
1635 .field("value", &self.get())
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 impl<T
: ?Sized
+ Debug
> Debug
for RefCell
<T
> {
1642 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1643 match self.borrow_state() {
1644 BorrowState
::Unused
| BorrowState
::Reading
=> {
1645 f
.debug_struct("RefCell")
1646 .field("value", &self.borrow())
1649 BorrowState
::Writing
=> {
1650 f
.debug_struct("RefCell")
1651 .field("value", &"<borrowed>")
1658 #[stable(feature = "rust1", since = "1.0.0")]
1659 impl<'b
, T
: ?Sized
+ Debug
> Debug
for Ref
<'b
, T
> {
1660 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1661 Debug
::fmt(&**self, f
)
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 impl<'b
, T
: ?Sized
+ Debug
> Debug
for RefMut
<'b
, T
> {
1667 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1668 Debug
::fmt(&*(self.deref()), f
)
1672 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1673 impl<T
: ?Sized
+ Debug
> Debug
for UnsafeCell
<T
> {
1674 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1679 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1680 // it's a lot easier than creating all of the rt::Piece structures here.