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::Write` 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::Write`, and the
65 /// `io::Write` 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 Write (below) without
89 // requiring a `Sized` bound.
90 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
92 impl<'a, T: ?Sized> Write 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 (Write+'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 #[stable(feature = "rust1", since = "1.0.0")]
201 pub fn new_v1_formatted(pieces: &'a [&'a str],
202 args: &'a [ArgumentV1<'a>],
203 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
212 /// This structure represents a safely precompiled version of a format string
213 /// and its arguments. This cannot be generated at runtime because it cannot
214 /// safely be done so, so no constructors are given and the fields are private
215 /// to prevent modification.
217 /// The `format_args!` macro will safely create an instance of this structure
218 /// and pass it to a function or closure, passed as the first argument. The
219 /// macro validates the format string at compile-time so usage of the `write`
220 /// and `format` functions can be safely performed.
221 #[stable(feature = "rust1", since = "1.0.0")]
223 pub struct Arguments<'a> {
224 // Format string pieces to print.
225 pieces: &'a [&'a str],
227 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
228 fmt: Option<&'a [rt::v1::Argument]>,
230 // Dynamic arguments for interpolation, to be interleaved with string
231 // pieces. (Every argument is preceded by a string piece.)
232 args: &'a [ArgumentV1<'a>],
235 #[stable(feature = "rust1", since = "1.0.0")]
236 impl<'a> Debug for Arguments<'a> {
237 fn fmt(&self, fmt: &mut Formatter) -> Result {
238 Display::fmt(self, fmt)
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl<'a> Display for Arguments<'a> {
244 fn fmt(&self, fmt: &mut Formatter) -> Result {
245 write(fmt.buf, *self)
249 /// Format trait for the `:?` format. Useful for debugging, all types
250 /// should implement this.
251 #[deprecated(since = "1.0.0", reason = "renamed to Debug")]
252 #[unstable(feature = "old_fmt")]
254 /// Formats the value using the given formatter.
255 #[stable(feature = "rust1", since = "1.0.0")]
256 fn fmt(&self, &mut Formatter) -> Result;
259 /// Format trait for the `:?` format. Useful for debugging, all types
260 /// should implement this.
261 #[stable(feature = "rust1", since = "1.0.0")]
262 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
263 defined in your crate, add `#[derive(Debug)]` or \
264 manually implement it"]
265 #[lang = "debug_trait"]
267 /// Formats the value using the given formatter.
268 #[stable(feature = "rust1", since = "1.0.0")]
269 fn fmt(&self, &mut Formatter) -> Result;
273 impl<T: Show + ?Sized> Debug for T {
275 fn fmt(&self, f: &mut Formatter) -> Result { Show::fmt(self, f) }
278 /// When a value can be semantically expressed as a String, this trait may be
279 /// used. It corresponds to the default format, `{}`.
280 #[deprecated(since = "1.0.0", reason = "renamed to Display")]
281 #[unstable(feature = "old_fmt")]
283 /// Formats the value using the given formatter.
284 #[stable(feature = "rust1", since = "1.0.0")]
285 fn fmt(&self, &mut Formatter) -> Result;
288 /// When a value can be semantically expressed as a String, this trait may be
289 /// used. It corresponds to the default format, `{}`.
290 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
291 formatter; try using `:?` instead if you are using \
293 #[stable(feature = "rust1", since = "1.0.0")]
295 /// Formats the value using the given formatter.
296 #[stable(feature = "rust1", since = "1.0.0")]
297 fn fmt(&self, &mut Formatter) -> Result;
301 impl<T: String + ?Sized> Display for T {
303 fn fmt(&self, f: &mut Formatter) -> Result { String::fmt(self, f) }
306 /// Format trait for the `o` character
307 #[stable(feature = "rust1", since = "1.0.0")]
309 /// Formats the value using the given formatter.
310 #[stable(feature = "rust1", since = "1.0.0")]
311 fn fmt(&self, &mut Formatter) -> Result;
314 /// Format trait for the `b` character
315 #[stable(feature = "rust1", since = "1.0.0")]
317 /// Formats the value using the given formatter.
318 #[stable(feature = "rust1", since = "1.0.0")]
319 fn fmt(&self, &mut Formatter) -> Result;
322 /// Format trait for the `x` character
323 #[stable(feature = "rust1", since = "1.0.0")]
325 /// Formats the value using the given formatter.
326 #[stable(feature = "rust1", since = "1.0.0")]
327 fn fmt(&self, &mut Formatter) -> Result;
330 /// Format trait for the `X` character
331 #[stable(feature = "rust1", since = "1.0.0")]
333 /// Formats the value using the given formatter.
334 #[stable(feature = "rust1", since = "1.0.0")]
335 fn fmt(&self, &mut Formatter) -> Result;
338 /// Format trait for the `p` character
339 #[stable(feature = "rust1", since = "1.0.0")]
341 /// Formats the value using the given formatter.
342 #[stable(feature = "rust1", since = "1.0.0")]
343 fn fmt(&self, &mut Formatter) -> Result;
346 /// Format trait for the `e` character
347 #[stable(feature = "rust1", since = "1.0.0")]
349 /// Formats the value using the given formatter.
350 #[stable(feature = "rust1", since = "1.0.0")]
351 fn fmt(&self, &mut Formatter) -> Result;
354 /// Format trait for the `E` character
355 #[stable(feature = "rust1", since = "1.0.0")]
357 /// Formats the value using the given formatter.
358 #[stable(feature = "rust1", since = "1.0.0")]
359 fn fmt(&self, &mut Formatter) -> Result;
362 /// The `write` function takes an output stream, a precompiled format string,
363 /// and a list of arguments. The arguments will be formatted according to the
364 /// specified format string into the output stream provided.
368 /// * output - the buffer to write output to
369 /// * args - the precompiled arguments generated by `format_args!`
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn write(output: &mut Write, args: Arguments) -> Result {
372 let mut formatter = Formatter {
377 align: Alignment::Unknown,
380 curarg: args.args.iter(),
383 let mut pieces = args.pieces.iter();
387 // We can use default formatting parameters for all arguments.
388 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
389 try!(formatter.buf.write_str(*piece));
390 try!((arg.formatter)(arg.value, &mut formatter));
394 // Every spec has a corresponding argument that is preceded by
396 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
397 try!(formatter.buf.write_str(*piece));
398 try!(formatter.run(arg));
403 // There can be only one trailing string piece left.
404 match pieces.next() {
406 try!(formatter.buf.write_str(*piece));
414 impl<'a> Formatter<'a> {
416 // First up is the collection of functions used to execute a format string
417 // at runtime. This consumes all of the compile-time statics generated by
418 // the format! syntax extension.
419 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
420 // Fill in the format parameters into the formatter
421 self.fill = arg.format.fill;
422 self.align = arg.format.align;
423 self.flags = arg.format.flags;
424 self.width = self.getcount(&arg.format.width);
425 self.precision = self.getcount(&arg.format.precision);
427 // Extract the correct argument
428 let value = match arg.position {
429 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
430 rt::v1::Position::At(i) => self.args[i],
433 // Then actually do some printing
434 (value.formatter)(value.value, self)
437 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<uint> {
439 rt::v1::Count::Is(n) => Some(n),
440 rt::v1::Count::Implied => None,
441 rt::v1::Count::Param(i) => {
442 self.args[i].as_uint()
444 rt::v1::Count::NextParam => {
445 self.curarg.next().and_then(|arg| arg.as_uint())
450 // Helper methods used for padding and processing formatting arguments that
451 // all formatting traits can use.
453 /// Performs the correct padding for an integer which has already been
454 /// emitted into a str. The str should *not* contain the sign for the
455 /// integer, that will be added by this method.
459 /// * is_positive - whether the original integer was positive or not.
460 /// * prefix - if the '#' character (FlagAlternate) is provided, this
461 /// is the prefix to put in front of the number.
462 /// * buf - the byte array that the number has been formatted into
464 /// This function will correctly account for the flags provided as well as
465 /// the minimum width. It will not take precision into account.
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub fn pad_integral(&mut self,
474 let mut width = buf.len();
478 sign = Some('-'); width += 1;
479 } else if self.flags & (1 << (FlagV1::SignPlus as uint)) != 0 {
480 sign = Some('+'); width += 1;
483 let mut prefixed = false;
484 if self.flags & (1 << (FlagV1::Alternate as uint)) != 0 {
485 prefixed = true; width += prefix.char_len();
488 // Writes the sign if it exists, and then the prefix if it was requested
489 let write_prefix = |f: &mut Formatter| {
490 if let Some(c) = sign {
492 let n = c.encode_utf8(&mut b).unwrap_or(0);
493 let b = unsafe { str::from_utf8_unchecked(&b[..n]) };
494 try!(f.buf.write_str(b));
496 if prefixed { f.buf.write_str(prefix) }
500 // The `width` field is more of a `min-width` parameter at this point.
502 // If there's no minimum length requirements then we can just
505 try!(write_prefix(self)); self.buf.write_str(buf)
507 // Check if we're over the minimum width, if so then we can also
508 // just write the bytes.
509 Some(min) if width >= min => {
510 try!(write_prefix(self)); self.buf.write_str(buf)
512 // The sign and prefix goes before the padding if the fill character
514 Some(min) if self.flags & (1 << (FlagV1::SignAwareZeroPad as uint)) != 0 => {
516 try!(write_prefix(self));
517 self.with_padding(min - width, Alignment::Right, |f| {
521 // Otherwise, the sign and prefix goes after the padding
523 self.with_padding(min - width, Alignment::Right, |f| {
524 try!(write_prefix(f)); f.buf.write_str(buf)
530 /// This function takes a string slice and emits it to the internal buffer
531 /// after applying the relevant formatting flags specified. The flags
532 /// recognized for generic strings are:
534 /// * width - the minimum width of what to emit
535 /// * fill/align - what to emit and where to emit it if the string
536 /// provided needs to be padded
537 /// * precision - the maximum length to emit, the string is truncated if it
538 /// is longer than this length
540 /// Notably this function ignored the `flag` parameters
541 #[stable(feature = "rust1", since = "1.0.0")]
542 pub fn pad(&mut self, s: &str) -> Result {
543 // Make sure there's a fast path up front
544 if self.width.is_none() && self.precision.is_none() {
545 return self.buf.write_str(s);
547 // The `precision` field can be interpreted as a `max-width` for the
548 // string being formatted
549 match self.precision {
551 // If there's a maximum width and our string is longer than
552 // that, then we must always have truncation. This is the only
553 // case where the maximum length will matter.
554 let char_len = s.char_len();
556 let nchars = ::cmp::min(max, char_len);
557 return self.buf.write_str(s.slice_chars(0, nchars));
562 // The `width` field is more of a `min-width` parameter at this point.
564 // If we're under the maximum length, and there's no minimum length
565 // requirements, then we can just emit the string
566 None => self.buf.write_str(s),
567 // If we're under the maximum width, check if we're over the minimum
568 // width, if so it's as easy as just emitting the string.
569 Some(width) if s.char_len() >= width => {
570 self.buf.write_str(s)
572 // If we're under both the maximum and the minimum width, then fill
573 // up the minimum width with the specified string + some alignment.
575 self.with_padding(width - s.char_len(), Alignment::Left, |me| {
582 /// Runs a callback, emitting the correct padding either before or
583 /// afterwards depending on whether right or left alignment is requested.
584 fn with_padding<F>(&mut self, padding: uint, default: Alignment,
586 where F: FnOnce(&mut Formatter) -> Result,
589 let align = match self.align {
590 Alignment::Unknown => default,
594 let (pre_pad, post_pad) = match align {
595 Alignment::Left => (0, padding),
596 Alignment::Right | Alignment::Unknown => (padding, 0),
597 Alignment::Center => (padding / 2, (padding + 1) / 2),
600 let mut fill = [0u8; 4];
601 let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
602 let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) };
604 for _ in 0..pre_pad {
605 try!(self.buf.write_str(fill));
610 for _ in 0..post_pad {
611 try!(self.buf.write_str(fill));
617 /// Writes some data to the underlying buffer contained within this
619 #[stable(feature = "rust1", since = "1.0.0")]
620 pub fn write_str(&mut self, data: &str) -> Result {
621 self.buf.write_str(data)
624 /// Writes some formatted information into this instance
625 #[stable(feature = "rust1", since = "1.0.0")]
626 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
630 /// Flags for formatting (packed version of rt::Flag)
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn flags(&self) -> usize { self.flags }
634 /// Character used as 'fill' whenever there is alignment
635 #[unstable(feature = "core", reason = "method was just created")]
636 pub fn fill(&self) -> char { self.fill }
638 /// Flag indicating what form of alignment was requested
639 #[unstable(feature = "core", reason = "method was just created")]
640 pub fn align(&self) -> Alignment { self.align }
642 /// Optionally specified integer width that the output should be
643 #[unstable(feature = "core", reason = "method was just created")]
644 pub fn width(&self) -> Option<uint> { self.width }
646 /// Optionally specified precision for numeric types
647 #[unstable(feature = "core", reason = "method was just created")]
648 pub fn precision(&self) -> Option<uint> { self.precision }
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl Display for Error {
653 fn fmt(&self, f: &mut Formatter) -> Result {
654 Display::fmt("an error occurred when formatting an argument", f)
658 // Implementations of the core formatting traits
660 macro_rules! fmt_refs {
661 ($($tr:ident),*) => {
663 #[stable(feature = "rust1", since = "1.0.0")]
664 impl<'a, T: ?Sized + $tr> $tr for &'a T {
665 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
669 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
675 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl Debug for bool {
679 fn fmt(&self, f: &mut Formatter) -> Result {
680 Display::fmt(self, f)
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl Display for bool {
686 fn fmt(&self, f: &mut Formatter) -> Result {
687 Display::fmt(if *self { "true" } else { "false" }, f)
691 #[stable(feature = "rust1", since = "1.0.0")]
693 fn fmt(&self, f: &mut Formatter) -> Result {
694 try!(write!(f, "\""));
695 for c in self.chars().flat_map(|c| c.escape_default()) {
696 try!(write!(f, "{}", c));
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl Display for str {
704 fn fmt(&self, f: &mut Formatter) -> Result {
709 #[stable(feature = "rust1", since = "1.0.0")]
710 impl Debug for char {
711 fn fmt(&self, f: &mut Formatter) -> Result {
713 try!(write!(f, "'"));
714 for c in self.escape_default() {
715 try!(write!(f, "{}", c));
721 #[stable(feature = "rust1", since = "1.0.0")]
722 impl Display for char {
723 fn fmt(&self, f: &mut Formatter) -> Result {
724 let mut utf8 = [0u8; 4];
725 let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
726 let s: &str = unsafe { mem::transmute(&utf8[..amt]) };
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl<T> Pointer for *const T {
733 fn fmt(&self, f: &mut Formatter) -> Result {
734 f.flags |= 1 << (FlagV1::Alternate as uint);
735 let ret = LowerHex::fmt(&(*self as uint), f);
736 f.flags &= !(1 << (FlagV1::Alternate as uint));
741 #[stable(feature = "rust1", since = "1.0.0")]
742 impl<T> Pointer for *mut T {
743 fn fmt(&self, f: &mut Formatter) -> Result {
744 Pointer::fmt(&(*self as *const T), f)
748 #[stable(feature = "rust1", since = "1.0.0")]
749 impl<'a, T> Pointer for &'a T {
750 fn fmt(&self, f: &mut Formatter) -> Result {
751 Pointer::fmt(&(*self as *const T), f)
755 #[stable(feature = "rust1", since = "1.0.0")]
756 impl<'a, T> Pointer for &'a mut T {
757 fn fmt(&self, f: &mut Formatter) -> Result {
758 Pointer::fmt(&(&**self as *const T), f)
762 macro_rules! floating { ($ty:ident) => {
764 #[stable(feature = "rust1", since = "1.0.0")]
766 fn fmt(&self, fmt: &mut Formatter) -> Result {
767 Display::fmt(self, fmt)
771 #[stable(feature = "rust1", since = "1.0.0")]
772 impl Display for $ty {
773 fn fmt(&self, fmt: &mut Formatter) -> Result {
776 let digits = match fmt.precision {
777 Some(i) => float::DigExact(i),
778 None => float::DigMax(6),
780 float::float_to_str_bytes_common(self.abs(),
788 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
793 #[stable(feature = "rust1", since = "1.0.0")]
794 impl LowerExp for $ty {
795 fn fmt(&self, fmt: &mut Formatter) -> Result {
798 let digits = match fmt.precision {
799 Some(i) => float::DigExact(i),
800 None => float::DigMax(6),
802 float::float_to_str_bytes_common(self.abs(),
810 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
815 #[stable(feature = "rust1", since = "1.0.0")]
816 impl UpperExp for $ty {
817 fn fmt(&self, fmt: &mut Formatter) -> Result {
820 let digits = match fmt.precision {
821 Some(i) => float::DigExact(i),
822 None => float::DigMax(6),
824 float::float_to_str_bytes_common(self.abs(),
832 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
840 // Implementation of Display/Debug for various core types
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<T> Debug for *const T {
844 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl<T> Debug for *mut T {
848 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
852 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
857 ( $($name:ident,)+ ) => (
858 #[stable(feature = "rust1", since = "1.0.0")]
859 impl<$($name:Debug),*> Debug for ($($name,)*) {
860 #[allow(non_snake_case, unused_assignments)]
861 fn fmt(&self, f: &mut Formatter) -> Result {
862 try!(write!(f, "("));
863 let ($(ref $name,)*) = *self;
867 try!(write!(f, ", "));
869 try!(write!(f, "{:?}", *$name));
873 try!(write!(f, ","));
882 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl<'a> Debug for &'a (any::Any+'a) {
886 fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") }
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl<T: Debug> Debug for [T] {
891 fn fmt(&self, f: &mut Formatter) -> Result {
892 if f.flags & (1 << (FlagV1::Alternate as uint)) == 0 {
893 try!(write!(f, "["));
895 let mut is_first = true;
900 try!(write!(f, ", "));
902 try!(write!(f, "{:?}", *x))
904 if f.flags & (1 << (FlagV1::Alternate as uint)) == 0 {
905 try!(write!(f, "]"));
911 #[stable(feature = "rust1", since = "1.0.0")]
913 fn fmt(&self, f: &mut Formatter) -> Result {
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl<T: Copy + Debug> Debug for Cell<T> {
920 fn fmt(&self, f: &mut Formatter) -> Result {
921 write!(f, "Cell {{ value: {:?} }}", self.get())
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<T: Debug> Debug for RefCell<T> {
927 fn fmt(&self, f: &mut Formatter) -> Result {
928 match self.borrow_state() {
929 BorrowState::Unused | BorrowState::Reading => {
930 write!(f, "RefCell {{ value: {:?} }}", self.borrow())
932 BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'b, T: Debug> Debug for Ref<'b, T> {
939 fn fmt(&self, f: &mut Formatter) -> Result {
940 Debug::fmt(&**self, f)
944 #[stable(feature = "rust1", since = "1.0.0")]
945 impl<'b, T: Debug> Debug for RefMut<'b, T> {
946 fn fmt(&self, f: &mut Formatter) -> Result {
947 Debug::fmt(&*(self.deref()), f)
951 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
952 // it's a lot easier than creating all of the rt::Piece structures here.