1 // Copyright 2013-2014 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")]
16 use cell::{Cell, RefCell, Ref, RefMut, BorrowState};
18 use iter::{Iterator, IteratorExt};
19 use marker::{Copy, Sized};
22 use option::Option::{Some, None};
23 use result::Result::Ok;
24 use ops::{Deref, FnOnce};
28 use str::{self, StrExt};
29 use self::rt::v1::Alignment;
31 pub use self::num::radix;
32 pub use self::num::Radix;
33 pub use self::num::RadixFmt;
38 #[stable(feature = "rust1", since = "1.0.0")]
44 #[stable(feature = "rust1", since = "1.0.0")]
45 /// The type returned by formatter methods.
46 pub type Result = result::Result<(), Error>;
48 /// The error type which is returned from formatting a message into a stream.
50 /// This type does not support transmission of an error other than that an error
51 /// occurred. Any extra information must be arranged to be transmitted through
53 #[stable(feature = "rust1", since = "1.0.0")]
54 #[derive(Copy, Debug)]
57 /// A collection of methods that are required to format a message into a stream.
59 /// This trait is the type which this modules requires when formatting
60 /// information. This is similar to the standard library's `io::Writer` trait,
61 /// but it is only intended for use in libcore.
63 /// This trait should generally not be implemented by consumers of the standard
64 /// library. The `write!` macro accepts an instance of `io::Writer`, and the
65 /// `io::Writer` trait is favored over implementing this trait.
66 #[stable(feature = "rust1", since = "1.0.0")]
68 /// Writes a slice of bytes into this writer, returning whether the write
71 /// This method can only succeed if the entire byte slice was successfully
72 /// written, and this method will not return until all data has been
73 /// written or an error occurs.
77 /// This function will return an instance of `FormatError` on error.
78 #[stable(feature = "rust1", since = "1.0.0")]
79 fn write_str(&mut self, s: &str) -> Result;
81 /// Glue for usage of the `write!` macro with implementers of this trait.
83 /// This method should generally not be invoked manually, but rather through
84 /// the `write!` macro itself.
85 #[stable(feature = "rust1", since = "1.0.0")]
86 fn write_fmt(&mut self, args: Arguments) -> Result {
87 // This Adapter is needed to allow `self` (of type `&mut
88 // Self`) to be cast to a FormatWriter (below) without
89 // requiring a `Sized` bound.
90 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
92 impl<'a, T: ?Sized> Writer for Adapter<'a, T>
95 fn write_str(&mut self, s: &str) -> Result {
99 fn write_fmt(&mut self, args: Arguments) -> Result {
100 self.0.write_fmt(args)
104 write(&mut Adapter(self), args)
108 /// A struct to represent both where to emit formatting strings to and how they
109 /// should be formatted. A mutable version of this is passed to all formatting
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct Formatter<'a> {
115 align: rt::v1::Alignment,
117 precision: Option<uint>,
119 buf: &'a mut (Writer+'a),
120 curarg: slice::Iter<'a, ArgumentV1<'a>>,
121 args: &'a [ArgumentV1<'a>],
124 // NB. Argument is essentially an optimized partially applied formatting function,
125 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
129 /// This struct represents the generic "argument" which is taken by the Xprintf
130 /// family of functions. It contains a function to format the given value. At
131 /// compile time it is ensured that the function and the value have the correct
132 /// types, and then this struct is used to canonicalize arguments to one type.
134 #[stable(feature = "rust1", since = "1.0.0")]
136 pub struct ArgumentV1<'a> {
138 formatter: fn(&Void, &mut Formatter) -> Result,
141 impl<'a> ArgumentV1<'a> {
143 fn show_uint(x: &uint, f: &mut Formatter) -> Result {
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub fn new<'b, T>(x: &'b T,
150 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
153 formatter: mem::transmute(f),
154 value: mem::transmute(x)
160 #[stable(feature = "rust1", since = "1.0.0")]
161 pub fn from_uint(x: &uint) -> ArgumentV1 {
162 ArgumentV1::new(x, ArgumentV1::show_uint)
165 fn as_uint(&self) -> Option<uint> {
166 if self.formatter as uint == ArgumentV1::show_uint as uint {
167 Some(unsafe { *(self.value as *const _ as *const uint) })
174 // flags available in the v1 format of format_args
176 #[allow(dead_code)] // SignMinus isn't currently used
177 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
179 impl<'a> Arguments<'a> {
180 /// When using the format_args!() macro, this function is used to generate the
181 /// Arguments structure.
182 #[doc(hidden)] #[inline]
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub fn new_v1(pieces: &'a [&'a str],
185 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
193 /// This function is used to specify nonstandard formatting parameters.
194 /// The `pieces` array must be at least as long as `fmt` to construct
195 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
196 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
197 /// created with `argumentuint`. However, failing to do so doesn't cause
198 /// unsafety, but will ignore invalid .
199 #[doc(hidden)] #[inline]
200 pub fn new_v1_formatted(pieces: &'a [&'a str],
201 args: &'a [ArgumentV1<'a>],
202 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
211 /// This structure represents a safely precompiled version of a format string
212 /// and its arguments. This cannot be generated at runtime because it cannot
213 /// safely be done so, so no constructors are given and the fields are private
214 /// to prevent modification.
216 /// The `format_args!` macro will safely create an instance of this structure
217 /// and pass it to a function or closure, passed as the first argument. The
218 /// macro validates the format string at compile-time so usage of the `write`
219 /// and `format` functions can be safely performed.
220 #[stable(feature = "rust1", since = "1.0.0")]
222 pub struct Arguments<'a> {
223 // Format string pieces to print.
224 pieces: &'a [&'a str],
226 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
227 fmt: Option<&'a [rt::v1::Argument]>,
229 // Dynamic arguments for interpolation, to be interleaved with string
230 // pieces. (Every argument is preceded by a string piece.)
231 args: &'a [ArgumentV1<'a>],
234 #[stable(feature = "rust1", since = "1.0.0")]
235 impl<'a> Debug for Arguments<'a> {
236 fn fmt(&self, fmt: &mut Formatter) -> Result {
237 Display::fmt(self, fmt)
241 #[stable(feature = "rust1", since = "1.0.0")]
242 impl<'a> Display for Arguments<'a> {
243 fn fmt(&self, fmt: &mut Formatter) -> Result {
244 write(fmt.buf, *self)
248 /// Format trait for the `:?` format. Useful for debugging, all types
249 /// should implement this.
250 #[deprecated(since = "1.0.0", reason = "renamed to Debug")]
251 #[unstable(feature = "old_fmt")]
253 /// Formats the value using the given formatter.
254 #[stable(feature = "rust1", since = "1.0.0")]
255 fn fmt(&self, &mut Formatter) -> Result;
258 /// Format trait for the `:?` format. Useful for debugging, all types
259 /// should implement this.
260 #[stable(feature = "rust1", since = "1.0.0")]
261 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
262 defined in your crate, add `#[derive(Debug)]` or \
263 manually implement it"]
264 #[lang = "debug_trait"]
266 /// Formats the value using the given formatter.
267 #[stable(feature = "rust1", since = "1.0.0")]
268 fn fmt(&self, &mut Formatter) -> Result;
272 impl<T: Show + ?Sized> Debug for T {
274 fn fmt(&self, f: &mut Formatter) -> Result { Show::fmt(self, f) }
277 /// When a value can be semantically expressed as a String, this trait may be
278 /// used. It corresponds to the default format, `{}`.
279 #[deprecated(since = "1.0.0", reason = "renamed to Display")]
280 #[unstable(feature = "old_fmt")]
282 /// Formats the value using the given formatter.
283 #[stable(feature = "rust1", since = "1.0.0")]
284 fn fmt(&self, &mut Formatter) -> Result;
287 /// When a value can be semantically expressed as a String, this trait may be
288 /// used. It corresponds to the default format, `{}`.
289 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
290 formatter; try using `:?` instead if you are using \
292 #[stable(feature = "rust1", since = "1.0.0")]
294 /// Formats the value using the given formatter.
295 #[stable(feature = "rust1", since = "1.0.0")]
296 fn fmt(&self, &mut Formatter) -> Result;
300 impl<T: String + ?Sized> Display for T {
302 fn fmt(&self, f: &mut Formatter) -> Result { String::fmt(self, f) }
305 /// Format trait for the `o` character
306 #[stable(feature = "rust1", since = "1.0.0")]
308 /// Formats the value using the given formatter.
309 #[stable(feature = "rust1", since = "1.0.0")]
310 fn fmt(&self, &mut Formatter) -> Result;
313 /// Format trait for the `b` character
314 #[stable(feature = "rust1", since = "1.0.0")]
316 /// Formats the value using the given formatter.
317 #[stable(feature = "rust1", since = "1.0.0")]
318 fn fmt(&self, &mut Formatter) -> Result;
321 /// Format trait for the `x` character
322 #[stable(feature = "rust1", since = "1.0.0")]
324 /// Formats the value using the given formatter.
325 #[stable(feature = "rust1", since = "1.0.0")]
326 fn fmt(&self, &mut Formatter) -> Result;
329 /// Format trait for the `X` character
330 #[stable(feature = "rust1", since = "1.0.0")]
332 /// Formats the value using the given formatter.
333 #[stable(feature = "rust1", since = "1.0.0")]
334 fn fmt(&self, &mut Formatter) -> Result;
337 /// Format trait for the `p` character
338 #[stable(feature = "rust1", since = "1.0.0")]
340 /// Formats the value using the given formatter.
341 #[stable(feature = "rust1", since = "1.0.0")]
342 fn fmt(&self, &mut Formatter) -> Result;
345 /// Format trait for the `e` character
346 #[stable(feature = "rust1", since = "1.0.0")]
348 /// Formats the value using the given formatter.
349 #[stable(feature = "rust1", since = "1.0.0")]
350 fn fmt(&self, &mut Formatter) -> Result;
353 /// Format trait for the `E` character
354 #[stable(feature = "rust1", since = "1.0.0")]
356 /// Formats the value using the given formatter.
357 #[stable(feature = "rust1", since = "1.0.0")]
358 fn fmt(&self, &mut Formatter) -> Result;
361 /// The `write` function takes an output stream, a precompiled format string,
362 /// and a list of arguments. The arguments will be formatted according to the
363 /// specified format string into the output stream provided.
367 /// * output - the buffer to write output to
368 /// * args - the precompiled arguments generated by `format_args!`
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn write(output: &mut Writer, args: Arguments) -> Result {
371 let mut formatter = Formatter {
376 align: Alignment::Unknown,
379 curarg: args.args.iter(),
382 let mut pieces = args.pieces.iter();
386 // We can use default formatting parameters for all arguments.
387 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
388 try!(formatter.buf.write_str(*piece));
389 try!((arg.formatter)(arg.value, &mut formatter));
393 // Every spec has a corresponding argument that is preceded by
395 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
396 try!(formatter.buf.write_str(*piece));
397 try!(formatter.run(arg));
402 // There can be only one trailing string piece left.
403 match pieces.next() {
405 try!(formatter.buf.write_str(*piece));
413 impl<'a> Formatter<'a> {
415 // First up is the collection of functions used to execute a format string
416 // at runtime. This consumes all of the compile-time statics generated by
417 // the format! syntax extension.
418 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
419 // Fill in the format parameters into the formatter
420 self.fill = arg.format.fill;
421 self.align = arg.format.align;
422 self.flags = arg.format.flags;
423 self.width = self.getcount(&arg.format.width);
424 self.precision = self.getcount(&arg.format.precision);
426 // Extract the correct argument
427 let value = match arg.position {
428 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
429 rt::v1::Position::At(i) => self.args[i],
432 // Then actually do some printing
433 (value.formatter)(value.value, self)
436 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<uint> {
438 rt::v1::Count::Is(n) => Some(n),
439 rt::v1::Count::Implied => None,
440 rt::v1::Count::Param(i) => {
441 self.args[i].as_uint()
443 rt::v1::Count::NextParam => {
444 self.curarg.next().and_then(|arg| arg.as_uint())
449 // Helper methods used for padding and processing formatting arguments that
450 // all formatting traits can use.
452 /// Performs the correct padding for an integer which has already been
453 /// emitted into a str. The str should *not* contain the sign for the
454 /// integer, that will be added by this method.
458 /// * is_positive - whether the original integer was positive or not.
459 /// * prefix - if the '#' character (FlagAlternate) is provided, this
460 /// is the prefix to put in front of the number.
461 /// * buf - the byte array that the number has been formatted into
463 /// This function will correctly account for the flags provided as well as
464 /// the minimum width. It will not take precision into account.
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn pad_integral(&mut self,
473 let mut width = buf.len();
477 sign = Some('-'); width += 1;
478 } else if self.flags & (1 << (FlagV1::SignPlus as uint)) != 0 {
479 sign = Some('+'); width += 1;
482 let mut prefixed = false;
483 if self.flags & (1 << (FlagV1::Alternate as uint)) != 0 {
484 prefixed = true; width += prefix.char_len();
487 // Writes the sign if it exists, and then the prefix if it was requested
488 let write_prefix = |f: &mut Formatter| {
489 if let Some(c) = sign {
491 let n = c.encode_utf8(&mut b).unwrap_or(0);
492 let b = unsafe { str::from_utf8_unchecked(&b[..n]) };
493 try!(f.buf.write_str(b));
495 if prefixed { f.buf.write_str(prefix) }
499 // The `width` field is more of a `min-width` parameter at this point.
501 // If there's no minimum length requirements then we can just
504 try!(write_prefix(self)); self.buf.write_str(buf)
506 // Check if we're over the minimum width, if so then we can also
507 // just write the bytes.
508 Some(min) if width >= min => {
509 try!(write_prefix(self)); self.buf.write_str(buf)
511 // The sign and prefix goes before the padding if the fill character
513 Some(min) if self.flags & (1 << (FlagV1::SignAwareZeroPad as uint)) != 0 => {
515 try!(write_prefix(self));
516 self.with_padding(min - width, Alignment::Right, |f| {
520 // Otherwise, the sign and prefix goes after the padding
522 self.with_padding(min - width, Alignment::Right, |f| {
523 try!(write_prefix(f)); f.buf.write_str(buf)
529 /// This function takes a string slice and emits it to the internal buffer
530 /// after applying the relevant formatting flags specified. The flags
531 /// recognized for generic strings are:
533 /// * width - the minimum width of what to emit
534 /// * fill/align - what to emit and where to emit it if the string
535 /// provided needs to be padded
536 /// * precision - the maximum length to emit, the string is truncated if it
537 /// is longer than this length
539 /// Notably this function ignored the `flag` parameters
540 #[stable(feature = "rust1", since = "1.0.0")]
541 pub fn pad(&mut self, s: &str) -> Result {
542 // Make sure there's a fast path up front
543 if self.width.is_none() && self.precision.is_none() {
544 return self.buf.write_str(s);
546 // The `precision` field can be interpreted as a `max-width` for the
547 // string being formatted
548 match self.precision {
550 // If there's a maximum width and our string is longer than
551 // that, then we must always have truncation. This is the only
552 // case where the maximum length will matter.
553 let char_len = s.char_len();
555 let nchars = ::cmp::min(max, char_len);
556 return self.buf.write_str(s.slice_chars(0, nchars));
561 // The `width` field is more of a `min-width` parameter at this point.
563 // If we're under the maximum length, and there's no minimum length
564 // requirements, then we can just emit the string
565 None => self.buf.write_str(s),
566 // If we're under the maximum width, check if we're over the minimum
567 // width, if so it's as easy as just emitting the string.
568 Some(width) if s.char_len() >= width => {
569 self.buf.write_str(s)
571 // If we're under both the maximum and the minimum width, then fill
572 // up the minimum width with the specified string + some alignment.
574 self.with_padding(width - s.char_len(), Alignment::Left, |me| {
581 /// Runs a callback, emitting the correct padding either before or
582 /// afterwards depending on whether right or left alignment is requested.
583 fn with_padding<F>(&mut self, padding: uint, default: Alignment,
585 where F: FnOnce(&mut Formatter) -> Result,
588 let align = match self.align {
589 Alignment::Unknown => default,
593 let (pre_pad, post_pad) = match align {
594 Alignment::Left => (0, padding),
595 Alignment::Right | Alignment::Unknown => (padding, 0),
596 Alignment::Center => (padding / 2, (padding + 1) / 2),
599 let mut fill = [0u8; 4];
600 let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
601 let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) };
603 for _ in 0..pre_pad {
604 try!(self.buf.write_str(fill));
609 for _ in 0..post_pad {
610 try!(self.buf.write_str(fill));
616 /// Writes some data to the underlying buffer contained within this
618 #[stable(feature = "rust1", since = "1.0.0")]
619 pub fn write_str(&mut self, data: &str) -> Result {
620 self.buf.write_str(data)
623 /// Writes some formatted information into this instance
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
629 /// Flags for formatting (packed version of rt::Flag)
630 #[stable(feature = "rust1", since = "1.0.0")]
631 pub fn flags(&self) -> usize { self.flags }
633 /// Character used as 'fill' whenever there is alignment
634 #[unstable(feature = "core", reason = "method was just created")]
635 pub fn fill(&self) -> char { self.fill }
637 /// Flag indicating what form of alignment was requested
638 #[unstable(feature = "core", reason = "method was just created")]
639 pub fn align(&self) -> Alignment { self.align }
641 /// Optionally specified integer width that the output should be
642 #[unstable(feature = "core", reason = "method was just created")]
643 pub fn width(&self) -> Option<uint> { self.width }
645 /// Optionally specified precision for numeric types
646 #[unstable(feature = "core", reason = "method was just created")]
647 pub fn precision(&self) -> Option<uint> { self.precision }
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl Display for Error {
652 fn fmt(&self, f: &mut Formatter) -> Result {
653 Display::fmt("an error occurred when formatting an argument", f)
657 // Implementations of the core formatting traits
659 macro_rules! fmt_refs {
660 ($($tr:ident),*) => {
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl<'a, T: ?Sized + $tr> $tr for &'a T {
664 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
666 #[stable(feature = "rust1", since = "1.0.0")]
667 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
668 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
674 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl Debug for bool {
678 fn fmt(&self, f: &mut Formatter) -> Result {
679 Display::fmt(self, f)
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl Display for bool {
685 fn fmt(&self, f: &mut Formatter) -> Result {
686 Display::fmt(if *self { "true" } else { "false" }, f)
690 #[stable(feature = "rust1", since = "1.0.0")]
692 fn fmt(&self, f: &mut Formatter) -> Result {
693 try!(write!(f, "\""));
694 for c in self.chars().flat_map(|c| c.escape_default()) {
695 try!(write!(f, "{}", c));
701 #[stable(feature = "rust1", since = "1.0.0")]
702 impl Display for str {
703 fn fmt(&self, f: &mut Formatter) -> Result {
708 #[stable(feature = "rust1", since = "1.0.0")]
709 impl Debug for char {
710 fn fmt(&self, f: &mut Formatter) -> Result {
712 try!(write!(f, "'"));
713 for c in self.escape_default() {
714 try!(write!(f, "{}", c));
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl Display for char {
722 fn fmt(&self, f: &mut Formatter) -> Result {
723 let mut utf8 = [0u8; 4];
724 let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
725 let s: &str = unsafe { mem::transmute(&utf8[..amt]) };
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl<T> Pointer for *const T {
732 fn fmt(&self, f: &mut Formatter) -> Result {
733 f.flags |= 1 << (FlagV1::Alternate as uint);
734 let ret = LowerHex::fmt(&(*self as uint), f);
735 f.flags &= !(1 << (FlagV1::Alternate as uint));
740 #[stable(feature = "rust1", since = "1.0.0")]
741 impl<T> Pointer for *mut T {
742 fn fmt(&self, f: &mut Formatter) -> Result {
743 Pointer::fmt(&(*self as *const T), f)
747 #[stable(feature = "rust1", since = "1.0.0")]
748 impl<'a, T> Pointer for &'a T {
749 fn fmt(&self, f: &mut Formatter) -> Result {
750 Pointer::fmt(&(*self as *const T), f)
754 #[stable(feature = "rust1", since = "1.0.0")]
755 impl<'a, T> Pointer for &'a mut T {
756 fn fmt(&self, f: &mut Formatter) -> Result {
757 Pointer::fmt(&(&**self as *const T), f)
761 macro_rules! floating { ($ty:ident) => {
763 #[stable(feature = "rust1", since = "1.0.0")]
765 fn fmt(&self, fmt: &mut Formatter) -> Result {
766 Display::fmt(self, fmt)
770 #[stable(feature = "rust1", since = "1.0.0")]
771 impl Display for $ty {
772 fn fmt(&self, fmt: &mut Formatter) -> Result {
775 let digits = match fmt.precision {
776 Some(i) => float::DigExact(i),
777 None => float::DigMax(6),
779 float::float_to_str_bytes_common(self.abs(),
787 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl LowerExp for $ty {
794 fn fmt(&self, fmt: &mut Formatter) -> Result {
797 let digits = match fmt.precision {
798 Some(i) => float::DigExact(i),
799 None => float::DigMax(6),
801 float::float_to_str_bytes_common(self.abs(),
809 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl UpperExp for $ty {
816 fn fmt(&self, fmt: &mut Formatter) -> Result {
819 let digits = match fmt.precision {
820 Some(i) => float::DigExact(i),
821 None => float::DigMax(6),
823 float::float_to_str_bytes_common(self.abs(),
831 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
839 // Implementation of Display/Debug for various core types
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<T> Debug for *const T {
843 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
845 #[stable(feature = "rust1", since = "1.0.0")]
846 impl<T> Debug for *mut T {
847 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
851 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
856 ( $($name:ident,)+ ) => (
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<$($name:Debug),*> Debug for ($($name,)*) {
859 #[allow(non_snake_case, unused_assignments)]
860 fn fmt(&self, f: &mut Formatter) -> Result {
861 try!(write!(f, "("));
862 let ($(ref $name,)*) = *self;
866 try!(write!(f, ", "));
868 try!(write!(f, "{:?}", *$name));
872 try!(write!(f, ","));
881 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl<'a> Debug for &'a (any::Any+'a) {
885 fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") }
888 #[stable(feature = "rust1", since = "1.0.0")]
889 impl<T: Debug> Debug for [T] {
890 fn fmt(&self, f: &mut Formatter) -> Result {
891 if f.flags & (1 << (FlagV1::Alternate as uint)) == 0 {
892 try!(write!(f, "["));
894 let mut is_first = true;
899 try!(write!(f, ", "));
901 try!(write!(f, "{:?}", *x))
903 if f.flags & (1 << (FlagV1::Alternate as uint)) == 0 {
904 try!(write!(f, "]"));
910 #[stable(feature = "rust1", since = "1.0.0")]
912 fn fmt(&self, f: &mut Formatter) -> Result {
917 #[stable(feature = "rust1", since = "1.0.0")]
918 impl<T: Copy + Debug> Debug for Cell<T> {
919 fn fmt(&self, f: &mut Formatter) -> Result {
920 write!(f, "Cell {{ value: {:?} }}", self.get())
924 #[stable(feature = "rust1", since = "1.0.0")]
925 impl<T: Debug> Debug for RefCell<T> {
926 fn fmt(&self, f: &mut Formatter) -> Result {
927 match self.borrow_state() {
928 BorrowState::Unused | BorrowState::Reading => {
929 write!(f, "RefCell {{ value: {:?} }}", self.borrow())
931 BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<'b, T: Debug> Debug for Ref<'b, T> {
938 fn fmt(&self, f: &mut Formatter) -> Result {
939 Debug::fmt(&**self, f)
943 #[stable(feature = "rust1", since = "1.0.0")]
944 impl<'b, T: Debug> Debug for RefMut<'b, T> {
945 fn fmt(&self, f: &mut Formatter) -> Result {
946 Debug::fmt(&*(self.deref()), f)
950 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
951 // it's a lot easier than creating all of the rt::Piece structures here.