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}
;
19 use marker
::{Copy, PhantomData, 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
;
35 pub use self::builders
::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap}
;
41 #[stable(feature = "rust1", since = "1.0.0")]
47 #[stable(feature = "rust1", since = "1.0.0")]
48 /// The type returned by formatter methods.
49 pub type Result
= result
::Result
<(), Error
>;
51 /// The error type which is returned from formatting a message into a stream.
53 /// This type does not support transmission of an error other than that an error
54 /// occurred. Any extra information must be arranged to be transmitted through
56 #[stable(feature = "rust1", since = "1.0.0")]
57 #[derive(Copy, Clone, Debug)]
60 /// A collection of methods that are required to format a message into a stream.
62 /// This trait is the type which this modules requires when formatting
63 /// information. This is similar to the standard library's `io::Write` trait,
64 /// but it is only intended for use in libcore.
66 /// This trait should generally not be implemented by consumers of the standard
67 /// library. The `write!` macro accepts an instance of `io::Write`, and the
68 /// `io::Write` trait is favored over implementing this trait.
69 #[stable(feature = "rust1", since = "1.0.0")]
71 /// Writes a slice of bytes into this writer, returning whether the write
74 /// This method can only succeed if the entire byte slice was successfully
75 /// written, and this method will not return until all data has been
76 /// written or an error occurs.
80 /// This function will return an instance of `FormatError` on error.
81 #[stable(feature = "rust1", since = "1.0.0")]
82 fn write_str(&mut self, s
: &str) -> Result
;
84 /// Glue for usage of the `write!` macro with implementers of this trait.
86 /// This method should generally not be invoked manually, but rather through
87 /// the `write!` macro itself.
88 #[stable(feature = "rust1", since = "1.0.0")]
89 fn write_fmt(&mut self, args
: Arguments
) -> Result
{
90 // This Adapter is needed to allow `self` (of type `&mut
91 // Self`) to be cast to a Write (below) without
92 // requiring a `Sized` bound.
93 struct Adapter
<'a
,T
: ?Sized
+'a
>(&'a
mut T
);
95 impl<'a
, T
: ?Sized
> Write
for Adapter
<'a
, T
>
98 fn write_str(&mut self, s
: &str) -> Result
{
102 fn write_fmt(&mut self, args
: Arguments
) -> Result
{
103 self.0.write_fmt(args
)
107 write(&mut Adapter(self), args
)
111 /// A struct to represent both where to emit formatting strings to and how they
112 /// should be formatted. A mutable version of this is passed to all formatting
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub struct Formatter
<'a
> {
118 align
: rt
::v1
::Alignment
,
119 width
: Option
<usize>,
120 precision
: Option
<usize>,
122 buf
: &'a
mut (Write
+'a
),
123 curarg
: slice
::Iter
<'a
, ArgumentV1
<'a
>>,
124 args
: &'a
[ArgumentV1
<'a
>],
127 // NB. Argument is essentially an optimized partially applied formatting function,
128 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
132 /// This struct represents the generic "argument" which is taken by the Xprintf
133 /// family of functions. It contains a function to format the given value. At
134 /// compile time it is ensured that the function and the value have the correct
135 /// types, and then this struct is used to canonicalize arguments to one type.
137 #[stable(feature = "rust1", since = "1.0.0")]
139 pub struct ArgumentV1
<'a
> {
141 formatter
: fn(&Void
, &mut Formatter
) -> Result
,
144 impl<'a
> Clone
for ArgumentV1
<'a
> {
145 fn clone(&self) -> ArgumentV1
<'a
> {
150 impl<'a
> ArgumentV1
<'a
> {
152 fn show_usize(x
: &usize, f
: &mut Formatter
) -> Result
{
157 #[stable(feature = "rust1", since = "1.0.0")]
158 pub fn new
<'b
, T
>(x
: &'b T
,
159 f
: fn(&T
, &mut Formatter
) -> Result
) -> ArgumentV1
<'b
> {
162 formatter
: mem
::transmute(f
),
163 value
: mem
::transmute(x
)
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub fn from_usize(x
: &usize) -> ArgumentV1
{
171 ArgumentV1
::new(x
, ArgumentV1
::show_usize
)
174 fn as_usize(&self) -> Option
<usize> {
175 if self.formatter
as usize == ArgumentV1
::show_usize
as usize {
176 Some(unsafe { *(self.value as *const _ as *const usize) }
)
183 // flags available in the v1 format of format_args
184 #[derive(Copy, Clone)]
185 #[allow(dead_code)] // SignMinus isn't currently used
186 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
188 impl<'a
> Arguments
<'a
> {
189 /// When using the format_args!() macro, this function is used to generate the
190 /// Arguments structure.
191 #[doc(hidden)] #[inline]
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub fn new_v1(pieces
: &'a
[&'a
str],
194 args
: &'a
[ArgumentV1
<'a
>]) -> Arguments
<'a
> {
202 /// This function is used to specify nonstandard formatting parameters.
203 /// The `pieces` array must be at least as long as `fmt` to construct
204 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
205 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
206 /// created with `argumentusize`. However, failing to do so doesn't cause
207 /// unsafety, but will ignore invalid .
208 #[doc(hidden)] #[inline]
209 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn new_v1_formatted(pieces
: &'a
[&'a
str],
211 args
: &'a
[ArgumentV1
<'a
>],
212 fmt
: &'a
[rt
::v1
::Argument
]) -> Arguments
<'a
> {
221 /// This structure represents a safely precompiled version of a format string
222 /// and its arguments. This cannot be generated at runtime because it cannot
223 /// safely be done so, so no constructors are given and the fields are private
224 /// to prevent modification.
226 /// The `format_args!` macro will safely create an instance of this structure
227 /// and pass it to a function or closure, passed as the first argument. The
228 /// macro validates the format string at compile-time so usage of the `write`
229 /// and `format` functions can be safely performed.
230 #[stable(feature = "rust1", since = "1.0.0")]
231 #[derive(Copy, Clone)]
232 pub struct Arguments
<'a
> {
233 // Format string pieces to print.
234 pieces
: &'a
[&'a
str],
236 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
237 fmt
: Option
<&'a
[rt
::v1
::Argument
]>,
239 // Dynamic arguments for interpolation, to be interleaved with string
240 // pieces. (Every argument is preceded by a string piece.)
241 args
: &'a
[ArgumentV1
<'a
>],
244 #[stable(feature = "rust1", since = "1.0.0")]
245 impl<'a
> Debug
for Arguments
<'a
> {
246 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
247 Display
::fmt(self, fmt
)
251 #[stable(feature = "rust1", since = "1.0.0")]
252 impl<'a
> Display
for Arguments
<'a
> {
253 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
254 write(fmt
.buf
, *self)
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
;
271 /// When a value can be semantically expressed as a String, this trait may be
272 /// used. It corresponds to the default format, `{}`.
273 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
274 formatter; try using `:?` instead if you are using \
276 #[stable(feature = "rust1", since = "1.0.0")]
278 /// Formats the value using the given formatter.
279 #[stable(feature = "rust1", since = "1.0.0")]
280 fn fmt(&self, &mut Formatter
) -> Result
;
283 /// Format trait for the `o` character
284 #[stable(feature = "rust1", since = "1.0.0")]
286 /// Formats the value using the given formatter.
287 #[stable(feature = "rust1", since = "1.0.0")]
288 fn fmt(&self, &mut Formatter
) -> Result
;
291 /// Format trait for the `b` character
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
;
299 /// Format trait for the `x` character
300 #[stable(feature = "rust1", since = "1.0.0")]
302 /// Formats the value using the given formatter.
303 #[stable(feature = "rust1", since = "1.0.0")]
304 fn fmt(&self, &mut Formatter
) -> Result
;
307 /// Format trait for the `X` character
308 #[stable(feature = "rust1", since = "1.0.0")]
310 /// Formats the value using the given formatter.
311 #[stable(feature = "rust1", since = "1.0.0")]
312 fn fmt(&self, &mut Formatter
) -> Result
;
315 /// Format trait for the `p` character
316 #[stable(feature = "rust1", since = "1.0.0")]
318 /// Formats the value using the given formatter.
319 #[stable(feature = "rust1", since = "1.0.0")]
320 fn fmt(&self, &mut Formatter
) -> Result
;
323 /// Format trait for the `e` character
324 #[stable(feature = "rust1", since = "1.0.0")]
326 /// Formats the value using the given formatter.
327 #[stable(feature = "rust1", since = "1.0.0")]
328 fn fmt(&self, &mut Formatter
) -> Result
;
331 /// Format trait for the `E` character
332 #[stable(feature = "rust1", since = "1.0.0")]
334 /// Formats the value using the given formatter.
335 #[stable(feature = "rust1", since = "1.0.0")]
336 fn fmt(&self, &mut Formatter
) -> Result
;
339 /// The `write` function takes an output stream, a precompiled format string,
340 /// and a list of arguments. The arguments will be formatted according to the
341 /// specified format string into the output stream provided.
345 /// * output - the buffer to write output to
346 /// * args - the precompiled arguments generated by `format_args!`
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub fn write(output
: &mut Write
, args
: Arguments
) -> Result
{
349 let mut formatter
= Formatter
{
354 align
: Alignment
::Unknown
,
357 curarg
: args
.args
.iter(),
360 let mut pieces
= args
.pieces
.iter();
364 // We can use default formatting parameters for all arguments.
365 for (arg
, piece
) in args
.args
.iter().zip(pieces
.by_ref()) {
366 try
!(formatter
.buf
.write_str(*piece
));
367 try
!((arg
.formatter
)(arg
.value
, &mut formatter
));
371 // Every spec has a corresponding argument that is preceded by
373 for (arg
, piece
) in fmt
.iter().zip(pieces
.by_ref()) {
374 try
!(formatter
.buf
.write_str(*piece
));
375 try
!(formatter
.run(arg
));
380 // There can be only one trailing string piece left.
381 match pieces
.next() {
383 try
!(formatter
.buf
.write_str(*piece
));
391 impl<'a
> Formatter
<'a
> {
393 // First up is the collection of functions used to execute a format string
394 // at runtime. This consumes all of the compile-time statics generated by
395 // the format! syntax extension.
396 fn run(&mut self, arg
: &rt
::v1
::Argument
) -> Result
{
397 // Fill in the format parameters into the formatter
398 self.fill
= arg
.format
.fill
;
399 self.align
= arg
.format
.align
;
400 self.flags
= arg
.format
.flags
;
401 self.width
= self.getcount(&arg
.format
.width
);
402 self.precision
= self.getcount(&arg
.format
.precision
);
404 // Extract the correct argument
405 let value
= match arg
.position
{
406 rt
::v1
::Position
::Next
=> { *self.curarg.next().unwrap() }
407 rt
::v1
::Position
::At(i
) => self.args
[i
],
410 // Then actually do some printing
411 (value
.formatter
)(value
.value
, self)
414 fn getcount(&mut self, cnt
: &rt
::v1
::Count
) -> Option
<usize> {
416 rt
::v1
::Count
::Is(n
) => Some(n
),
417 rt
::v1
::Count
::Implied
=> None
,
418 rt
::v1
::Count
::Param(i
) => {
419 self.args
[i
].as_usize()
421 rt
::v1
::Count
::NextParam
=> {
422 self.curarg
.next().and_then(|arg
| arg
.as_usize())
427 // Helper methods used for padding and processing formatting arguments that
428 // all formatting traits can use.
430 /// Performs the correct padding for an integer which has already been
431 /// emitted into a str. The str should *not* contain the sign for the
432 /// integer, that will be added by this method.
436 /// * is_positive - whether the original integer was positive or not.
437 /// * prefix - if the '#' character (Alternate) is provided, this
438 /// is the prefix to put in front of the number.
439 /// * buf - the byte array that the number has been formatted into
441 /// This function will correctly account for the flags provided as well as
442 /// the minimum width. It will not take precision into account.
443 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn pad_integral(&mut self,
451 let mut width
= buf
.len();
455 sign
= Some('
-'
); width
+= 1;
456 } else if self.flags
& (1 << (FlagV1
::SignPlus
as u32)) != 0 {
457 sign
= Some('
+'
); width
+= 1;
460 let mut prefixed
= false;
461 if self.flags
& (1 << (FlagV1
::Alternate
as u32)) != 0 {
462 prefixed
= true; width
+= prefix
.char_len();
465 // Writes the sign if it exists, and then the prefix if it was requested
466 let write_prefix
= |f
: &mut Formatter
| {
467 if let Some(c
) = sign
{
469 let n
= c
.encode_utf8(&mut b
).unwrap_or(0);
470 let b
= unsafe { str::from_utf8_unchecked(&b[..n]) }
;
471 try
!(f
.buf
.write_str(b
));
473 if prefixed { f.buf.write_str(prefix) }
477 // The `width` field is more of a `min-width` parameter at this point.
479 // If there's no minimum length requirements then we can just
482 try
!(write_prefix(self)); self.buf
.write_str(buf
)
484 // Check if we're over the minimum width, if so then we can also
485 // just write the bytes.
486 Some(min
) if width
>= min
=> {
487 try
!(write_prefix(self)); self.buf
.write_str(buf
)
489 // The sign and prefix goes before the padding if the fill character
491 Some(min
) if self.flags
& (1 << (FlagV1
::SignAwareZeroPad
as u32)) != 0 => {
493 try
!(write_prefix(self));
494 self.with_padding(min
- width
, Alignment
::Right
, |f
| {
498 // Otherwise, the sign and prefix goes after the padding
500 self.with_padding(min
- width
, Alignment
::Right
, |f
| {
501 try
!(write_prefix(f
)); f
.buf
.write_str(buf
)
507 /// This function takes a string slice and emits it to the internal buffer
508 /// after applying the relevant formatting flags specified. The flags
509 /// recognized for generic strings are:
511 /// * width - the minimum width of what to emit
512 /// * fill/align - what to emit and where to emit it if the string
513 /// provided needs to be padded
514 /// * precision - the maximum length to emit, the string is truncated if it
515 /// is longer than this length
517 /// Notably this function ignored the `flag` parameters
518 #[stable(feature = "rust1", since = "1.0.0")]
519 pub fn pad(&mut self, s
: &str) -> Result
{
520 // Make sure there's a fast path up front
521 if self.width
.is_none() && self.precision
.is_none() {
522 return self.buf
.write_str(s
);
524 // The `precision` field can be interpreted as a `max-width` for the
525 // string being formatted
526 match self.precision
{
528 // If there's a maximum width and our string is longer than
529 // that, then we must always have truncation. This is the only
530 // case where the maximum length will matter.
531 let char_len
= s
.char_len();
533 let nchars
= ::cmp
::min(max
, char_len
);
534 return self.buf
.write_str(s
.slice_chars(0, nchars
));
539 // The `width` field is more of a `min-width` parameter at this point.
541 // If we're under the maximum length, and there's no minimum length
542 // requirements, then we can just emit the string
543 None
=> self.buf
.write_str(s
),
544 // If we're under the maximum width, check if we're over the minimum
545 // width, if so it's as easy as just emitting the string.
546 Some(width
) if s
.char_len() >= width
=> {
547 self.buf
.write_str(s
)
549 // If we're under both the maximum and the minimum width, then fill
550 // up the minimum width with the specified string + some alignment.
552 self.with_padding(width
- s
.char_len(), Alignment
::Left
, |me
| {
559 /// Runs a callback, emitting the correct padding either before or
560 /// afterwards depending on whether right or left alignment is requested.
561 fn with_padding
<F
>(&mut self, padding
: usize, default: Alignment
,
563 where F
: FnOnce(&mut Formatter
) -> Result
,
566 let align
= match self.align
{
567 Alignment
::Unknown
=> default,
571 let (pre_pad
, post_pad
) = match align
{
572 Alignment
::Left
=> (0, padding
),
573 Alignment
::Right
| Alignment
::Unknown
=> (padding
, 0),
574 Alignment
::Center
=> (padding
/ 2, (padding
+ 1) / 2),
577 let mut fill
= [0; 4];
578 let len
= self.fill
.encode_utf8(&mut fill
).unwrap_or(0);
579 let fill
= unsafe { str::from_utf8_unchecked(&fill[..len]) }
;
581 for _
in 0..pre_pad
{
582 try
!(self.buf
.write_str(fill
));
587 for _
in 0..post_pad
{
588 try
!(self.buf
.write_str(fill
));
594 /// Writes some data to the underlying buffer contained within this
596 #[stable(feature = "rust1", since = "1.0.0")]
597 pub fn write_str(&mut self, data
: &str) -> Result
{
598 self.buf
.write_str(data
)
601 /// Writes some formatted information into this instance
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn write_fmt(&mut self, fmt
: Arguments
) -> Result
{
607 /// Flags for formatting (packed version of rt::Flag)
608 #[stable(feature = "rust1", since = "1.0.0")]
609 pub fn flags(&self) -> u32 { self.flags }
611 /// Character used as 'fill' whenever there is alignment
612 #[unstable(feature = "core", reason = "method was just created")]
613 pub fn fill(&self) -> char { self.fill }
615 /// Flag indicating what form of alignment was requested
616 #[unstable(feature = "core", reason = "method was just created")]
617 pub fn align(&self) -> Alignment { self.align }
619 /// Optionally specified integer width that the output should be
620 #[unstable(feature = "core", reason = "method was just created")]
621 pub fn width(&self) -> Option
<usize> { self.width }
623 /// Optionally specified precision for numeric types
624 #[unstable(feature = "core", reason = "method was just created")]
625 pub fn precision(&self) -> Option
<usize> { self.precision }
627 /// Creates a `DebugStruct` builder designed to assist with creation of
628 /// `fmt::Debug` implementations for structs.
633 /// # #![feature(debug_builders, core)]
641 /// impl fmt::Debug for Foo {
642 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
643 /// fmt.debug_struct("Foo")
644 /// .field("bar", &self.bar)
645 /// .field("baz", &self.baz)
650 /// // prints "Foo { bar: 10, baz: "Hello World" }"
651 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
653 #[unstable(feature = "debug_builders", reason = "method was just created")]
655 pub fn debug_struct
<'b
>(&'b
mut self, name
: &str) -> DebugStruct
<'b
, 'a
> {
656 builders
::debug_struct_new(self, name
)
659 /// Creates a `DebugTuple` builder designed to assist with creation of
660 /// `fmt::Debug` implementations for tuple structs.
665 /// # #![feature(debug_builders, core)]
668 /// struct Foo(i32, String);
670 /// impl fmt::Debug for Foo {
671 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
672 /// fmt.debug_tuple("Foo")
679 /// // prints "Foo(10, "Hello World")"
680 /// println!("{:?}", Foo(10, "Hello World".to_string()));
682 #[unstable(feature = "debug_builders", reason = "method was just created")]
684 pub fn debug_tuple
<'b
>(&'b
mut self, name
: &str) -> DebugTuple
<'b
, 'a
> {
685 builders
::debug_tuple_new(self, name
)
688 /// Creates a `DebugList` builder designed to assist with creation of
689 /// `fmt::Debug` implementations for list-like structures.
694 /// # #![feature(debug_builders, core)]
697 /// struct Foo(Vec<i32>);
699 /// impl fmt::Debug for Foo {
700 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
701 /// self.0.iter().fold(fmt.debug_list(), |b, e| b.entry(e)).finish()
705 /// // prints "[10, 11]"
706 /// println!("{:?}", Foo(vec![10, 11]));
708 #[unstable(feature = "debug_builders", reason = "method was just created")]
710 pub fn debug_list
<'b
>(&'b
mut self) -> DebugList
<'b
, 'a
> {
711 builders
::debug_list_new(self)
714 /// Creates a `DebugSet` builder designed to assist with creation of
715 /// `fmt::Debug` implementations for set-like structures.
720 /// # #![feature(debug_builders, core)]
723 /// struct Foo(Vec<i32>);
725 /// impl fmt::Debug for Foo {
726 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
727 /// self.0.iter().fold(fmt.debug_set(), |b, e| b.entry(e)).finish()
731 /// // prints "{10, 11}"
732 /// println!("{:?}", Foo(vec![10, 11]));
734 #[unstable(feature = "debug_builders", reason = "method was just created")]
736 pub fn debug_set
<'b
>(&'b
mut self) -> DebugSet
<'b
, 'a
> {
737 builders
::debug_set_new(self)
740 /// Creates a `DebugMap` builder designed to assist with creation of
741 /// `fmt::Debug` implementations for map-like structures.
746 /// # #![feature(debug_builders, core)]
749 /// struct Foo(Vec<(String, i32)>);
751 /// impl fmt::Debug for Foo {
752 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
753 /// self.0.iter().fold(fmt.debug_map(), |b, &(ref k, ref v)| b.entry(k, v)).finish()
757 /// // prints "{"A": 10, "B": 11}"
758 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
760 #[unstable(feature = "debug_builders", reason = "method was just created")]
762 pub fn debug_map
<'b
>(&'b
mut self) -> DebugMap
<'b
, 'a
> {
763 builders
::debug_map_new(self)
767 #[stable(feature = "rust1", since = "1.0.0")]
768 impl Display
for Error
{
769 fn fmt(&self, f
: &mut Formatter
) -> Result
{
770 Display
::fmt("an error occurred when formatting an argument", f
)
774 // Implementations of the core formatting traits
776 macro_rules
! fmt_refs
{
777 ($
($tr
:ident
),*) => {
779 #[stable(feature = "rust1", since = "1.0.0")]
780 impl<'a
, T
: ?Sized
+ $tr
> $tr
for &'a T
{
781 fn fmt(&self, f
: &mut Formatter
) -> Result { $tr::fmt(&**self, f) }
783 #[stable(feature = "rust1", since = "1.0.0")]
784 impl<'a
, T
: ?Sized
+ $tr
> $tr
for &'a
mut T
{
785 fn fmt(&self, f
: &mut Formatter
) -> Result { $tr::fmt(&**self, f) }
791 fmt_refs
! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
793 #[stable(feature = "rust1", since = "1.0.0")]
794 impl Debug
for bool
{
795 fn fmt(&self, f
: &mut Formatter
) -> Result
{
796 Display
::fmt(self, f
)
800 #[stable(feature = "rust1", since = "1.0.0")]
801 impl Display
for bool
{
802 fn fmt(&self, f
: &mut Formatter
) -> Result
{
803 Display
::fmt(if *self { "true" }
else { "false" }
, f
)
807 #[stable(feature = "rust1", since = "1.0.0")]
809 fn fmt(&self, f
: &mut Formatter
) -> Result
{
810 try
!(write
!(f
, "\""));
811 for c
in self.chars().flat_map(|c
| c
.escape_default()) {
812 try
!(write
!(f
, "{}", c
));
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl Display
for str {
820 fn fmt(&self, f
: &mut Formatter
) -> Result
{
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl Debug
for char {
827 fn fmt(&self, f
: &mut Formatter
) -> Result
{
829 try
!(write
!(f
, "'"));
830 for c
in self.escape_default() {
831 try
!(write
!(f
, "{}", c
));
837 #[stable(feature = "rust1", since = "1.0.0")]
838 impl Display
for char {
839 fn fmt(&self, f
: &mut Formatter
) -> Result
{
840 let mut utf8
= [0; 4];
841 let amt
= self.encode_utf8(&mut utf8
).unwrap_or(0);
842 let s
: &str = unsafe { mem::transmute(&utf8[..amt]) }
;
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl<T
> Pointer
for *const T
{
849 fn fmt(&self, f
: &mut Formatter
) -> Result
{
850 f
.flags
|= 1 << (FlagV1
::Alternate
as u32);
851 let ret
= LowerHex
::fmt(&(*self as usize), f
);
852 f
.flags
&= !(1 << (FlagV1
::Alternate
as u32));
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<T
> Pointer
for *mut T
{
859 fn fmt(&self, f
: &mut Formatter
) -> Result
{
860 // FIXME(#23542) Replace with type ascription.
861 #![allow(trivial_casts)]
862 Pointer
::fmt(&(*self as *const T
), f
)
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<'a
, T
> Pointer
for &'a T
{
868 fn fmt(&self, f
: &mut Formatter
) -> Result
{
869 // FIXME(#23542) Replace with type ascription.
870 #![allow(trivial_casts)]
871 Pointer
::fmt(&(*self as *const T
), f
)
875 #[stable(feature = "rust1", since = "1.0.0")]
876 impl<'a
, T
> Pointer
for &'a
mut T
{
877 fn fmt(&self, f
: &mut Formatter
) -> Result
{
878 // FIXME(#23542) Replace with type ascription.
879 #![allow(trivial_casts)]
880 Pointer
::fmt(&(&**self as *const T
), f
)
884 macro_rules
! floating
{ ($ty
:ident
) => {
886 #[stable(feature = "rust1", since = "1.0.0")]
888 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
889 Display
::fmt(self, fmt
)
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl Display
for $ty
{
895 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
898 let digits
= match fmt
.precision
{
899 Some(i
) => float
::DigExact(i
),
900 None
=> float
::DigMax(6),
902 float
::float_to_str_bytes_common(self.abs(),
910 fmt
.pad_integral(self.is_nan() || *self >= 0.0, "", bytes
)
915 #[stable(feature = "rust1", since = "1.0.0")]
916 impl LowerExp
for $ty
{
917 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
920 let digits
= match fmt
.precision
{
921 Some(i
) => float
::DigExact(i
),
922 None
=> float
::DigMax(6),
924 float
::float_to_str_bytes_common(self.abs(),
932 fmt
.pad_integral(self.is_nan() || *self >= 0.0, "", bytes
)
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl UpperExp
for $ty
{
939 fn fmt(&self, fmt
: &mut Formatter
) -> Result
{
942 let digits
= match fmt
.precision
{
943 Some(i
) => float
::DigExact(i
),
944 None
=> float
::DigMax(6),
946 float
::float_to_str_bytes_common(self.abs(),
954 fmt
.pad_integral(self.is_nan() || *self >= 0.0, "", bytes
)
962 // Implementation of Display/Debug for various core types
964 #[stable(feature = "rust1", since = "1.0.0")]
965 impl<T
> Debug
for *const T
{
966 fn fmt(&self, f
: &mut Formatter
) -> Result { Pointer::fmt(self, f) }
968 #[stable(feature = "rust1", since = "1.0.0")]
969 impl<T
> Debug
for *mut T
{
970 fn fmt(&self, f
: &mut Formatter
) -> Result { Pointer::fmt(self, f) }
974 ($name
:ident
, $
($other
:ident
,)*) => (tuple
! { $($other,)* }
)
979 ( $
($name
:ident
,)+ ) => (
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl<$
($name
:Debug
),*> Debug
for ($
($name
,)*) {
982 #[allow(non_snake_case, unused_assignments)]
983 fn fmt(&self, f
: &mut Formatter
) -> Result
{
984 try
!(write
!(f
, "("));
985 let ($
(ref $name
,)*) = *self;
989 try
!(write
!(f
, ", "));
991 try
!(write
!(f
, "{:?}", *$name
));
995 try
!(write
!(f
, ","));
1000 peel
! { $($name,)* }
1004 tuple
! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 impl<T
: Debug
> Debug
for [T
] {
1008 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1009 self.iter().fold(f
.debug_list(), |b
, e
| b
.entry(e
)).finish()
1013 #[stable(feature = "rust1", since = "1.0.0")]
1015 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1019 impl<T
> Debug
for PhantomData
<T
> {
1020 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1021 f
.pad("PhantomData")
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl<T
: Copy
+ Debug
> Debug
for Cell
<T
> {
1027 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1028 write
!(f
, "Cell {{ value: {:?} }}", self.get())
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 impl<T
: Debug
> Debug
for RefCell
<T
> {
1034 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1035 match self.borrow_state() {
1036 BorrowState
::Unused
| BorrowState
::Reading
=> {
1037 write
!(f
, "RefCell {{ value: {:?} }}", self.borrow())
1039 BorrowState
::Writing
=> write
!(f
, "RefCell {{ <borrowed> }}"),
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 impl<'b
, T
: Debug
> Debug
for Ref
<'b
, T
> {
1046 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1047 Debug
::fmt(&**self, f
)
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 impl<'b
, T
: Debug
> Debug
for RefMut
<'b
, T
> {
1053 fn fmt(&self, f
: &mut Formatter
) -> Result
{
1054 Debug
::fmt(&*(self.deref()), f
)
1058 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1059 // it's a lot easier than creating all of the rt::Piece structures here.