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
92 /// use std::fmt::{self, write};
94 /// let mut output = String::new();
95 /// match write(&mut output, format_args!("Hello {}!", "world")) {
96 /// Err(fmt::Error) => panic!("An error occurred"),
100 #[stable(feature = "rust1", since = "1.0.0")]
101 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
104 /// A collection of methods that are required to format a message into a stream.
106 /// This trait is the type which this modules requires when formatting
107 /// information. This is similar to the standard library's [`io::Write`] trait,
108 /// but it is only intended for use in libcore.
110 /// This trait should generally not be implemented by consumers of the standard
111 /// library. The [`write!`] macro accepts an instance of [`io::Write`], and the
112 /// [`io::Write`] trait is favored over implementing this trait.
114 /// [`write!`]: ../../std/macro.write.html
115 /// [`io::Write`]: ../../std/io/trait.Write.html
116 #[stable(feature = "rust1", since = "1.0.0")]
118 /// Writes a slice of bytes into this writer, returning whether the write
121 /// This method can only succeed if the entire byte slice was successfully
122 /// written, and this method will not return until all data has been
123 /// written or an error occurs.
127 /// This function will return an instance of [`Error`] on error.
129 /// [`Error`]: struct.Error.html
134 /// use std::fmt::{Error, Write};
136 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
140 /// let mut buf = String::new();
141 /// writer(&mut buf, "hola").unwrap();
142 /// assert_eq!(&buf, "hola");
144 #[stable(feature = "rust1", since = "1.0.0")]
145 fn write_str(&mut self, s: &str) -> Result;
147 /// Writes a [`char`] into this writer, returning whether the write succeeded.
149 /// A single [`char`] may be encoded as more than one byte.
150 /// This method can only succeed if the entire byte sequence was successfully
151 /// written, and this method will not return until all data has been
152 /// written or an error occurs.
156 /// This function will return an instance of [`Error`] on error.
158 /// [`char`]: ../../std/primitive.char.html
159 /// [`Error`]: struct.Error.html
164 /// use std::fmt::{Error, Write};
166 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
170 /// let mut buf = String::new();
171 /// writer(&mut buf, 'a').unwrap();
172 /// writer(&mut buf, 'b').unwrap();
173 /// assert_eq!(&buf, "ab");
175 #[stable(feature = "fmt_write_char", since = "1.1.0")]
176 fn write_char(&mut self, c: char) -> Result {
177 self.write_str(c.encode_utf8(&mut [0; 4]))
180 /// Glue for usage of the [`write!`] macro with implementors of this trait.
182 /// This method should generally not be invoked manually, but rather through
183 /// the [`write!`] macro itself.
185 /// [`write!`]: ../../std/macro.write.html
190 /// use std::fmt::{Error, Write};
192 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
193 /// f.write_fmt(format_args!("{}", s))
196 /// let mut buf = String::new();
197 /// writer(&mut buf, "world").unwrap();
198 /// assert_eq!(&buf, "world");
200 #[stable(feature = "rust1", since = "1.0.0")]
201 fn write_fmt(&mut self, args: Arguments) -> Result {
202 // This Adapter is needed to allow `self` (of type `&mut
203 // Self`) to be cast to a Write (below) without
204 // requiring a `Sized` bound.
205 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
207 impl<'a, T: ?Sized> Write for Adapter<'a, T>
210 fn write_str(&mut self, s: &str) -> Result {
214 fn write_char(&mut self, c: char) -> Result {
218 fn write_fmt(&mut self, args: Arguments) -> Result {
219 self.0.write_fmt(args)
223 write(&mut Adapter(self), args)
227 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
228 impl<'a, W: Write + ?Sized> Write for &'a mut W {
229 fn write_str(&mut self, s: &str) -> Result {
230 (**self).write_str(s)
233 fn write_char(&mut self, c: char) -> Result {
234 (**self).write_char(c)
237 fn write_fmt(&mut self, args: Arguments) -> Result {
238 (**self).write_fmt(args)
242 /// A struct to represent both where to emit formatting strings to and how they
243 /// should be formatted. A mutable version of this is passed to all formatting
245 #[allow(missing_debug_implementations)]
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub struct Formatter<'a> {
250 align: rt::v1::Alignment,
251 width: Option<usize>,
252 precision: Option<usize>,
254 buf: &'a mut (Write+'a),
255 curarg: slice::Iter<'a, ArgumentV1<'a>>,
256 args: &'a [ArgumentV1<'a>],
259 // NB. Argument is essentially an optimized partially applied formatting function,
260 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
264 /// Erases all oibits, because `Void` erases the type of the object that
265 /// will be used to produce formatted output. Since we do not know what
266 /// oibits the real types have (and they can have any or none), we need to
267 /// take the most conservative approach and forbid all oibits.
269 /// It was added after #45197 showed that one could share a `!Sync`
270 /// object across threads by passing it into `format_args!`.
271 _oibit_remover: PhantomData<*mut Fn()>,
274 /// This struct represents the generic "argument" which is taken by the Xprintf
275 /// family of functions. It contains a function to format the given value. At
276 /// compile time it is ensured that the function and the value have the correct
277 /// types, and then this struct is used to canonicalize arguments to one type.
279 #[allow(missing_debug_implementations)]
280 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
283 pub struct ArgumentV1<'a> {
285 formatter: fn(&Void, &mut Formatter) -> Result,
288 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
290 impl<'a> Clone for ArgumentV1<'a> {
291 fn clone(&self) -> ArgumentV1<'a> {
296 impl<'a> ArgumentV1<'a> {
298 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
303 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
305 pub fn new<'b, T>(x: &'b T,
306 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
309 formatter: mem::transmute(f),
310 value: mem::transmute(x)
316 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
318 pub fn from_usize(x: &usize) -> ArgumentV1 {
319 ArgumentV1::new(x, ArgumentV1::show_usize)
322 fn as_usize(&self) -> Option<usize> {
323 if self.formatter as usize == ArgumentV1::show_usize as usize {
324 Some(unsafe { *(self.value as *const _ as *const usize) })
331 // flags available in the v1 format of format_args
332 #[derive(Copy, Clone)]
333 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
335 impl<'a> Arguments<'a> {
336 /// When using the format_args!() macro, this function is used to generate the
337 /// Arguments structure.
338 #[doc(hidden)] #[inline]
339 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
341 pub fn new_v1(pieces: &'a [&'a str],
342 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
350 /// This function is used to specify nonstandard formatting parameters.
351 /// The `pieces` array must be at least as long as `fmt` to construct
352 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
353 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
354 /// created with `argumentusize`. However, failing to do so doesn't cause
355 /// unsafety, but will ignore invalid .
356 #[doc(hidden)] #[inline]
357 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
359 pub fn new_v1_formatted(pieces: &'a [&'a str],
360 args: &'a [ArgumentV1<'a>],
361 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
369 /// Estimates the length of the formatted text.
371 /// This is intended to be used for setting initial `String` capacity
372 /// when using `format!`. Note: this is neither the lower nor upper bound.
373 #[doc(hidden)] #[inline]
374 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
376 pub fn estimated_capacity(&self) -> usize {
377 let pieces_length: usize = self.pieces.iter()
378 .map(|x| x.len()).sum();
380 if self.args.is_empty() {
382 } else if self.pieces[0] == "" && pieces_length < 16 {
383 // If the format string starts with an argument,
384 // don't preallocate anything, unless length
385 // of pieces is significant.
388 // There are some arguments, so any additional push
389 // will reallocate the string. To avoid that,
390 // we're "pre-doubling" the capacity here.
391 pieces_length.checked_mul(2).unwrap_or(0)
396 /// This structure represents a safely precompiled version of a format string
397 /// and its arguments. This cannot be generated at runtime because it cannot
398 /// safely be done, so no constructors are given and the fields are private
399 /// to prevent modification.
401 /// The [`format_args!`] macro will safely create an instance of this structure
402 /// and pass it to a function or closure, passed as the first argument. The
403 /// macro validates the format string at compile-time so usage of the [`write`]
404 /// and [`format`] functions can be safely performed.
406 /// [`format_args!`]: ../../std/macro.format_args.html
407 /// [`format`]: ../../std/fmt/fn.format.html
408 /// [`write`]: ../../std/fmt/fn.write.html
409 #[stable(feature = "rust1", since = "1.0.0")]
410 #[derive(Copy, Clone)]
411 pub struct Arguments<'a> {
412 // Format string pieces to print.
413 pieces: &'a [&'a str],
415 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
416 fmt: Option<&'a [rt::v1::Argument]>,
418 // Dynamic arguments for interpolation, to be interleaved with string
419 // pieces. (Every argument is preceded by a string piece.)
420 args: &'a [ArgumentV1<'a>],
423 #[stable(feature = "rust1", since = "1.0.0")]
424 impl<'a> Debug for Arguments<'a> {
425 fn fmt(&self, fmt: &mut Formatter) -> Result {
426 Display::fmt(self, fmt)
430 #[stable(feature = "rust1", since = "1.0.0")]
431 impl<'a> Display for Arguments<'a> {
432 fn fmt(&self, fmt: &mut Formatter) -> Result {
433 write(fmt.buf, *self)
439 /// `Debug` should format the output in a programmer-facing, debugging context.
441 /// Generally speaking, you should just `derive` a `Debug` implementation.
443 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
445 /// For more information on formatters, see [the module-level documentation][module].
447 /// [module]: ../../std/fmt/index.html
449 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
450 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
451 /// comma-separated list of each field's name and `Debug` value, then `}`. For
452 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
453 /// `Debug` values of the fields, then `)`.
457 /// Deriving an implementation:
466 /// let origin = Point { x: 0, y: 0 };
468 /// println!("The origin is: {:?}", origin);
471 /// Manually implementing:
481 /// impl fmt::Debug for Point {
482 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
483 /// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
487 /// let origin = Point { x: 0, y: 0 };
489 /// println!("The origin is: {:?}", origin);
495 /// The origin is: Point { x: 0, y: 0 }
498 /// There are a number of `debug_*` methods on [`Formatter`] to help you with manual
499 /// implementations, such as [`debug_struct`][debug_struct].
501 /// `Debug` implementations using either `derive` or the debug builder API
502 /// on [`Formatter`] support pretty printing using the alternate flag: `{:#?}`.
504 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
505 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
507 /// Pretty printing with `#?`:
516 /// let origin = Point { x: 0, y: 0 };
518 /// println!("The origin is: {:#?}", origin);
524 /// The origin is: Point {
529 #[stable(feature = "rust1", since = "1.0.0")]
530 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
531 defined in your crate, add `#[derive(Debug)]` or \
532 manually implement it"]
533 #[lang = "debug_trait"]
535 /// Formats the value using the given formatter.
542 /// struct Position {
547 /// impl fmt::Debug for Position {
548 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
549 /// write!(f, "({:?}, {:?})", self.longitude, self.latitude)
553 /// assert_eq!("(1.987, 2.983)".to_owned(),
554 /// format!("{:?}", Position { longitude: 1.987, latitude: 2.983, }));
556 #[stable(feature = "rust1", since = "1.0.0")]
557 fn fmt(&self, f: &mut Formatter) -> Result;
560 /// Format trait for an empty format, `{}`.
562 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
563 /// output, and so cannot be derived.
565 /// [debug]: trait.Debug.html
567 /// For more information on formatters, see [the module-level documentation][module].
569 /// [module]: ../../std/fmt/index.html
573 /// Implementing `Display` on a type:
583 /// impl fmt::Display for Point {
584 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
585 /// write!(f, "({}, {})", self.x, self.y)
589 /// let origin = Point { x: 0, y: 0 };
591 /// println!("The origin is: {}", origin);
593 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
594 formatter; try using `:?` instead if you are using \
596 #[stable(feature = "rust1", since = "1.0.0")]
598 /// Formats the value using the given formatter.
605 /// struct Position {
610 /// impl fmt::Display for Position {
611 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
612 /// write!(f, "({}, {})", self.longitude, self.latitude)
616 /// assert_eq!("(1.987, 2.983)".to_owned(),
617 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
619 #[stable(feature = "rust1", since = "1.0.0")]
620 fn fmt(&self, f: &mut Formatter) -> Result;
625 /// The `Octal` trait should format its output as a number in base-8.
627 /// The alternate flag, `#`, adds a `0o` in front of the output.
629 /// For more information on formatters, see [the module-level documentation][module].
631 /// [module]: ../../std/fmt/index.html
635 /// Basic usage with `i32`:
638 /// let x = 42; // 42 is '52' in octal
640 /// assert_eq!(format!("{:o}", x), "52");
641 /// assert_eq!(format!("{:#o}", x), "0o52");
644 /// Implementing `Octal` on a type:
649 /// struct Length(i32);
651 /// impl fmt::Octal for Length {
652 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
653 /// let val = self.0;
655 /// write!(f, "{:o}", val) // delegate to i32's implementation
659 /// let l = Length(9);
661 /// println!("l as octal is: {:o}", l);
663 #[stable(feature = "rust1", since = "1.0.0")]
665 /// Formats the value using the given formatter.
666 #[stable(feature = "rust1", since = "1.0.0")]
667 fn fmt(&self, f: &mut Formatter) -> Result;
672 /// The `Binary` trait should format its output as a number in binary.
674 /// The alternate flag, `#`, adds a `0b` in front of the output.
676 /// For more information on formatters, see [the module-level documentation][module].
678 /// [module]: ../../std/fmt/index.html
682 /// Basic usage with `i32`:
685 /// let x = 42; // 42 is '101010' in binary
687 /// assert_eq!(format!("{:b}", x), "101010");
688 /// assert_eq!(format!("{:#b}", x), "0b101010");
691 /// Implementing `Binary` on a type:
696 /// struct Length(i32);
698 /// impl fmt::Binary for Length {
699 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
700 /// let val = self.0;
702 /// write!(f, "{:b}", val) // delegate to i32's implementation
706 /// let l = Length(107);
708 /// println!("l as binary is: {:b}", l);
710 #[stable(feature = "rust1", since = "1.0.0")]
712 /// Formats the value using the given formatter.
713 #[stable(feature = "rust1", since = "1.0.0")]
714 fn fmt(&self, f: &mut Formatter) -> Result;
719 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
722 /// The alternate flag, `#`, adds a `0x` in front of the output.
724 /// For more information on formatters, see [the module-level documentation][module].
726 /// [module]: ../../std/fmt/index.html
730 /// Basic usage with `i32`:
733 /// let x = 42; // 42 is '2a' in hex
735 /// assert_eq!(format!("{:x}", x), "2a");
736 /// assert_eq!(format!("{:#x}", x), "0x2a");
739 /// Implementing `LowerHex` on a type:
744 /// struct Length(i32);
746 /// impl fmt::LowerHex for Length {
747 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
748 /// let val = self.0;
750 /// write!(f, "{:x}", val) // delegate to i32's implementation
754 /// let l = Length(9);
756 /// println!("l as hex is: {:x}", l);
758 #[stable(feature = "rust1", since = "1.0.0")]
760 /// Formats the value using the given formatter.
761 #[stable(feature = "rust1", since = "1.0.0")]
762 fn fmt(&self, f: &mut Formatter) -> Result;
767 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
770 /// The alternate flag, `#`, adds a `0x` in front of the output.
772 /// For more information on formatters, see [the module-level documentation][module].
774 /// [module]: ../../std/fmt/index.html
778 /// Basic usage with `i32`:
781 /// let x = 42; // 42 is '2A' in hex
783 /// assert_eq!(format!("{:X}", x), "2A");
784 /// assert_eq!(format!("{:#X}", x), "0x2A");
787 /// Implementing `UpperHex` on a type:
792 /// struct Length(i32);
794 /// impl fmt::UpperHex for Length {
795 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
796 /// let val = self.0;
798 /// write!(f, "{:X}", val) // delegate to i32's implementation
802 /// let l = Length(9);
804 /// println!("l as hex is: {:X}", l);
806 #[stable(feature = "rust1", since = "1.0.0")]
808 /// Formats the value using the given formatter.
809 #[stable(feature = "rust1", since = "1.0.0")]
810 fn fmt(&self, f: &mut Formatter) -> Result;
815 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
818 /// For more information on formatters, see [the module-level documentation][module].
820 /// [module]: ../../std/fmt/index.html
824 /// Basic usage with `&i32`:
829 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
832 /// Implementing `Pointer` on a type:
837 /// struct Length(i32);
839 /// impl fmt::Pointer for Length {
840 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
841 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
843 /// write!(f, "{:p}", self as *const Length)
847 /// let l = Length(42);
849 /// println!("l is in memory here: {:p}", l);
851 #[stable(feature = "rust1", since = "1.0.0")]
853 /// Formats the value using the given formatter.
854 #[stable(feature = "rust1", since = "1.0.0")]
855 fn fmt(&self, f: &mut Formatter) -> Result;
860 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
862 /// For more information on formatters, see [the module-level documentation][module].
864 /// [module]: ../../std/fmt/index.html
868 /// Basic usage with `i32`:
871 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
873 /// assert_eq!(format!("{:e}", x), "4.2e1");
876 /// Implementing `LowerExp` on a type:
881 /// struct Length(i32);
883 /// impl fmt::LowerExp for Length {
884 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
885 /// let val = self.0;
886 /// write!(f, "{}e1", val / 10)
890 /// let l = Length(100);
892 /// println!("l in scientific notation is: {:e}", l);
894 #[stable(feature = "rust1", since = "1.0.0")]
896 /// Formats the value using the given formatter.
897 #[stable(feature = "rust1", since = "1.0.0")]
898 fn fmt(&self, f: &mut Formatter) -> Result;
903 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
905 /// For more information on formatters, see [the module-level documentation][module].
907 /// [module]: ../../std/fmt/index.html
911 /// Basic usage with `f32`:
914 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
916 /// assert_eq!(format!("{:E}", x), "4.2E1");
919 /// Implementing `UpperExp` on a type:
924 /// struct Length(i32);
926 /// impl fmt::UpperExp for Length {
927 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
928 /// let val = self.0;
929 /// write!(f, "{}E1", val / 10)
933 /// let l = Length(100);
935 /// println!("l in scientific notation is: {:E}", l);
937 #[stable(feature = "rust1", since = "1.0.0")]
939 /// Formats the value using the given formatter.
940 #[stable(feature = "rust1", since = "1.0.0")]
941 fn fmt(&self, f: &mut Formatter) -> Result;
944 /// The `write` function takes an output stream, and an `Arguments` struct
945 /// that can be precompiled with the `format_args!` macro.
947 /// The arguments will be formatted according to the specified format string
948 /// into the output stream provided.
957 /// let mut output = String::new();
958 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
959 /// .expect("Error occurred while trying to write in String");
960 /// assert_eq!(output, "Hello world!");
963 /// Please note that using [`write!`] might be preferable. Example:
966 /// use std::fmt::Write;
968 /// let mut output = String::new();
969 /// write!(&mut output, "Hello {}!", "world")
970 /// .expect("Error occurred while trying to write in String");
971 /// assert_eq!(output, "Hello world!");
974 /// [`write!`]: ../../std/macro.write.html
975 #[stable(feature = "rust1", since = "1.0.0")]
976 pub fn write(output: &mut Write, args: Arguments) -> Result {
977 let mut formatter = Formatter {
982 align: rt::v1::Alignment::Unknown,
985 curarg: args.args.iter(),
988 let mut pieces = args.pieces.iter();
992 // We can use default formatting parameters for all arguments.
993 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
994 formatter.buf.write_str(*piece)?;
995 (arg.formatter)(arg.value, &mut formatter)?;
999 // Every spec has a corresponding argument that is preceded by
1001 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
1002 formatter.buf.write_str(*piece)?;
1003 formatter.run(arg)?;
1008 // There can be only one trailing string piece left.
1009 if let Some(piece) = pieces.next() {
1010 formatter.buf.write_str(*piece)?;
1016 impl<'a> Formatter<'a> {
1017 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1018 where 'b: 'c, F: FnOnce(&'b mut (Write+'b)) -> &'c mut (Write+'c)
1021 // We want to change this
1022 buf: wrap(self.buf),
1024 // And preserve these
1029 precision: self.precision,
1031 // These only exist in the struct for the `run` method,
1032 // which won’t be used together with this method.
1033 curarg: self.curarg.clone(),
1038 // First up is the collection of functions used to execute a format string
1039 // at runtime. This consumes all of the compile-time statics generated by
1040 // the format! syntax extension.
1041 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1042 // Fill in the format parameters into the formatter
1043 self.fill = arg.format.fill;
1044 self.align = arg.format.align;
1045 self.flags = arg.format.flags;
1046 self.width = self.getcount(&arg.format.width);
1047 self.precision = self.getcount(&arg.format.precision);
1049 // Extract the correct argument
1050 let value = match arg.position {
1051 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1052 rt::v1::Position::At(i) => self.args[i],
1055 // Then actually do some printing
1056 (value.formatter)(value.value, self)
1059 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1061 rt::v1::Count::Is(n) => Some(n),
1062 rt::v1::Count::Implied => None,
1063 rt::v1::Count::Param(i) => {
1064 self.args[i].as_usize()
1066 rt::v1::Count::NextParam => {
1067 self.curarg.next().and_then(|arg| arg.as_usize())
1072 // Helper methods used for padding and processing formatting arguments that
1073 // all formatting traits can use.
1075 /// Performs the correct padding for an integer which has already been
1076 /// emitted into a str. The str should *not* contain the sign for the
1077 /// integer, that will be added by this method.
1081 /// * is_nonnegative - whether the original integer was either positive or zero.
1082 /// * prefix - if the '#' character (Alternate) is provided, this
1083 /// is the prefix to put in front of the number.
1084 /// * buf - the byte array that the number has been formatted into
1086 /// This function will correctly account for the flags provided as well as
1087 /// the minimum width. It will not take precision into account.
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 pub fn pad_integral(&mut self,
1090 is_nonnegative: bool,
1094 let mut width = buf.len();
1096 let mut sign = None;
1097 if !is_nonnegative {
1098 sign = Some('-'); width += 1;
1099 } else if self.sign_plus() {
1100 sign = Some('+'); width += 1;
1103 let mut prefixed = false;
1104 if self.alternate() {
1105 prefixed = true; width += prefix.chars().count();
1108 // Writes the sign if it exists, and then the prefix if it was requested
1109 let write_prefix = |f: &mut Formatter| {
1110 if let Some(c) = sign {
1111 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
1113 if prefixed { f.buf.write_str(prefix) }
1117 // The `width` field is more of a `min-width` parameter at this point.
1119 // If there's no minimum length requirements then we can just
1122 write_prefix(self)?; self.buf.write_str(buf)
1124 // Check if we're over the minimum width, if so then we can also
1125 // just write the bytes.
1126 Some(min) if width >= min => {
1127 write_prefix(self)?; self.buf.write_str(buf)
1129 // The sign and prefix goes before the padding if the fill character
1131 Some(min) if self.sign_aware_zero_pad() => {
1133 self.align = rt::v1::Alignment::Right;
1134 write_prefix(self)?;
1135 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1136 f.buf.write_str(buf)
1139 // Otherwise, the sign and prefix goes after the padding
1141 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1142 write_prefix(f)?; f.buf.write_str(buf)
1148 /// This function takes a string slice and emits it to the internal buffer
1149 /// after applying the relevant formatting flags specified. The flags
1150 /// recognized for generic strings are:
1152 /// * width - the minimum width of what to emit
1153 /// * fill/align - what to emit and where to emit it if the string
1154 /// provided needs to be padded
1155 /// * precision - the maximum length to emit, the string is truncated if it
1156 /// is longer than this length
1158 /// Notably this function ignores the `flag` parameters.
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 pub fn pad(&mut self, s: &str) -> Result {
1161 // Make sure there's a fast path up front
1162 if self.width.is_none() && self.precision.is_none() {
1163 return self.buf.write_str(s);
1165 // The `precision` field can be interpreted as a `max-width` for the
1166 // string being formatted.
1167 let s = if let Some(max) = self.precision {
1168 // If our string is longer that the precision, then we must have
1169 // truncation. However other flags like `fill`, `width` and `align`
1170 // must act as always.
1171 if let Some((i, _)) = s.char_indices().skip(max).next() {
1179 // The `width` field is more of a `min-width` parameter at this point.
1181 // If we're under the maximum length, and there's no minimum length
1182 // requirements, then we can just emit the string
1183 None => self.buf.write_str(s),
1184 // If we're under the maximum width, check if we're over the minimum
1185 // width, if so it's as easy as just emitting the string.
1186 Some(width) if s.chars().count() >= width => {
1187 self.buf.write_str(s)
1189 // If we're under both the maximum and the minimum width, then fill
1190 // up the minimum width with the specified string + some alignment.
1192 let align = rt::v1::Alignment::Left;
1193 self.with_padding(width - s.chars().count(), align, |me| {
1200 /// Runs a callback, emitting the correct padding either before or
1201 /// afterwards depending on whether right or left alignment is requested.
1202 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1204 where F: FnOnce(&mut Formatter) -> Result,
1206 let align = match self.align {
1207 rt::v1::Alignment::Unknown => default,
1211 let (pre_pad, post_pad) = match align {
1212 rt::v1::Alignment::Left => (0, padding),
1213 rt::v1::Alignment::Right |
1214 rt::v1::Alignment::Unknown => (padding, 0),
1215 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1218 let mut fill = [0; 4];
1219 let fill = self.fill.encode_utf8(&mut fill);
1221 for _ in 0..pre_pad {
1222 self.buf.write_str(fill)?;
1227 for _ in 0..post_pad {
1228 self.buf.write_str(fill)?;
1234 /// Takes the formatted parts and applies the padding.
1235 /// Assumes that the caller already has rendered the parts with required precision,
1236 /// so that `self.precision` can be ignored.
1237 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1238 if let Some(mut width) = self.width {
1239 // for the sign-aware zero padding, we render the sign first and
1240 // behave as if we had no sign from the beginning.
1241 let mut formatted = formatted.clone();
1242 let old_fill = self.fill;
1243 let old_align = self.align;
1244 let mut align = old_align;
1245 if self.sign_aware_zero_pad() {
1246 // a sign always goes first
1247 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1248 self.buf.write_str(sign)?;
1250 // remove the sign from the formatted parts
1251 formatted.sign = b"";
1252 width = if width < sign.len() { 0 } else { width - sign.len() };
1253 align = rt::v1::Alignment::Right;
1255 self.align = rt::v1::Alignment::Right;
1258 // remaining parts go through the ordinary padding process.
1259 let len = formatted.len();
1260 let ret = if width <= len { // no padding
1261 self.write_formatted_parts(&formatted)
1263 self.with_padding(width - len, align, |f| {
1264 f.write_formatted_parts(&formatted)
1267 self.fill = old_fill;
1268 self.align = old_align;
1271 // this is the common case and we take a shortcut
1272 self.write_formatted_parts(formatted)
1276 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1277 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1278 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1281 if !formatted.sign.is_empty() {
1282 write_bytes(self.buf, formatted.sign)?;
1284 for part in formatted.parts {
1286 flt2dec::Part::Zero(mut nzeroes) => {
1287 const ZEROES: &'static str = // 64 zeroes
1288 "0000000000000000000000000000000000000000000000000000000000000000";
1289 while nzeroes > ZEROES.len() {
1290 self.buf.write_str(ZEROES)?;
1291 nzeroes -= ZEROES.len();
1294 self.buf.write_str(&ZEROES[..nzeroes])?;
1297 flt2dec::Part::Num(mut v) => {
1299 let len = part.len();
1300 for c in s[..len].iter_mut().rev() {
1301 *c = b'0' + (v % 10) as u8;
1304 write_bytes(self.buf, &s[..len])?;
1306 flt2dec::Part::Copy(buf) => {
1307 write_bytes(self.buf, buf)?;
1314 /// Writes some data to the underlying buffer contained within this
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 pub fn write_str(&mut self, data: &str) -> Result {
1318 self.buf.write_str(data)
1321 /// Writes some formatted information into this instance
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1324 write(self.buf, fmt)
1327 /// Flags for formatting
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 pub fn flags(&self) -> u32 { self.flags }
1331 /// Character used as 'fill' whenever there is alignment
1332 #[stable(feature = "fmt_flags", since = "1.5.0")]
1333 pub fn fill(&self) -> char { self.fill }
1335 /// Flag indicating what form of alignment was requested
1336 #[unstable(feature = "fmt_flags_align", reason = "method was just created",
1338 pub fn align(&self) -> Alignment {
1340 rt::v1::Alignment::Left => Alignment::Left,
1341 rt::v1::Alignment::Right => Alignment::Right,
1342 rt::v1::Alignment::Center => Alignment::Center,
1343 rt::v1::Alignment::Unknown => Alignment::Unknown,
1347 /// Optionally specified integer width that the output should be
1348 #[stable(feature = "fmt_flags", since = "1.5.0")]
1349 pub fn width(&self) -> Option<usize> { self.width }
1351 /// Optionally specified precision for numeric types
1352 #[stable(feature = "fmt_flags", since = "1.5.0")]
1353 pub fn precision(&self) -> Option<usize> { self.precision }
1355 /// Determines if the `+` flag was specified.
1356 #[stable(feature = "fmt_flags", since = "1.5.0")]
1357 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1359 /// Determines if the `-` flag was specified.
1360 #[stable(feature = "fmt_flags", since = "1.5.0")]
1361 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1363 /// Determines if the `#` flag was specified.
1364 #[stable(feature = "fmt_flags", since = "1.5.0")]
1365 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1367 /// Determines if the `0` flag was specified.
1368 #[stable(feature = "fmt_flags", since = "1.5.0")]
1369 pub fn sign_aware_zero_pad(&self) -> bool {
1370 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1373 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1374 /// [`fmt::Debug`] implementations for structs.
1376 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1377 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1389 /// impl fmt::Debug for Foo {
1390 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1391 /// fmt.debug_struct("Foo")
1392 /// .field("bar", &self.bar)
1393 /// .field("baz", &self.baz)
1398 /// // prints "Foo { bar: 10, baz: "Hello World" }"
1399 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1401 #[stable(feature = "debug_builders", since = "1.2.0")]
1402 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1403 builders::debug_struct_new(self, name)
1406 /// Creates a `DebugTuple` builder designed to assist with creation of
1407 /// `fmt::Debug` implementations for tuple structs.
1414 /// struct Foo(i32, String);
1416 /// impl fmt::Debug for Foo {
1417 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1418 /// fmt.debug_tuple("Foo")
1425 /// // prints "Foo(10, "Hello World")"
1426 /// println!("{:?}", Foo(10, "Hello World".to_string()));
1428 #[stable(feature = "debug_builders", since = "1.2.0")]
1429 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1430 builders::debug_tuple_new(self, name)
1433 /// Creates a `DebugList` builder designed to assist with creation of
1434 /// `fmt::Debug` implementations for list-like structures.
1441 /// struct Foo(Vec<i32>);
1443 /// impl fmt::Debug for Foo {
1444 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1445 /// fmt.debug_list().entries(self.0.iter()).finish()
1449 /// // prints "[10, 11]"
1450 /// println!("{:?}", Foo(vec![10, 11]));
1452 #[stable(feature = "debug_builders", since = "1.2.0")]
1453 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1454 builders::debug_list_new(self)
1457 /// Creates a `DebugSet` builder designed to assist with creation of
1458 /// `fmt::Debug` implementations for set-like structures.
1465 /// struct Foo(Vec<i32>);
1467 /// impl fmt::Debug for Foo {
1468 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1469 /// fmt.debug_set().entries(self.0.iter()).finish()
1473 /// // prints "{10, 11}"
1474 /// println!("{:?}", Foo(vec![10, 11]));
1476 #[stable(feature = "debug_builders", since = "1.2.0")]
1477 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1478 builders::debug_set_new(self)
1481 /// Creates a `DebugMap` builder designed to assist with creation of
1482 /// `fmt::Debug` implementations for map-like structures.
1489 /// struct Foo(Vec<(String, i32)>);
1491 /// impl fmt::Debug for Foo {
1492 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1493 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1497 /// // prints "{"A": 10, "B": 11}"
1498 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1500 #[stable(feature = "debug_builders", since = "1.2.0")]
1501 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1502 builders::debug_map_new(self)
1506 #[stable(since = "1.2.0", feature = "formatter_write")]
1507 impl<'a> Write for Formatter<'a> {
1508 fn write_str(&mut self, s: &str) -> Result {
1509 self.buf.write_str(s)
1512 fn write_char(&mut self, c: char) -> Result {
1513 self.buf.write_char(c)
1516 fn write_fmt(&mut self, args: Arguments) -> Result {
1517 write(self.buf, args)
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 impl Display for Error {
1523 fn fmt(&self, f: &mut Formatter) -> Result {
1524 Display::fmt("an error occurred when formatting an argument", f)
1528 // Implementations of the core formatting traits
1530 macro_rules! fmt_refs {
1531 ($($tr:ident),*) => {
1533 #[stable(feature = "rust1", since = "1.0.0")]
1534 impl<'a, T: ?Sized + $tr> $tr for &'a T {
1535 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1539 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1545 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1547 #[unstable(feature = "never_type_impls", issue = "35121")]
1549 fn fmt(&self, _: &mut Formatter) -> Result {
1554 #[unstable(feature = "never_type_impls", issue = "35121")]
1555 impl Display for ! {
1556 fn fmt(&self, _: &mut Formatter) -> Result {
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl Debug for bool {
1563 fn fmt(&self, f: &mut Formatter) -> Result {
1564 Display::fmt(self, f)
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 impl Display for bool {
1570 fn fmt(&self, f: &mut Formatter) -> Result {
1571 Display::fmt(if *self { "true" } else { "false" }, f)
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl Debug for str {
1577 fn fmt(&self, f: &mut Formatter) -> Result {
1580 for (i, c) in self.char_indices() {
1581 let esc = c.escape_debug();
1582 // If char needs escaping, flush backlog so far and write, else skip
1584 f.write_str(&self[from..i])?;
1588 from = i + c.len_utf8();
1591 f.write_str(&self[from..])?;
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl Display for str {
1598 fn fmt(&self, f: &mut Formatter) -> Result {
1603 #[stable(feature = "rust1", since = "1.0.0")]
1604 impl Debug for char {
1605 fn fmt(&self, f: &mut Formatter) -> Result {
1606 f.write_char('\'')?;
1607 for c in self.escape_debug() {
1614 #[stable(feature = "rust1", since = "1.0.0")]
1615 impl Display for char {
1616 fn fmt(&self, f: &mut Formatter) -> Result {
1617 if f.width.is_none() && f.precision.is_none() {
1620 f.pad(self.encode_utf8(&mut [0; 4]))
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl<T: ?Sized> Pointer for *const T {
1627 fn fmt(&self, f: &mut Formatter) -> Result {
1628 let old_width = f.width;
1629 let old_flags = f.flags;
1631 // The alternate flag is already treated by LowerHex as being special-
1632 // it denotes whether to prefix with 0x. We use it to work out whether
1633 // or not to zero extend, and then unconditionally set it to get the
1636 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1638 if let None = f.width {
1639 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
1642 f.flags |= 1 << (FlagV1::Alternate as u32);
1644 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
1646 f.width = old_width;
1647 f.flags = old_flags;
1653 #[stable(feature = "rust1", since = "1.0.0")]
1654 impl<T: ?Sized> Pointer for *mut T {
1655 fn fmt(&self, f: &mut Formatter) -> Result {
1656 Pointer::fmt(&(*self as *const T), f)
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<'a, T: ?Sized> Pointer for &'a T {
1662 fn fmt(&self, f: &mut Formatter) -> Result {
1663 Pointer::fmt(&(*self as *const T), f)
1667 #[stable(feature = "rust1", since = "1.0.0")]
1668 impl<'a, T: ?Sized> Pointer for &'a mut T {
1669 fn fmt(&self, f: &mut Formatter) -> Result {
1670 Pointer::fmt(&(&**self as *const T), f)
1674 // Implementation of Display/Debug for various core types
1676 #[stable(feature = "rust1", since = "1.0.0")]
1677 impl<T: ?Sized> Debug for *const T {
1678 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 impl<T: ?Sized> Debug for *mut T {
1682 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1686 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1689 macro_rules! tuple {
1691 ( $($name:ident,)+ ) => (
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
1694 #[allow(non_snake_case, unused_assignments, deprecated)]
1695 fn fmt(&self, f: &mut Formatter) -> Result {
1696 let mut builder = f.debug_tuple("");
1697 let ($(ref $name,)*) = *self;
1699 builder.field(&$name);
1705 peel! { $($name,)* }
1709 macro_rules! last_type {
1710 ($a:ident,) => { $a };
1711 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
1714 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 impl<T: Debug> Debug for [T] {
1718 fn fmt(&self, f: &mut Formatter) -> Result {
1719 f.debug_list().entries(self.iter()).finish()
1723 #[stable(feature = "rust1", since = "1.0.0")]
1725 fn fmt(&self, f: &mut Formatter) -> Result {
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 impl<T: ?Sized> Debug for PhantomData<T> {
1731 fn fmt(&self, f: &mut Formatter) -> Result {
1732 f.pad("PhantomData")
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 impl<T: Copy + Debug> Debug for Cell<T> {
1738 fn fmt(&self, f: &mut Formatter) -> Result {
1739 f.debug_struct("Cell")
1740 .field("value", &self.get())
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1747 fn fmt(&self, f: &mut Formatter) -> Result {
1748 match self.try_borrow() {
1750 f.debug_struct("RefCell")
1751 .field("value", &borrow)
1755 // The RefCell is mutably borrowed so we can't look at its value
1756 // here. Show a placeholder instead.
1757 struct BorrowedPlaceholder;
1759 impl Debug for BorrowedPlaceholder {
1760 fn fmt(&self, f: &mut Formatter) -> Result {
1761 f.write_str("<borrowed>")
1765 f.debug_struct("RefCell")
1766 .field("value", &BorrowedPlaceholder)
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1775 fn fmt(&self, f: &mut Formatter) -> Result {
1776 Debug::fmt(&**self, f)
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1782 fn fmt(&self, f: &mut Formatter) -> Result {
1783 Debug::fmt(&*(self.deref()), f)
1787 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1788 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
1789 fn fmt(&self, f: &mut Formatter) -> Result {
1794 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1795 // it's a lot easier than creating all of the rt::Piece structures here.