]> git.proxmox.com Git - rustc.git/blob - src/libcore/fmt/mod.rs
Merge tag 'upstream/1.0.0_beta'
[rustc.git] / src / libcore / fmt / mod.rs
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.
4 //
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.
10
11 //! Utilities for formatting and printing strings
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use cell::{Cell, RefCell, Ref, RefMut, BorrowState};
16 use char::CharExt;
17 use clone::Clone;
18 use iter::Iterator;
19 use marker::{Copy, PhantomData, Sized};
20 use mem;
21 use option::Option;
22 use option::Option::{Some, None};
23 use result::Result::Ok;
24 use ops::{Deref, FnOnce};
25 use result;
26 use slice::SliceExt;
27 use slice;
28 use str::{self, StrExt};
29 use self::rt::v1::Alignment;
30
31 pub use self::num::radix;
32 pub use self::num::Radix;
33 pub use self::num::RadixFmt;
34
35 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
36
37 mod num;
38 mod float;
39 mod builders;
40
41 #[stable(feature = "rust1", since = "1.0.0")]
42 #[doc(hidden)]
43 pub mod rt {
44 pub mod v1;
45 }
46
47 #[stable(feature = "rust1", since = "1.0.0")]
48 /// The type returned by formatter methods.
49 pub type Result = result::Result<(), Error>;
50
51 /// The error type which is returned from formatting a message into a stream.
52 ///
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
55 /// some other means.
56 #[stable(feature = "rust1", since = "1.0.0")]
57 #[derive(Copy, Clone, Debug)]
58 pub struct Error;
59
60 /// A collection of methods that are required to format a message into a stream.
61 ///
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.
65 ///
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")]
70 pub trait Write {
71 /// Writes a slice of bytes into this writer, returning whether the write
72 /// succeeded.
73 ///
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.
77 ///
78 /// # Errors
79 ///
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;
83
84 /// Glue for usage of the `write!` macro with implementers of this trait.
85 ///
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);
94
95 impl<'a, T: ?Sized> Write for Adapter<'a, T>
96 where T: Write
97 {
98 fn write_str(&mut self, s: &str) -> Result {
99 self.0.write_str(s)
100 }
101
102 fn write_fmt(&mut self, args: Arguments) -> Result {
103 self.0.write_fmt(args)
104 }
105 }
106
107 write(&mut Adapter(self), args)
108 }
109 }
110
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
113 /// traits.
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub struct Formatter<'a> {
116 flags: u32,
117 fill: char,
118 align: rt::v1::Alignment,
119 width: Option<usize>,
120 precision: Option<usize>,
121
122 buf: &'a mut (Write+'a),
123 curarg: slice::Iter<'a, ArgumentV1<'a>>,
124 args: &'a [ArgumentV1<'a>],
125 }
126
127 // NB. Argument is essentially an optimized partially applied formatting function,
128 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
129
130 enum Void {}
131
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.
136 #[derive(Copy)]
137 #[stable(feature = "rust1", since = "1.0.0")]
138 #[doc(hidden)]
139 pub struct ArgumentV1<'a> {
140 value: &'a Void,
141 formatter: fn(&Void, &mut Formatter) -> Result,
142 }
143
144 impl<'a> Clone for ArgumentV1<'a> {
145 fn clone(&self) -> ArgumentV1<'a> {
146 *self
147 }
148 }
149
150 impl<'a> ArgumentV1<'a> {
151 #[inline(never)]
152 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
153 Display::fmt(x, f)
154 }
155
156 #[doc(hidden)]
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> {
160 unsafe {
161 ArgumentV1 {
162 formatter: mem::transmute(f),
163 value: mem::transmute(x)
164 }
165 }
166 }
167
168 #[doc(hidden)]
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub fn from_usize(x: &usize) -> ArgumentV1 {
171 ArgumentV1::new(x, ArgumentV1::show_usize)
172 }
173
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) })
177 } else {
178 None
179 }
180 }
181 }
182
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, }
187
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> {
195 Arguments {
196 pieces: pieces,
197 fmt: None,
198 args: args
199 }
200 }
201
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> {
213 Arguments {
214 pieces: pieces,
215 fmt: Some(fmt),
216 args: args
217 }
218 }
219 }
220
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.
225 ///
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],
235
236 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
237 fmt: Option<&'a [rt::v1::Argument]>,
238
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>],
242 }
243
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)
248 }
249 }
250
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)
255 }
256 }
257
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"]
265 pub trait Debug {
266 /// Formats the value using the given formatter.
267 #[stable(feature = "rust1", since = "1.0.0")]
268 fn fmt(&self, &mut Formatter) -> Result;
269 }
270
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 \
275 a format string"]
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub trait Display {
278 /// Formats the value using the given formatter.
279 #[stable(feature = "rust1", since = "1.0.0")]
280 fn fmt(&self, &mut Formatter) -> Result;
281 }
282
283 /// Format trait for the `o` character
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub trait Octal {
286 /// Formats the value using the given formatter.
287 #[stable(feature = "rust1", since = "1.0.0")]
288 fn fmt(&self, &mut Formatter) -> Result;
289 }
290
291 /// Format trait for the `b` character
292 #[stable(feature = "rust1", since = "1.0.0")]
293 pub trait Binary {
294 /// Formats the value using the given formatter.
295 #[stable(feature = "rust1", since = "1.0.0")]
296 fn fmt(&self, &mut Formatter) -> Result;
297 }
298
299 /// Format trait for the `x` character
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub trait LowerHex {
302 /// Formats the value using the given formatter.
303 #[stable(feature = "rust1", since = "1.0.0")]
304 fn fmt(&self, &mut Formatter) -> Result;
305 }
306
307 /// Format trait for the `X` character
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub trait UpperHex {
310 /// Formats the value using the given formatter.
311 #[stable(feature = "rust1", since = "1.0.0")]
312 fn fmt(&self, &mut Formatter) -> Result;
313 }
314
315 /// Format trait for the `p` character
316 #[stable(feature = "rust1", since = "1.0.0")]
317 pub trait Pointer {
318 /// Formats the value using the given formatter.
319 #[stable(feature = "rust1", since = "1.0.0")]
320 fn fmt(&self, &mut Formatter) -> Result;
321 }
322
323 /// Format trait for the `e` character
324 #[stable(feature = "rust1", since = "1.0.0")]
325 pub trait LowerExp {
326 /// Formats the value using the given formatter.
327 #[stable(feature = "rust1", since = "1.0.0")]
328 fn fmt(&self, &mut Formatter) -> Result;
329 }
330
331 /// Format trait for the `E` character
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub trait UpperExp {
334 /// Formats the value using the given formatter.
335 #[stable(feature = "rust1", since = "1.0.0")]
336 fn fmt(&self, &mut Formatter) -> Result;
337 }
338
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.
342 ///
343 /// # Arguments
344 ///
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 {
350 flags: 0,
351 width: None,
352 precision: None,
353 buf: output,
354 align: Alignment::Unknown,
355 fill: ' ',
356 args: args.args,
357 curarg: args.args.iter(),
358 };
359
360 let mut pieces = args.pieces.iter();
361
362 match args.fmt {
363 None => {
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));
368 }
369 }
370 Some(fmt) => {
371 // Every spec has a corresponding argument that is preceded by
372 // a string piece.
373 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
374 try!(formatter.buf.write_str(*piece));
375 try!(formatter.run(arg));
376 }
377 }
378 }
379
380 // There can be only one trailing string piece left.
381 match pieces.next() {
382 Some(piece) => {
383 try!(formatter.buf.write_str(*piece));
384 }
385 None => {}
386 }
387
388 Ok(())
389 }
390
391 impl<'a> Formatter<'a> {
392
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);
403
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],
408 };
409
410 // Then actually do some printing
411 (value.formatter)(value.value, self)
412 }
413
414 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
415 match *cnt {
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()
420 }
421 rt::v1::Count::NextParam => {
422 self.curarg.next().and_then(|arg| arg.as_usize())
423 }
424 }
425 }
426
427 // Helper methods used for padding and processing formatting arguments that
428 // all formatting traits can use.
429
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.
433 ///
434 /// # Arguments
435 ///
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
440 ///
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,
445 is_positive: bool,
446 prefix: &str,
447 buf: &str)
448 -> Result {
449 use char::CharExt;
450
451 let mut width = buf.len();
452
453 let mut sign = None;
454 if !is_positive {
455 sign = Some('-'); width += 1;
456 } else if self.flags & (1 << (FlagV1::SignPlus as u32)) != 0 {
457 sign = Some('+'); width += 1;
458 }
459
460 let mut prefixed = false;
461 if self.flags & (1 << (FlagV1::Alternate as u32)) != 0 {
462 prefixed = true; width += prefix.char_len();
463 }
464
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 {
468 let mut b = [0; 4];
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));
472 }
473 if prefixed { f.buf.write_str(prefix) }
474 else { Ok(()) }
475 };
476
477 // The `width` field is more of a `min-width` parameter at this point.
478 match self.width {
479 // If there's no minimum length requirements then we can just
480 // write the bytes.
481 None => {
482 try!(write_prefix(self)); self.buf.write_str(buf)
483 }
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)
488 }
489 // The sign and prefix goes before the padding if the fill character
490 // is zero
491 Some(min) if self.flags & (1 << (FlagV1::SignAwareZeroPad as u32)) != 0 => {
492 self.fill = '0';
493 try!(write_prefix(self));
494 self.with_padding(min - width, Alignment::Right, |f| {
495 f.buf.write_str(buf)
496 })
497 }
498 // Otherwise, the sign and prefix goes after the padding
499 Some(min) => {
500 self.with_padding(min - width, Alignment::Right, |f| {
501 try!(write_prefix(f)); f.buf.write_str(buf)
502 })
503 }
504 }
505 }
506
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:
510 ///
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
516 ///
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);
523 }
524 // The `precision` field can be interpreted as a `max-width` for the
525 // string being formatted
526 match self.precision {
527 Some(max) => {
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();
532 if char_len >= max {
533 let nchars = ::cmp::min(max, char_len);
534 return self.buf.write_str(s.slice_chars(0, nchars));
535 }
536 }
537 None => {}
538 }
539 // The `width` field is more of a `min-width` parameter at this point.
540 match self.width {
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)
548 }
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.
551 Some(width) => {
552 self.with_padding(width - s.char_len(), Alignment::Left, |me| {
553 me.buf.write_str(s)
554 })
555 }
556 }
557 }
558
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,
562 f: F) -> Result
563 where F: FnOnce(&mut Formatter) -> Result,
564 {
565 use char::CharExt;
566 let align = match self.align {
567 Alignment::Unknown => default,
568 _ => self.align
569 };
570
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),
575 };
576
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]) };
580
581 for _ in 0..pre_pad {
582 try!(self.buf.write_str(fill));
583 }
584
585 try!(f(self));
586
587 for _ in 0..post_pad {
588 try!(self.buf.write_str(fill));
589 }
590
591 Ok(())
592 }
593
594 /// Writes some data to the underlying buffer contained within this
595 /// formatter.
596 #[stable(feature = "rust1", since = "1.0.0")]
597 pub fn write_str(&mut self, data: &str) -> Result {
598 self.buf.write_str(data)
599 }
600
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 {
604 write(self.buf, fmt)
605 }
606
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 }
610
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 }
614
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 }
618
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 }
622
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 }
626
627 /// Creates a `DebugStruct` builder designed to assist with creation of
628 /// `fmt::Debug` implementations for structs.
629 ///
630 /// # Examples
631 ///
632 /// ```rust
633 /// # #![feature(debug_builders, core)]
634 /// use std::fmt;
635 ///
636 /// struct Foo {
637 /// bar: i32,
638 /// baz: String,
639 /// }
640 ///
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)
646 /// .finish()
647 /// }
648 /// }
649 ///
650 /// // prints "Foo { bar: 10, baz: "Hello World" }"
651 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
652 /// ```
653 #[unstable(feature = "debug_builders", reason = "method was just created")]
654 #[inline]
655 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
656 builders::debug_struct_new(self, name)
657 }
658
659 /// Creates a `DebugTuple` builder designed to assist with creation of
660 /// `fmt::Debug` implementations for tuple structs.
661 ///
662 /// # Examples
663 ///
664 /// ```rust
665 /// # #![feature(debug_builders, core)]
666 /// use std::fmt;
667 ///
668 /// struct Foo(i32, String);
669 ///
670 /// impl fmt::Debug for Foo {
671 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
672 /// fmt.debug_tuple("Foo")
673 /// .field(&self.0)
674 /// .field(&self.1)
675 /// .finish()
676 /// }
677 /// }
678 ///
679 /// // prints "Foo(10, "Hello World")"
680 /// println!("{:?}", Foo(10, "Hello World".to_string()));
681 /// ```
682 #[unstable(feature = "debug_builders", reason = "method was just created")]
683 #[inline]
684 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
685 builders::debug_tuple_new(self, name)
686 }
687
688 /// Creates a `DebugList` builder designed to assist with creation of
689 /// `fmt::Debug` implementations for list-like structures.
690 ///
691 /// # Examples
692 ///
693 /// ```rust
694 /// # #![feature(debug_builders, core)]
695 /// use std::fmt;
696 ///
697 /// struct Foo(Vec<i32>);
698 ///
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()
702 /// }
703 /// }
704 ///
705 /// // prints "[10, 11]"
706 /// println!("{:?}", Foo(vec![10, 11]));
707 /// ```
708 #[unstable(feature = "debug_builders", reason = "method was just created")]
709 #[inline]
710 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
711 builders::debug_list_new(self)
712 }
713
714 /// Creates a `DebugSet` builder designed to assist with creation of
715 /// `fmt::Debug` implementations for set-like structures.
716 ///
717 /// # Examples
718 ///
719 /// ```rust
720 /// # #![feature(debug_builders, core)]
721 /// use std::fmt;
722 ///
723 /// struct Foo(Vec<i32>);
724 ///
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()
728 /// }
729 /// }
730 ///
731 /// // prints "{10, 11}"
732 /// println!("{:?}", Foo(vec![10, 11]));
733 /// ```
734 #[unstable(feature = "debug_builders", reason = "method was just created")]
735 #[inline]
736 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
737 builders::debug_set_new(self)
738 }
739
740 /// Creates a `DebugMap` builder designed to assist with creation of
741 /// `fmt::Debug` implementations for map-like structures.
742 ///
743 /// # Examples
744 ///
745 /// ```rust
746 /// # #![feature(debug_builders, core)]
747 /// use std::fmt;
748 ///
749 /// struct Foo(Vec<(String, i32)>);
750 ///
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()
754 /// }
755 /// }
756 ///
757 /// // prints "{"A": 10, "B": 11}"
758 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
759 /// ```
760 #[unstable(feature = "debug_builders", reason = "method was just created")]
761 #[inline]
762 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
763 builders::debug_map_new(self)
764 }
765 }
766
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)
771 }
772 }
773
774 // Implementations of the core formatting traits
775
776 macro_rules! fmt_refs {
777 ($($tr:ident),*) => {
778 $(
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) }
782 }
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) }
786 }
787 )*
788 }
789 }
790
791 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
792
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)
797 }
798 }
799
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)
804 }
805 }
806
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl Debug for str {
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));
813 }
814 write!(f, "\"")
815 }
816 }
817
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl Display for str {
820 fn fmt(&self, f: &mut Formatter) -> Result {
821 f.pad(self)
822 }
823 }
824
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl Debug for char {
827 fn fmt(&self, f: &mut Formatter) -> Result {
828 use char::CharExt;
829 try!(write!(f, "'"));
830 for c in self.escape_default() {
831 try!(write!(f, "{}", c));
832 }
833 write!(f, "'")
834 }
835 }
836
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]) };
843 Display::fmt(s, f)
844 }
845 }
846
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));
853 ret
854 }
855 }
856
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)
863 }
864 }
865
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)
872 }
873 }
874
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)
881 }
882 }
883
884 macro_rules! floating { ($ty:ident) => {
885
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl Debug for $ty {
888 fn fmt(&self, fmt: &mut Formatter) -> Result {
889 Display::fmt(self, fmt)
890 }
891 }
892
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl Display for $ty {
895 fn fmt(&self, fmt: &mut Formatter) -> Result {
896 use num::Float;
897
898 let digits = match fmt.precision {
899 Some(i) => float::DigExact(i),
900 None => float::DigMax(6),
901 };
902 float::float_to_str_bytes_common(self.abs(),
903 10,
904 true,
905 float::SignNeg,
906 digits,
907 float::ExpNone,
908 false,
909 |bytes| {
910 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
911 })
912 }
913 }
914
915 #[stable(feature = "rust1", since = "1.0.0")]
916 impl LowerExp for $ty {
917 fn fmt(&self, fmt: &mut Formatter) -> Result {
918 use num::Float;
919
920 let digits = match fmt.precision {
921 Some(i) => float::DigExact(i),
922 None => float::DigMax(6),
923 };
924 float::float_to_str_bytes_common(self.abs(),
925 10,
926 true,
927 float::SignNeg,
928 digits,
929 float::ExpDec,
930 false,
931 |bytes| {
932 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
933 })
934 }
935 }
936
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl UpperExp for $ty {
939 fn fmt(&self, fmt: &mut Formatter) -> Result {
940 use num::Float;
941
942 let digits = match fmt.precision {
943 Some(i) => float::DigExact(i),
944 None => float::DigMax(6),
945 };
946 float::float_to_str_bytes_common(self.abs(),
947 10,
948 true,
949 float::SignNeg,
950 digits,
951 float::ExpDec,
952 true,
953 |bytes| {
954 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
955 })
956 }
957 }
958 } }
959 floating! { f32 }
960 floating! { f64 }
961
962 // Implementation of Display/Debug for various core types
963
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) }
967 }
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) }
971 }
972
973 macro_rules! peel {
974 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
975 }
976
977 macro_rules! tuple {
978 () => ();
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;
986 let mut n = 0;
987 $(
988 if n > 0 {
989 try!(write!(f, ", "));
990 }
991 try!(write!(f, "{:?}", *$name));
992 n += 1;
993 )*
994 if n == 1 {
995 try!(write!(f, ","));
996 }
997 write!(f, ")")
998 }
999 }
1000 peel! { $($name,)* }
1001 )
1002 }
1003
1004 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1005
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()
1010 }
1011 }
1012
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 impl Debug for () {
1015 fn fmt(&self, f: &mut Formatter) -> Result {
1016 f.pad("()")
1017 }
1018 }
1019 impl<T> Debug for PhantomData<T> {
1020 fn fmt(&self, f: &mut Formatter) -> Result {
1021 f.pad("PhantomData")
1022 }
1023 }
1024
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())
1029 }
1030 }
1031
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())
1038 }
1039 BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
1040 }
1041 }
1042 }
1043
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)
1048 }
1049 }
1050
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)
1055 }
1056 }
1057
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.