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")]
15 use cell::{Cell, RefCell, Ref, RefMut, BorrowState};
18 use marker::{Copy, PhantomData, Sized};
21 use option::Option::{Some, None};
22 use result::Result::Ok;
23 use ops::{Deref, FnOnce};
27 use str::{self, StrExt};
28 use self::rt::v1::Alignment;
30 pub use self::num::radix;
31 pub use self::num::Radix;
32 pub use self::num::RadixFmt;
34 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
40 #[stable(feature = "rust1", since = "1.0.0")]
46 #[stable(feature = "rust1", since = "1.0.0")]
47 /// The type returned by formatter methods.
48 pub type Result = result::Result<(), Error>;
50 /// The error type which is returned from formatting a message into a stream.
52 /// This type does not support transmission of an error other than that an error
53 /// occurred. Any extra information must be arranged to be transmitted through
55 #[stable(feature = "rust1", since = "1.0.0")]
56 #[derive(Copy, Debug)]
59 /// A collection of methods that are required to format a message into a stream.
61 /// This trait is the type which this modules requires when formatting
62 /// information. This is similar to the standard library's `io::Write` trait,
63 /// but it is only intended for use in libcore.
65 /// This trait should generally not be implemented by consumers of the standard
66 /// library. The `write!` macro accepts an instance of `io::Write`, and the
67 /// `io::Write` trait is favored over implementing this trait.
68 #[stable(feature = "rust1", since = "1.0.0")]
70 /// Writes a slice of bytes into this writer, returning whether the write
73 /// This method can only succeed if the entire byte slice was successfully
74 /// written, and this method will not return until all data has been
75 /// written or an error occurs.
79 /// This function will return an instance of `FormatError` on error.
80 #[stable(feature = "rust1", since = "1.0.0")]
81 fn write_str(&mut self, s: &str) -> Result;
83 /// Glue for usage of the `write!` macro with implementers of this trait.
85 /// This method should generally not be invoked manually, but rather through
86 /// the `write!` macro itself.
87 #[stable(feature = "rust1", since = "1.0.0")]
88 fn write_fmt(&mut self, args: Arguments) -> Result {
89 // This Adapter is needed to allow `self` (of type `&mut
90 // Self`) to be cast to a Write (below) without
91 // requiring a `Sized` bound.
92 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
94 impl<'a, T: ?Sized> Write for Adapter<'a, T>
97 fn write_str(&mut self, s: &str) -> Result {
101 fn write_fmt(&mut self, args: Arguments) -> Result {
102 self.0.write_fmt(args)
106 write(&mut Adapter(self), args)
110 /// A struct to represent both where to emit formatting strings to and how they
111 /// should be formatted. A mutable version of this is passed to all formatting
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub struct Formatter<'a> {
117 align: rt::v1::Alignment,
118 width: Option<usize>,
119 precision: Option<usize>,
121 buf: &'a mut (Write+'a),
122 curarg: slice::Iter<'a, ArgumentV1<'a>>,
123 args: &'a [ArgumentV1<'a>],
126 // NB. Argument is essentially an optimized partially applied formatting function,
127 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
131 /// This struct represents the generic "argument" which is taken by the Xprintf
132 /// family of functions. It contains a function to format the given value. At
133 /// compile time it is ensured that the function and the value have the correct
134 /// types, and then this struct is used to canonicalize arguments to one type.
136 #[stable(feature = "rust1", since = "1.0.0")]
138 pub struct ArgumentV1<'a> {
140 formatter: fn(&Void, &mut Formatter) -> Result,
143 impl<'a> ArgumentV1<'a> {
145 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub fn new<'b, T>(x: &'b T,
152 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
155 formatter: mem::transmute(f),
156 value: mem::transmute(x)
162 #[stable(feature = "rust1", since = "1.0.0")]
163 pub fn from_usize(x: &usize) -> ArgumentV1 {
164 ArgumentV1::new(x, ArgumentV1::show_usize)
167 fn as_usize(&self) -> Option<usize> {
168 if self.formatter as usize == ArgumentV1::show_usize as usize {
169 Some(unsafe { *(self.value as *const _ as *const usize) })
176 // flags available in the v1 format of format_args
178 #[allow(dead_code)] // SignMinus isn't currently used
179 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
181 impl<'a> Arguments<'a> {
182 /// When using the format_args!() macro, this function is used to generate the
183 /// Arguments structure.
184 #[doc(hidden)] #[inline]
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub fn new_v1(pieces: &'a [&'a str],
187 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
195 /// This function is used to specify nonstandard formatting parameters.
196 /// The `pieces` array must be at least as long as `fmt` to construct
197 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
198 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
199 /// created with `argumentusize`. However, failing to do so doesn't cause
200 /// unsafety, but will ignore invalid .
201 #[doc(hidden)] #[inline]
202 #[stable(feature = "rust1", since = "1.0.0")]
203 pub fn new_v1_formatted(pieces: &'a [&'a str],
204 args: &'a [ArgumentV1<'a>],
205 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
214 /// This structure represents a safely precompiled version of a format string
215 /// and its arguments. This cannot be generated at runtime because it cannot
216 /// safely be done so, so no constructors are given and the fields are private
217 /// to prevent modification.
219 /// The `format_args!` macro will safely create an instance of this structure
220 /// and pass it to a function or closure, passed as the first argument. The
221 /// macro validates the format string at compile-time so usage of the `write`
222 /// and `format` functions can be safely performed.
223 #[stable(feature = "rust1", since = "1.0.0")]
225 pub struct Arguments<'a> {
226 // Format string pieces to print.
227 pieces: &'a [&'a str],
229 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
230 fmt: Option<&'a [rt::v1::Argument]>,
232 // Dynamic arguments for interpolation, to be interleaved with string
233 // pieces. (Every argument is preceded by a string piece.)
234 args: &'a [ArgumentV1<'a>],
237 #[stable(feature = "rust1", since = "1.0.0")]
238 impl<'a> Debug for Arguments<'a> {
239 fn fmt(&self, fmt: &mut Formatter) -> Result {
240 Display::fmt(self, fmt)
244 #[stable(feature = "rust1", since = "1.0.0")]
245 impl<'a> Display for Arguments<'a> {
246 fn fmt(&self, fmt: &mut Formatter) -> Result {
247 write(fmt.buf, *self)
251 /// Format trait for the `:?` format. Useful for debugging, all types
252 /// should implement this.
253 #[stable(feature = "rust1", since = "1.0.0")]
254 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
255 defined in your crate, add `#[derive(Debug)]` or \
256 manually implement it"]
257 #[lang = "debug_trait"]
259 /// Formats the value using the given formatter.
260 #[stable(feature = "rust1", since = "1.0.0")]
261 fn fmt(&self, &mut Formatter) -> Result;
264 /// When a value can be semantically expressed as a String, this trait may be
265 /// used. It corresponds to the default format, `{}`.
266 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
267 formatter; try using `:?` instead if you are using \
269 #[stable(feature = "rust1", since = "1.0.0")]
271 /// Formats the value using the given formatter.
272 #[stable(feature = "rust1", since = "1.0.0")]
273 fn fmt(&self, &mut Formatter) -> Result;
276 /// Format trait for the `o` character
277 #[stable(feature = "rust1", since = "1.0.0")]
279 /// Formats the value using the given formatter.
280 #[stable(feature = "rust1", since = "1.0.0")]
281 fn fmt(&self, &mut Formatter) -> Result;
284 /// Format trait for the `b` character
285 #[stable(feature = "rust1", since = "1.0.0")]
287 /// Formats the value using the given formatter.
288 #[stable(feature = "rust1", since = "1.0.0")]
289 fn fmt(&self, &mut Formatter) -> Result;
292 /// Format trait for the `x` character
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;
300 /// Format trait for the `X` character
301 #[stable(feature = "rust1", since = "1.0.0")]
303 /// Formats the value using the given formatter.
304 #[stable(feature = "rust1", since = "1.0.0")]
305 fn fmt(&self, &mut Formatter) -> Result;
308 /// Format trait for the `p` character
309 #[stable(feature = "rust1", since = "1.0.0")]
311 /// Formats the value using the given formatter.
312 #[stable(feature = "rust1", since = "1.0.0")]
313 fn fmt(&self, &mut Formatter) -> Result;
316 /// Format trait for the `e` character
317 #[stable(feature = "rust1", since = "1.0.0")]
319 /// Formats the value using the given formatter.
320 #[stable(feature = "rust1", since = "1.0.0")]
321 fn fmt(&self, &mut Formatter) -> Result;
324 /// Format trait for the `E` character
325 #[stable(feature = "rust1", since = "1.0.0")]
327 /// Formats the value using the given formatter.
328 #[stable(feature = "rust1", since = "1.0.0")]
329 fn fmt(&self, &mut Formatter) -> Result;
332 /// The `write` function takes an output stream, a precompiled format string,
333 /// and a list of arguments. The arguments will be formatted according to the
334 /// specified format string into the output stream provided.
338 /// * output - the buffer to write output to
339 /// * args - the precompiled arguments generated by `format_args!`
340 #[stable(feature = "rust1", since = "1.0.0")]
341 pub fn write(output: &mut Write, args: Arguments) -> Result {
342 let mut formatter = Formatter {
347 align: Alignment::Unknown,
350 curarg: args.args.iter(),
353 let mut pieces = args.pieces.iter();
357 // We can use default formatting parameters for all arguments.
358 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
359 try!(formatter.buf.write_str(*piece));
360 try!((arg.formatter)(arg.value, &mut formatter));
364 // Every spec has a corresponding argument that is preceded by
366 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
367 try!(formatter.buf.write_str(*piece));
368 try!(formatter.run(arg));
373 // There can be only one trailing string piece left.
374 match pieces.next() {
376 try!(formatter.buf.write_str(*piece));
384 impl<'a> Formatter<'a> {
386 // First up is the collection of functions used to execute a format string
387 // at runtime. This consumes all of the compile-time statics generated by
388 // the format! syntax extension.
389 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
390 // Fill in the format parameters into the formatter
391 self.fill = arg.format.fill;
392 self.align = arg.format.align;
393 self.flags = arg.format.flags;
394 self.width = self.getcount(&arg.format.width);
395 self.precision = self.getcount(&arg.format.precision);
397 // Extract the correct argument
398 let value = match arg.position {
399 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
400 rt::v1::Position::At(i) => self.args[i],
403 // Then actually do some printing
404 (value.formatter)(value.value, self)
407 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
409 rt::v1::Count::Is(n) => Some(n),
410 rt::v1::Count::Implied => None,
411 rt::v1::Count::Param(i) => {
412 self.args[i].as_usize()
414 rt::v1::Count::NextParam => {
415 self.curarg.next().and_then(|arg| arg.as_usize())
420 // Helper methods used for padding and processing formatting arguments that
421 // all formatting traits can use.
423 /// Performs the correct padding for an integer which has already been
424 /// emitted into a str. The str should *not* contain the sign for the
425 /// integer, that will be added by this method.
429 /// * is_positive - whether the original integer was positive or not.
430 /// * prefix - if the '#' character (Alternate) is provided, this
431 /// is the prefix to put in front of the number.
432 /// * buf - the byte array that the number has been formatted into
434 /// This function will correctly account for the flags provided as well as
435 /// the minimum width. It will not take precision into account.
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub fn pad_integral(&mut self,
444 let mut width = buf.len();
448 sign = Some('-'); width += 1;
449 } else if self.flags & (1 << (FlagV1::SignPlus as u32)) != 0 {
450 sign = Some('+'); width += 1;
453 let mut prefixed = false;
454 if self.flags & (1 << (FlagV1::Alternate as u32)) != 0 {
455 prefixed = true; width += prefix.char_len();
458 // Writes the sign if it exists, and then the prefix if it was requested
459 let write_prefix = |f: &mut Formatter| {
460 if let Some(c) = sign {
462 let n = c.encode_utf8(&mut b).unwrap_or(0);
463 let b = unsafe { str::from_utf8_unchecked(&b[..n]) };
464 try!(f.buf.write_str(b));
466 if prefixed { f.buf.write_str(prefix) }
470 // The `width` field is more of a `min-width` parameter at this point.
472 // If there's no minimum length requirements then we can just
475 try!(write_prefix(self)); self.buf.write_str(buf)
477 // Check if we're over the minimum width, if so then we can also
478 // just write the bytes.
479 Some(min) if width >= min => {
480 try!(write_prefix(self)); self.buf.write_str(buf)
482 // The sign and prefix goes before the padding if the fill character
484 Some(min) if self.flags & (1 << (FlagV1::SignAwareZeroPad as u32)) != 0 => {
486 try!(write_prefix(self));
487 self.with_padding(min - width, Alignment::Right, |f| {
491 // Otherwise, the sign and prefix goes after the padding
493 self.with_padding(min - width, Alignment::Right, |f| {
494 try!(write_prefix(f)); f.buf.write_str(buf)
500 /// This function takes a string slice and emits it to the internal buffer
501 /// after applying the relevant formatting flags specified. The flags
502 /// recognized for generic strings are:
504 /// * width - the minimum width of what to emit
505 /// * fill/align - what to emit and where to emit it if the string
506 /// provided needs to be padded
507 /// * precision - the maximum length to emit, the string is truncated if it
508 /// is longer than this length
510 /// Notably this function ignored the `flag` parameters
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn pad(&mut self, s: &str) -> Result {
513 // Make sure there's a fast path up front
514 if self.width.is_none() && self.precision.is_none() {
515 return self.buf.write_str(s);
517 // The `precision` field can be interpreted as a `max-width` for the
518 // string being formatted
519 match self.precision {
521 // If there's a maximum width and our string is longer than
522 // that, then we must always have truncation. This is the only
523 // case where the maximum length will matter.
524 let char_len = s.char_len();
526 let nchars = ::cmp::min(max, char_len);
527 return self.buf.write_str(s.slice_chars(0, nchars));
532 // The `width` field is more of a `min-width` parameter at this point.
534 // If we're under the maximum length, and there's no minimum length
535 // requirements, then we can just emit the string
536 None => self.buf.write_str(s),
537 // If we're under the maximum width, check if we're over the minimum
538 // width, if so it's as easy as just emitting the string.
539 Some(width) if s.char_len() >= width => {
540 self.buf.write_str(s)
542 // If we're under both the maximum and the minimum width, then fill
543 // up the minimum width with the specified string + some alignment.
545 self.with_padding(width - s.char_len(), Alignment::Left, |me| {
552 /// Runs a callback, emitting the correct padding either before or
553 /// afterwards depending on whether right or left alignment is requested.
554 fn with_padding<F>(&mut self, padding: usize, default: Alignment,
556 where F: FnOnce(&mut Formatter) -> Result,
559 let align = match self.align {
560 Alignment::Unknown => default,
564 let (pre_pad, post_pad) = match align {
565 Alignment::Left => (0, padding),
566 Alignment::Right | Alignment::Unknown => (padding, 0),
567 Alignment::Center => (padding / 2, (padding + 1) / 2),
570 let mut fill = [0; 4];
571 let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
572 let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) };
574 for _ in 0..pre_pad {
575 try!(self.buf.write_str(fill));
580 for _ in 0..post_pad {
581 try!(self.buf.write_str(fill));
587 /// Writes some data to the underlying buffer contained within this
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn write_str(&mut self, data: &str) -> Result {
591 self.buf.write_str(data)
594 /// Writes some formatted information into this instance
595 #[stable(feature = "rust1", since = "1.0.0")]
596 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
600 /// Flags for formatting (packed version of rt::Flag)
601 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn flags(&self) -> u32 { self.flags }
604 /// Character used as 'fill' whenever there is alignment
605 #[unstable(feature = "core", reason = "method was just created")]
606 pub fn fill(&self) -> char { self.fill }
608 /// Flag indicating what form of alignment was requested
609 #[unstable(feature = "core", reason = "method was just created")]
610 pub fn align(&self) -> Alignment { self.align }
612 /// Optionally specified integer width that the output should be
613 #[unstable(feature = "core", reason = "method was just created")]
614 pub fn width(&self) -> Option<usize> { self.width }
616 /// Optionally specified precision for numeric types
617 #[unstable(feature = "core", reason = "method was just created")]
618 pub fn precision(&self) -> Option<usize> { self.precision }
620 /// Creates a `DebugStruct` builder designed to assist with creation of
621 /// `fmt::Debug` implementations for structs.
626 /// # #![feature(debug_builders, core)]
634 /// impl fmt::Debug for Foo {
635 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
636 /// fmt.debug_struct("Foo")
637 /// .field("bar", &self.bar)
638 /// .field("baz", &self.baz)
643 /// // prints "Foo { bar: 10, baz: "Hello World" }"
644 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
646 #[unstable(feature = "debug_builders", reason = "method was just created")]
648 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
649 builders::debug_struct_new(self, name)
652 /// Creates a `DebugTuple` builder designed to assist with creation of
653 /// `fmt::Debug` implementations for tuple structs.
658 /// # #![feature(debug_builders, core)]
661 /// struct Foo(i32, String);
663 /// impl fmt::Debug for Foo {
664 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
665 /// fmt.debug_tuple("Foo")
672 /// // prints "Foo(10, "Hello World")"
673 /// println!("{:?}", Foo(10, "Hello World".to_string()));
675 #[unstable(feature = "debug_builders", reason = "method was just created")]
677 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
678 builders::debug_tuple_new(self, name)
681 /// Creates a `DebugList` builder designed to assist with creation of
682 /// `fmt::Debug` implementations for list-like structures.
687 /// # #![feature(debug_builders, core)]
690 /// struct Foo(Vec<i32>);
692 /// impl fmt::Debug for Foo {
693 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
694 /// self.0.iter().fold(fmt.debug_list(), |b, e| b.entry(e)).finish()
698 /// // prints "[10, 11]"
699 /// println!("{:?}", Foo(vec![10, 11]));
701 #[unstable(feature = "debug_builders", reason = "method was just created")]
703 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
704 builders::debug_list_new(self)
707 /// Creates a `DebugSet` builder designed to assist with creation of
708 /// `fmt::Debug` implementations for set-like structures.
713 /// # #![feature(debug_builders, core)]
716 /// struct Foo(Vec<i32>);
718 /// impl fmt::Debug for Foo {
719 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
720 /// self.0.iter().fold(fmt.debug_set(), |b, e| b.entry(e)).finish()
724 /// // prints "{10, 11}"
725 /// println!("{:?}", Foo(vec![10, 11]));
727 #[unstable(feature = "debug_builders", reason = "method was just created")]
729 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
730 builders::debug_set_new(self)
733 /// Creates a `DebugMap` builder designed to assist with creation of
734 /// `fmt::Debug` implementations for map-like structures.
739 /// # #![feature(debug_builders, core)]
742 /// struct Foo(Vec<(String, i32)>);
744 /// impl fmt::Debug for Foo {
745 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
746 /// self.0.iter().fold(fmt.debug_map(), |b, &(ref k, ref v)| b.entry(k, v)).finish()
750 /// // prints "{"A": 10, "B": 11}"
751 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
753 #[unstable(feature = "debug_builders", reason = "method was just created")]
755 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
756 builders::debug_map_new(self)
760 #[stable(feature = "rust1", since = "1.0.0")]
761 impl Display for Error {
762 fn fmt(&self, f: &mut Formatter) -> Result {
763 Display::fmt("an error occurred when formatting an argument", f)
767 // Implementations of the core formatting traits
769 macro_rules! fmt_refs {
770 ($($tr:ident),*) => {
772 #[stable(feature = "rust1", since = "1.0.0")]
773 impl<'a, T: ?Sized + $tr> $tr for &'a T {
774 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
776 #[stable(feature = "rust1", since = "1.0.0")]
777 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
778 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
784 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
786 #[stable(feature = "rust1", since = "1.0.0")]
787 impl Debug for bool {
788 fn fmt(&self, f: &mut Formatter) -> Result {
789 Display::fmt(self, f)
793 #[stable(feature = "rust1", since = "1.0.0")]
794 impl Display for bool {
795 fn fmt(&self, f: &mut Formatter) -> Result {
796 Display::fmt(if *self { "true" } else { "false" }, f)
800 #[stable(feature = "rust1", since = "1.0.0")]
802 fn fmt(&self, f: &mut Formatter) -> Result {
803 try!(write!(f, "\""));
804 for c in self.chars().flat_map(|c| c.escape_default()) {
805 try!(write!(f, "{}", c));
811 #[stable(feature = "rust1", since = "1.0.0")]
812 impl Display for str {
813 fn fmt(&self, f: &mut Formatter) -> Result {
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl Debug for char {
820 fn fmt(&self, f: &mut Formatter) -> Result {
822 try!(write!(f, "'"));
823 for c in self.escape_default() {
824 try!(write!(f, "{}", c));
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl Display for char {
832 fn fmt(&self, f: &mut Formatter) -> Result {
833 let mut utf8 = [0; 4];
834 let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
835 let s: &str = unsafe { mem::transmute(&utf8[..amt]) };
840 #[stable(feature = "rust1", since = "1.0.0")]
841 impl<T> Pointer for *const T {
842 fn fmt(&self, f: &mut Formatter) -> Result {
843 f.flags |= 1 << (FlagV1::Alternate as u32);
844 let ret = LowerHex::fmt(&(*self as usize), f);
845 f.flags &= !(1 << (FlagV1::Alternate as u32));
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<T> Pointer for *mut T {
852 fn fmt(&self, f: &mut Formatter) -> Result {
853 // FIXME(#23542) Replace with type ascription.
854 #![allow(trivial_casts)]
855 Pointer::fmt(&(*self as *const T), f)
859 #[stable(feature = "rust1", since = "1.0.0")]
860 impl<'a, T> Pointer for &'a T {
861 fn fmt(&self, f: &mut Formatter) -> Result {
862 // FIXME(#23542) Replace with type ascription.
863 #![allow(trivial_casts)]
864 Pointer::fmt(&(*self as *const T), f)
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl<'a, T> Pointer for &'a mut T {
870 fn fmt(&self, f: &mut Formatter) -> Result {
871 // FIXME(#23542) Replace with type ascription.
872 #![allow(trivial_casts)]
873 Pointer::fmt(&(&**self as *const T), f)
877 macro_rules! floating { ($ty:ident) => {
879 #[stable(feature = "rust1", since = "1.0.0")]
881 fn fmt(&self, fmt: &mut Formatter) -> Result {
882 Display::fmt(self, fmt)
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl Display for $ty {
888 fn fmt(&self, fmt: &mut Formatter) -> Result {
891 let digits = match fmt.precision {
892 Some(i) => float::DigExact(i),
893 None => float::DigMax(6),
895 float::float_to_str_bytes_common(self.abs(),
903 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl LowerExp for $ty {
910 fn fmt(&self, fmt: &mut Formatter) -> Result {
913 let digits = match fmt.precision {
914 Some(i) => float::DigExact(i),
915 None => float::DigMax(6),
917 float::float_to_str_bytes_common(self.abs(),
925 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
930 #[stable(feature = "rust1", since = "1.0.0")]
931 impl UpperExp for $ty {
932 fn fmt(&self, fmt: &mut Formatter) -> Result {
935 let digits = match fmt.precision {
936 Some(i) => float::DigExact(i),
937 None => float::DigMax(6),
939 float::float_to_str_bytes_common(self.abs(),
947 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
955 // Implementation of Display/Debug for various core types
957 #[stable(feature = "rust1", since = "1.0.0")]
958 impl<T> Debug for *const T {
959 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
961 #[stable(feature = "rust1", since = "1.0.0")]
962 impl<T> Debug for *mut T {
963 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
967 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
972 ( $($name:ident,)+ ) => (
973 #[stable(feature = "rust1", since = "1.0.0")]
974 impl<$($name:Debug),*> Debug for ($($name,)*) {
975 #[allow(non_snake_case, unused_assignments)]
976 fn fmt(&self, f: &mut Formatter) -> Result {
977 try!(write!(f, "("));
978 let ($(ref $name,)*) = *self;
982 try!(write!(f, ", "));
984 try!(write!(f, "{:?}", *$name));
988 try!(write!(f, ","));
997 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 impl<T: Debug> Debug for [T] {
1001 fn fmt(&self, f: &mut Formatter) -> Result {
1002 self.iter().fold(f.debug_list(), |b, e| b.entry(e)).finish()
1006 #[stable(feature = "rust1", since = "1.0.0")]
1008 fn fmt(&self, f: &mut Formatter) -> Result {
1012 impl<T> Debug for PhantomData<T> {
1013 fn fmt(&self, f: &mut Formatter) -> Result {
1014 f.pad("PhantomData")
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 impl<T: Copy + Debug> Debug for Cell<T> {
1020 fn fmt(&self, f: &mut Formatter) -> Result {
1021 write!(f, "Cell {{ value: {:?} }}", self.get())
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl<T: Debug> Debug for RefCell<T> {
1027 fn fmt(&self, f: &mut Formatter) -> Result {
1028 match self.borrow_state() {
1029 BorrowState::Unused | BorrowState::Reading => {
1030 write!(f, "RefCell {{ value: {:?} }}", self.borrow())
1032 BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 impl<'b, T: Debug> Debug for Ref<'b, T> {
1039 fn fmt(&self, f: &mut Formatter) -> Result {
1040 Debug::fmt(&**self, f)
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 impl<'b, T: Debug> Debug for RefMut<'b, T> {
1046 fn fmt(&self, f: &mut Formatter) -> Result {
1047 Debug::fmt(&*(self.deref()), f)
1051 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1052 // it's a lot easier than creating all of the rt::Piece structures here.