]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/mod.rs
6579e5dab543245ccd56934ec787974880d00adf
[rust.git] / src / libcore / fmt / mod.rs
1 // Copyright 2013-2015 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 prelude::v1::*;
16
17 use cell::{UnsafeCell, Cell, RefCell, Ref, RefMut, BorrowState};
18 use marker::PhantomData;
19 use mem;
20 use num::flt2dec;
21 use ops::Deref;
22 use result;
23 use slice;
24 use str;
25
26 #[unstable(feature = "fmt_flags_align", issue = "27726")]
27 /// Possible alignments returned by `Formatter::align`
28 #[derive(Debug)]
29 pub enum Alignment {
30     /// Indication that contents should be left-aligned.
31     Left,
32     /// Indication that contents should be right-aligned.
33     Right,
34     /// Indication that contents should be center-aligned.
35     Center,
36     /// No alignment was requested.
37     Unknown,
38 }
39
40 #[stable(feature = "debug_builders", since = "1.2.0")]
41 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
42
43 mod num;
44 mod builders;
45
46 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
47            issue = "0")]
48 #[doc(hidden)]
49 pub mod rt {
50     pub mod v1;
51 }
52
53 #[stable(feature = "rust1", since = "1.0.0")]
54 /// The type returned by formatter methods.
55 pub type Result = result::Result<(), Error>;
56
57 /// The error type which is returned from formatting a message into a stream.
58 ///
59 /// This type does not support transmission of an error other than that an error
60 /// occurred. Any extra information must be arranged to be transmitted through
61 /// some other means.
62 #[stable(feature = "rust1", since = "1.0.0")]
63 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
64 pub struct Error;
65
66 /// A collection of methods that are required to format a message into a stream.
67 ///
68 /// This trait is the type which this modules requires when formatting
69 /// information. This is similar to the standard library's `io::Write` trait,
70 /// but it is only intended for use in libcore.
71 ///
72 /// This trait should generally not be implemented by consumers of the standard
73 /// library. The `write!` macro accepts an instance of `io::Write`, and the
74 /// `io::Write` trait is favored over implementing this trait.
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub trait Write {
77     /// Writes a slice of bytes into this writer, returning whether the write
78     /// succeeded.
79     ///
80     /// This method can only succeed if the entire byte slice was successfully
81     /// written, and this method will not return until all data has been
82     /// written or an error occurs.
83     ///
84     /// # Errors
85     ///
86     /// This function will return an instance of `Error` on error.
87     #[stable(feature = "rust1", since = "1.0.0")]
88     fn write_str(&mut self, s: &str) -> Result;
89
90     /// Writes a `char` into this writer, returning whether the write succeeded.
91     ///
92     /// A single `char` may be encoded as more than one byte.
93     /// This method can only succeed if the entire byte sequence was successfully
94     /// written, and this method will not return until all data has been
95     /// written or an error occurs.
96     ///
97     /// # Errors
98     ///
99     /// This function will return an instance of `Error` on error.
100     #[stable(feature = "fmt_write_char", since = "1.1.0")]
101     fn write_char(&mut self, c: char) -> Result {
102         self.write_str(unsafe {
103             str::from_utf8_unchecked(c.encode_utf8().as_slice())
104         })
105     }
106
107     /// Glue for usage of the `write!` macro with implementors of this trait.
108     ///
109     /// This method should generally not be invoked manually, but rather through
110     /// the `write!` macro itself.
111     #[stable(feature = "rust1", since = "1.0.0")]
112     fn write_fmt(&mut self, args: Arguments) -> Result {
113         // This Adapter is needed to allow `self` (of type `&mut
114         // Self`) to be cast to a Write (below) without
115         // requiring a `Sized` bound.
116         struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
117
118         impl<'a, T: ?Sized> Write for Adapter<'a, T>
119             where T: Write
120         {
121             fn write_str(&mut self, s: &str) -> Result {
122                 self.0.write_str(s)
123             }
124
125             fn write_char(&mut self, c: char) -> Result {
126                 self.0.write_char(c)
127             }
128
129             fn write_fmt(&mut self, args: Arguments) -> Result {
130                 self.0.write_fmt(args)
131             }
132         }
133
134         write(&mut Adapter(self), args)
135     }
136 }
137
138 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
139 impl<'a, W: Write + ?Sized> Write for &'a mut W {
140     fn write_str(&mut self, s: &str) -> Result {
141         (**self).write_str(s)
142     }
143
144     fn write_char(&mut self, c: char) -> Result {
145         (**self).write_char(c)
146     }
147
148     fn write_fmt(&mut self, args: Arguments) -> Result {
149         (**self).write_fmt(args)
150     }
151 }
152
153 /// A struct to represent both where to emit formatting strings to and how they
154 /// should be formatted. A mutable version of this is passed to all formatting
155 /// traits.
156 #[allow(missing_debug_implementations)]
157 #[stable(feature = "rust1", since = "1.0.0")]
158 pub struct Formatter<'a> {
159     flags: u32,
160     fill: char,
161     align: rt::v1::Alignment,
162     width: Option<usize>,
163     precision: Option<usize>,
164
165     buf: &'a mut (Write+'a),
166     curarg: slice::Iter<'a, ArgumentV1<'a>>,
167     args: &'a [ArgumentV1<'a>],
168 }
169
170 // NB. Argument is essentially an optimized partially applied formatting function,
171 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
172
173 enum Void {}
174
175 /// This struct represents the generic "argument" which is taken by the Xprintf
176 /// family of functions. It contains a function to format the given value. At
177 /// compile time it is ensured that the function and the value have the correct
178 /// types, and then this struct is used to canonicalize arguments to one type.
179 #[derive(Copy)]
180 #[allow(missing_debug_implementations)]
181 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
182            issue = "0")]
183 #[doc(hidden)]
184 pub struct ArgumentV1<'a> {
185     value: &'a Void,
186     formatter: fn(&Void, &mut Formatter) -> Result,
187 }
188
189 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
190            issue = "0")]
191 impl<'a> Clone for ArgumentV1<'a> {
192     fn clone(&self) -> ArgumentV1<'a> {
193         *self
194     }
195 }
196
197 impl<'a> ArgumentV1<'a> {
198     #[inline(never)]
199     fn show_usize(x: &usize, f: &mut Formatter) -> Result {
200         Display::fmt(x, f)
201     }
202
203     #[doc(hidden)]
204     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
205                issue = "0")]
206     pub fn new<'b, T>(x: &'b T,
207                       f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
208         unsafe {
209             ArgumentV1 {
210                 formatter: mem::transmute(f),
211                 value: mem::transmute(x)
212             }
213         }
214     }
215
216     #[doc(hidden)]
217     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
218                issue = "0")]
219     pub fn from_usize(x: &usize) -> ArgumentV1 {
220         ArgumentV1::new(x, ArgumentV1::show_usize)
221     }
222
223     fn as_usize(&self) -> Option<usize> {
224         if self.formatter as usize == ArgumentV1::show_usize as usize {
225             Some(unsafe { *(self.value as *const _ as *const usize) })
226         } else {
227             None
228         }
229     }
230 }
231
232 // flags available in the v1 format of format_args
233 #[derive(Copy, Clone)]
234 #[allow(dead_code)] // SignMinus isn't currently used
235 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
236
237 impl<'a> Arguments<'a> {
238     /// When using the format_args!() macro, this function is used to generate the
239     /// Arguments structure.
240     #[doc(hidden)] #[inline]
241     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
242                issue = "0")]
243     pub fn new_v1(pieces: &'a [&'a str],
244                   args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
245         Arguments {
246             pieces: pieces,
247             fmt: None,
248             args: args
249         }
250     }
251
252     /// This function is used to specify nonstandard formatting parameters.
253     /// The `pieces` array must be at least as long as `fmt` to construct
254     /// a valid Arguments structure. Also, any `Count` within `fmt` that is
255     /// `CountIsParam` or `CountIsNextParam` has to point to an argument
256     /// created with `argumentusize`. However, failing to do so doesn't cause
257     /// unsafety, but will ignore invalid .
258     #[doc(hidden)] #[inline]
259     #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
260                issue = "0")]
261     pub fn new_v1_formatted(pieces: &'a [&'a str],
262                             args: &'a [ArgumentV1<'a>],
263                             fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
264         Arguments {
265             pieces: pieces,
266             fmt: Some(fmt),
267             args: args
268         }
269     }
270 }
271
272 /// This structure represents a safely precompiled version of a format string
273 /// and its arguments. This cannot be generated at runtime because it cannot
274 /// safely be done so, so no constructors are given and the fields are private
275 /// to prevent modification.
276 ///
277 /// The `format_args!` macro will safely create an instance of this structure
278 /// and pass it to a function or closure, passed as the first argument. The
279 /// macro validates the format string at compile-time so usage of the `write`
280 /// and `format` functions can be safely performed.
281 #[stable(feature = "rust1", since = "1.0.0")]
282 #[derive(Copy, Clone)]
283 pub struct Arguments<'a> {
284     // Format string pieces to print.
285     pieces: &'a [&'a str],
286
287     // Placeholder specs, or `None` if all specs are default (as in "{}{}").
288     fmt: Option<&'a [rt::v1::Argument]>,
289
290     // Dynamic arguments for interpolation, to be interleaved with string
291     // pieces. (Every argument is preceded by a string piece.)
292     args: &'a [ArgumentV1<'a>],
293 }
294
295 #[stable(feature = "rust1", since = "1.0.0")]
296 impl<'a> Debug for Arguments<'a> {
297     fn fmt(&self, fmt: &mut Formatter) -> Result {
298         Display::fmt(self, fmt)
299     }
300 }
301
302 #[stable(feature = "rust1", since = "1.0.0")]
303 impl<'a> Display for Arguments<'a> {
304     fn fmt(&self, fmt: &mut Formatter) -> Result {
305         write(fmt.buf, *self)
306     }
307 }
308
309 /// Format trait for the `?` character.
310 ///
311 /// `Debug` should format the output in a programmer-facing, debugging context.
312 ///
313 /// Generally speaking, you should just `derive` a `Debug` implementation.
314 ///
315 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
316 ///
317 /// For more information on formatters, see [the module-level documentation][module].
318 ///
319 /// [module]: ../../std/fmt/index.html
320 ///
321 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
322 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
323 /// comma-separated list of each field's name and `Debug` value, then `}`. For
324 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
325 /// `Debug` values of the fields, then `)`.
326 ///
327 /// # Examples
328 ///
329 /// Deriving an implementation:
330 ///
331 /// ```
332 /// #[derive(Debug)]
333 /// struct Point {
334 ///     x: i32,
335 ///     y: i32,
336 /// }
337 ///
338 /// let origin = Point { x: 0, y: 0 };
339 ///
340 /// println!("The origin is: {:?}", origin);
341 /// ```
342 ///
343 /// Manually implementing:
344 ///
345 /// ```
346 /// use std::fmt;
347 ///
348 /// struct Point {
349 ///     x: i32,
350 ///     y: i32,
351 /// }
352 ///
353 /// impl fmt::Debug for Point {
354 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
355 ///         write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
356 ///     }
357 /// }
358 ///
359 /// let origin = Point { x: 0, y: 0 };
360 ///
361 /// println!("The origin is: {:?}", origin);
362 /// ```
363 ///
364 /// This outputs:
365 ///
366 /// ```text
367 /// The origin is: Point { x: 0, y: 0 }
368 /// ```
369 ///
370 /// There are a number of `debug_*` methods on `Formatter` to help you with manual
371 /// implementations, such as [`debug_struct`][debug_struct].
372 ///
373 /// `Debug` implementations using either `derive` or the debug builder API
374 /// on `Formatter` support pretty printing using the alternate flag: `{:#?}`.
375 ///
376 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
377 ///
378 /// Pretty printing with `#?`:
379 ///
380 /// ```
381 /// #[derive(Debug)]
382 /// struct Point {
383 ///     x: i32,
384 ///     y: i32,
385 /// }
386 ///
387 /// let origin = Point { x: 0, y: 0 };
388 ///
389 /// println!("The origin is: {:#?}", origin);
390 /// ```
391 ///
392 /// This outputs:
393 ///
394 /// ```text
395 /// The origin is: Point {
396 ///     x: 0,
397 ///     y: 0
398 /// }
399 /// ```
400 #[stable(feature = "rust1", since = "1.0.0")]
401 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
402                             defined in your crate, add `#[derive(Debug)]` or \
403                             manually implement it"]
404 #[lang = "debug_trait"]
405 pub trait Debug {
406     /// Formats the value using the given formatter.
407     #[stable(feature = "rust1", since = "1.0.0")]
408     fn fmt(&self, &mut Formatter) -> Result;
409 }
410
411 /// Format trait for an empty format, `{}`.
412 ///
413 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
414 /// output, and so cannot be derived.
415 ///
416 /// [debug]: trait.Debug.html
417 ///
418 /// For more information on formatters, see [the module-level documentation][module].
419 ///
420 /// [module]: ../../std/fmt/index.html
421 ///
422 /// # Examples
423 ///
424 /// Implementing `Display` on a type:
425 ///
426 /// ```
427 /// use std::fmt;
428 ///
429 /// struct Point {
430 ///     x: i32,
431 ///     y: i32,
432 /// }
433 ///
434 /// impl fmt::Display for Point {
435 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
436 ///         write!(f, "({}, {})", self.x, self.y)
437 ///     }
438 /// }
439 ///
440 /// let origin = Point { x: 0, y: 0 };
441 ///
442 /// println!("The origin is: {}", origin);
443 /// ```
444 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
445                             formatter; try using `:?` instead if you are using \
446                             a format string"]
447 #[stable(feature = "rust1", since = "1.0.0")]
448 pub trait Display {
449     /// Formats the value using the given formatter.
450     #[stable(feature = "rust1", since = "1.0.0")]
451     fn fmt(&self, &mut Formatter) -> Result;
452 }
453
454 /// Format trait for the `o` character.
455 ///
456 /// The `Octal` trait should format its output as a number in base-8.
457 ///
458 /// The alternate flag, `#`, adds a `0o` in front of the output.
459 ///
460 /// For more information on formatters, see [the module-level documentation][module].
461 ///
462 /// [module]: ../../std/fmt/index.html
463 ///
464 /// # Examples
465 ///
466 /// Basic usage with `i32`:
467 ///
468 /// ```
469 /// let x = 42; // 42 is '52' in octal
470 ///
471 /// assert_eq!(format!("{:o}", x), "52");
472 /// assert_eq!(format!("{:#o}", x), "0o52");
473 /// ```
474 ///
475 /// Implementing `Octal` on a type:
476 ///
477 /// ```
478 /// use std::fmt;
479 ///
480 /// struct Length(i32);
481 ///
482 /// impl fmt::Octal for Length {
483 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
484 ///         let val = self.0;
485 ///
486 ///         write!(f, "{:o}", val) // delegate to i32's implementation
487 ///     }
488 /// }
489 ///
490 /// let l = Length(9);
491 ///
492 /// println!("l as octal is: {:o}", l);
493 /// ```
494 #[stable(feature = "rust1", since = "1.0.0")]
495 pub trait Octal {
496     /// Formats the value using the given formatter.
497     #[stable(feature = "rust1", since = "1.0.0")]
498     fn fmt(&self, &mut Formatter) -> Result;
499 }
500
501 /// Format trait for the `b` character.
502 ///
503 /// The `Binary` trait should format its output as a number in binary.
504 ///
505 /// The alternate flag, `#`, adds a `0b` in front of the output.
506 ///
507 /// For more information on formatters, see [the module-level documentation][module].
508 ///
509 /// [module]: ../../std/fmt/index.html
510 ///
511 /// # Examples
512 ///
513 /// Basic usage with `i32`:
514 ///
515 /// ```
516 /// let x = 42; // 42 is '101010' in binary
517 ///
518 /// assert_eq!(format!("{:b}", x), "101010");
519 /// assert_eq!(format!("{:#b}", x), "0b101010");
520 /// ```
521 ///
522 /// Implementing `Binary` on a type:
523 ///
524 /// ```
525 /// use std::fmt;
526 ///
527 /// struct Length(i32);
528 ///
529 /// impl fmt::Binary for Length {
530 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
531 ///         let val = self.0;
532 ///
533 ///         write!(f, "{:b}", val) // delegate to i32's implementation
534 ///     }
535 /// }
536 ///
537 /// let l = Length(107);
538 ///
539 /// println!("l as binary is: {:b}", l);
540 /// ```
541 #[stable(feature = "rust1", since = "1.0.0")]
542 pub trait Binary {
543     /// Formats the value using the given formatter.
544     #[stable(feature = "rust1", since = "1.0.0")]
545     fn fmt(&self, &mut Formatter) -> Result;
546 }
547
548 /// Format trait for the `x` character.
549 ///
550 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
551 /// in lower case.
552 ///
553 /// The alternate flag, `#`, adds a `0x` in front of the output.
554 ///
555 /// For more information on formatters, see [the module-level documentation][module].
556 ///
557 /// [module]: ../../std/fmt/index.html
558 ///
559 /// # Examples
560 ///
561 /// Basic usage with `i32`:
562 ///
563 /// ```
564 /// let x = 42; // 42 is '2a' in hex
565 ///
566 /// assert_eq!(format!("{:x}", x), "2a");
567 /// assert_eq!(format!("{:#x}", x), "0x2a");
568 /// ```
569 ///
570 /// Implementing `LowerHex` on a type:
571 ///
572 /// ```
573 /// use std::fmt;
574 ///
575 /// struct Length(i32);
576 ///
577 /// impl fmt::LowerHex for Length {
578 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
579 ///         let val = self.0;
580 ///
581 ///         write!(f, "{:x}", val) // delegate to i32's implementation
582 ///     }
583 /// }
584 ///
585 /// let l = Length(9);
586 ///
587 /// println!("l as hex is: {:x}", l);
588 /// ```
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub trait LowerHex {
591     /// Formats the value using the given formatter.
592     #[stable(feature = "rust1", since = "1.0.0")]
593     fn fmt(&self, &mut Formatter) -> Result;
594 }
595
596 /// Format trait for the `X` character.
597 ///
598 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
599 /// in upper case.
600 ///
601 /// The alternate flag, `#`, adds a `0x` in front of the output.
602 ///
603 /// For more information on formatters, see [the module-level documentation][module].
604 ///
605 /// [module]: ../../std/fmt/index.html
606 ///
607 /// # Examples
608 ///
609 /// Basic usage with `i32`:
610 ///
611 /// ```
612 /// let x = 42; // 42 is '2A' in hex
613 ///
614 /// assert_eq!(format!("{:X}", x), "2A");
615 /// assert_eq!(format!("{:#X}", x), "0x2A");
616 /// ```
617 ///
618 /// Implementing `UpperHex` on a type:
619 ///
620 /// ```
621 /// use std::fmt;
622 ///
623 /// struct Length(i32);
624 ///
625 /// impl fmt::UpperHex for Length {
626 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
627 ///         let val = self.0;
628 ///
629 ///         write!(f, "{:X}", val) // delegate to i32's implementation
630 ///     }
631 /// }
632 ///
633 /// let l = Length(9);
634 ///
635 /// println!("l as hex is: {:X}", l);
636 /// ```
637 #[stable(feature = "rust1", since = "1.0.0")]
638 pub trait UpperHex {
639     /// Formats the value using the given formatter.
640     #[stable(feature = "rust1", since = "1.0.0")]
641     fn fmt(&self, &mut Formatter) -> Result;
642 }
643
644 /// Format trait for the `p` character.
645 ///
646 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
647 /// as hexadecimal.
648 ///
649 /// For more information on formatters, see [the module-level documentation][module].
650 ///
651 /// [module]: ../../std/fmt/index.html
652 ///
653 /// # Examples
654 ///
655 /// Basic usage with `&i32`:
656 ///
657 /// ```
658 /// let x = &42;
659 ///
660 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
661 /// ```
662 ///
663 /// Implementing `Pointer` on a type:
664 ///
665 /// ```
666 /// use std::fmt;
667 ///
668 /// struct Length(i32);
669 ///
670 /// impl fmt::Pointer for Length {
671 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
672 ///         // use `as` to convert to a `*const T`, which implements Pointer, which we can use
673 ///
674 ///         write!(f, "{:p}", self as *const Length)
675 ///     }
676 /// }
677 ///
678 /// let l = Length(42);
679 ///
680 /// println!("l is in memory here: {:p}", l);
681 /// ```
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub trait Pointer {
684     /// Formats the value using the given formatter.
685     #[stable(feature = "rust1", since = "1.0.0")]
686     fn fmt(&self, &mut Formatter) -> Result;
687 }
688
689 /// Format trait for the `e` character.
690 ///
691 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
692 ///
693 /// For more information on formatters, see [the module-level documentation][module].
694 ///
695 /// [module]: ../../std/fmt/index.html
696 ///
697 /// # Examples
698 ///
699 /// Basic usage with `i32`:
700 ///
701 /// ```
702 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
703 ///
704 /// assert_eq!(format!("{:e}", x), "4.2e1");
705 /// ```
706 ///
707 /// Implementing `LowerExp` on a type:
708 ///
709 /// ```
710 /// use std::fmt;
711 ///
712 /// struct Length(i32);
713 ///
714 /// impl fmt::LowerExp for Length {
715 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
716 ///         let val = self.0;
717 ///         write!(f, "{}e1", val / 10)
718 ///     }
719 /// }
720 ///
721 /// let l = Length(100);
722 ///
723 /// println!("l in scientific notation is: {:e}", l);
724 /// ```
725 #[stable(feature = "rust1", since = "1.0.0")]
726 pub trait LowerExp {
727     /// Formats the value using the given formatter.
728     #[stable(feature = "rust1", since = "1.0.0")]
729     fn fmt(&self, &mut Formatter) -> Result;
730 }
731
732 /// Format trait for the `E` character.
733 ///
734 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
735 ///
736 /// For more information on formatters, see [the module-level documentation][module].
737 ///
738 /// [module]: ../../std/fmt/index.html
739 ///
740 /// # Examples
741 ///
742 /// Basic usage with `f32`:
743 ///
744 /// ```
745 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
746 ///
747 /// assert_eq!(format!("{:E}", x), "4.2E1");
748 /// ```
749 ///
750 /// Implementing `UpperExp` on a type:
751 ///
752 /// ```
753 /// use std::fmt;
754 ///
755 /// struct Length(i32);
756 ///
757 /// impl fmt::UpperExp for Length {
758 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
759 ///         let val = self.0;
760 ///         write!(f, "{}E1", val / 10)
761 ///     }
762 /// }
763 ///
764 /// let l = Length(100);
765 ///
766 /// println!("l in scientific notation is: {:E}", l);
767 /// ```
768 #[stable(feature = "rust1", since = "1.0.0")]
769 pub trait UpperExp {
770     /// Formats the value using the given formatter.
771     #[stable(feature = "rust1", since = "1.0.0")]
772     fn fmt(&self, &mut Formatter) -> Result;
773 }
774
775 /// The `write` function takes an output stream, a precompiled format string,
776 /// and a list of arguments. The arguments will be formatted according to the
777 /// specified format string into the output stream provided.
778 ///
779 /// # Arguments
780 ///
781 ///   * output - the buffer to write output to
782 ///   * args - the precompiled arguments generated by `format_args!`
783 ///
784 /// # Examples
785 ///
786 /// Basic usage:
787 ///
788 /// ```
789 /// use std::fmt;
790 ///
791 /// let mut output = String::new();
792 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
793 ///     .expect("Error occurred while trying to write in String");
794 /// assert_eq!(output, "Hello world!");
795 /// ```
796 ///
797 /// Please note that using [`write!`][write_macro] might be preferrable. Example:
798 ///
799 /// ```
800 /// use std::fmt::Write;
801 ///
802 /// let mut output = String::new();
803 /// write!(&mut output, "Hello {}!", "world")
804 ///     .expect("Error occurred while trying to write in String");
805 /// assert_eq!(output, "Hello world!");
806 /// ```
807 ///
808 /// [write_macro]: ../../std/macro.write!.html
809 #[stable(feature = "rust1", since = "1.0.0")]
810 pub fn write(output: &mut Write, args: Arguments) -> Result {
811     let mut formatter = Formatter {
812         flags: 0,
813         width: None,
814         precision: None,
815         buf: output,
816         align: rt::v1::Alignment::Unknown,
817         fill: ' ',
818         args: args.args,
819         curarg: args.args.iter(),
820     };
821
822     let mut pieces = args.pieces.iter();
823
824     match args.fmt {
825         None => {
826             // We can use default formatting parameters for all arguments.
827             for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
828                 formatter.buf.write_str(*piece)?;
829                 (arg.formatter)(arg.value, &mut formatter)?;
830             }
831         }
832         Some(fmt) => {
833             // Every spec has a corresponding argument that is preceded by
834             // a string piece.
835             for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
836                 formatter.buf.write_str(*piece)?;
837                 formatter.run(arg)?;
838             }
839         }
840     }
841
842     // There can be only one trailing string piece left.
843     match pieces.next() {
844         Some(piece) => {
845             formatter.buf.write_str(*piece)?;
846         }
847         None => {}
848     }
849
850     Ok(())
851 }
852
853 impl<'a> Formatter<'a> {
854
855     // First up is the collection of functions used to execute a format string
856     // at runtime. This consumes all of the compile-time statics generated by
857     // the format! syntax extension.
858     fn run(&mut self, arg: &rt::v1::Argument) -> Result {
859         // Fill in the format parameters into the formatter
860         self.fill = arg.format.fill;
861         self.align = arg.format.align;
862         self.flags = arg.format.flags;
863         self.width = self.getcount(&arg.format.width);
864         self.precision = self.getcount(&arg.format.precision);
865
866         // Extract the correct argument
867         let value = match arg.position {
868             rt::v1::Position::Next => { *self.curarg.next().unwrap() }
869             rt::v1::Position::At(i) => self.args[i],
870         };
871
872         // Then actually do some printing
873         (value.formatter)(value.value, self)
874     }
875
876     fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
877         match *cnt {
878             rt::v1::Count::Is(n) => Some(n),
879             rt::v1::Count::Implied => None,
880             rt::v1::Count::Param(i) => {
881                 self.args[i].as_usize()
882             }
883             rt::v1::Count::NextParam => {
884                 self.curarg.next().and_then(|arg| arg.as_usize())
885             }
886         }
887     }
888
889     // Helper methods used for padding and processing formatting arguments that
890     // all formatting traits can use.
891
892     /// Performs the correct padding for an integer which has already been
893     /// emitted into a str. The str should *not* contain the sign for the
894     /// integer, that will be added by this method.
895     ///
896     /// # Arguments
897     ///
898     /// * is_nonnegative - whether the original integer was either positive or zero.
899     /// * prefix - if the '#' character (Alternate) is provided, this
900     ///   is the prefix to put in front of the number.
901     /// * buf - the byte array that the number has been formatted into
902     ///
903     /// This function will correctly account for the flags provided as well as
904     /// the minimum width. It will not take precision into account.
905     #[stable(feature = "rust1", since = "1.0.0")]
906     pub fn pad_integral(&mut self,
907                         is_nonnegative: bool,
908                         prefix: &str,
909                         buf: &str)
910                         -> Result {
911         use char::CharExt;
912
913         let mut width = buf.len();
914
915         let mut sign = None;
916         if !is_nonnegative {
917             sign = Some('-'); width += 1;
918         } else if self.sign_plus() {
919             sign = Some('+'); width += 1;
920         }
921
922         let mut prefixed = false;
923         if self.alternate() {
924             prefixed = true; width += prefix.chars().count();
925         }
926
927         // Writes the sign if it exists, and then the prefix if it was requested
928         let write_prefix = |f: &mut Formatter| {
929             if let Some(c) = sign {
930                 f.buf.write_str(unsafe {
931                     str::from_utf8_unchecked(c.encode_utf8().as_slice())
932                 })?;
933             }
934             if prefixed { f.buf.write_str(prefix) }
935             else { Ok(()) }
936         };
937
938         // The `width` field is more of a `min-width` parameter at this point.
939         match self.width {
940             // If there's no minimum length requirements then we can just
941             // write the bytes.
942             None => {
943                 write_prefix(self)?; self.buf.write_str(buf)
944             }
945             // Check if we're over the minimum width, if so then we can also
946             // just write the bytes.
947             Some(min) if width >= min => {
948                 write_prefix(self)?; self.buf.write_str(buf)
949             }
950             // The sign and prefix goes before the padding if the fill character
951             // is zero
952             Some(min) if self.sign_aware_zero_pad() => {
953                 self.fill = '0';
954                 write_prefix(self)?;
955                 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
956                     f.buf.write_str(buf)
957                 })
958             }
959             // Otherwise, the sign and prefix goes after the padding
960             Some(min) => {
961                 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
962                     write_prefix(f)?; f.buf.write_str(buf)
963                 })
964             }
965         }
966     }
967
968     /// This function takes a string slice and emits it to the internal buffer
969     /// after applying the relevant formatting flags specified. The flags
970     /// recognized for generic strings are:
971     ///
972     /// * width - the minimum width of what to emit
973     /// * fill/align - what to emit and where to emit it if the string
974     ///                provided needs to be padded
975     /// * precision - the maximum length to emit, the string is truncated if it
976     ///               is longer than this length
977     ///
978     /// Notably this function ignored the `flag` parameters
979     #[stable(feature = "rust1", since = "1.0.0")]
980     pub fn pad(&mut self, s: &str) -> Result {
981         // Make sure there's a fast path up front
982         if self.width.is_none() && self.precision.is_none() {
983             return self.buf.write_str(s);
984         }
985         // The `precision` field can be interpreted as a `max-width` for the
986         // string being formatted
987         if let Some(max) = self.precision {
988             // If there's a maximum width and our string is longer than
989             // that, then we must always have truncation. This is the only
990             // case where the maximum length will matter.
991             if let Some((i, _)) = s.char_indices().skip(max).next() {
992                 return self.buf.write_str(&s[..i])
993             }
994         }
995         // The `width` field is more of a `min-width` parameter at this point.
996         match self.width {
997             // If we're under the maximum length, and there's no minimum length
998             // requirements, then we can just emit the string
999             None => self.buf.write_str(s),
1000             // If we're under the maximum width, check if we're over the minimum
1001             // width, if so it's as easy as just emitting the string.
1002             Some(width) if s.chars().count() >= width => {
1003                 self.buf.write_str(s)
1004             }
1005             // If we're under both the maximum and the minimum width, then fill
1006             // up the minimum width with the specified string + some alignment.
1007             Some(width) => {
1008                 let align = rt::v1::Alignment::Left;
1009                 self.with_padding(width - s.chars().count(), align, |me| {
1010                     me.buf.write_str(s)
1011                 })
1012             }
1013         }
1014     }
1015
1016     /// Runs a callback, emitting the correct padding either before or
1017     /// afterwards depending on whether right or left alignment is requested.
1018     fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1019                        f: F) -> Result
1020         where F: FnOnce(&mut Formatter) -> Result,
1021     {
1022         use char::CharExt;
1023         let align = match self.align {
1024             rt::v1::Alignment::Unknown => default,
1025             _ => self.align
1026         };
1027
1028         let (pre_pad, post_pad) = match align {
1029             rt::v1::Alignment::Left => (0, padding),
1030             rt::v1::Alignment::Right |
1031             rt::v1::Alignment::Unknown => (padding, 0),
1032             rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1033         };
1034
1035         let fill = self.fill.encode_utf8();
1036         let fill = unsafe {
1037             str::from_utf8_unchecked(fill.as_slice())
1038         };
1039
1040         for _ in 0..pre_pad {
1041             self.buf.write_str(fill)?;
1042         }
1043
1044         f(self)?;
1045
1046         for _ in 0..post_pad {
1047             self.buf.write_str(fill)?;
1048         }
1049
1050         Ok(())
1051     }
1052
1053     /// Takes the formatted parts and applies the padding.
1054     /// Assumes that the caller already has rendered the parts with required precision,
1055     /// so that `self.precision` can be ignored.
1056     fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1057         if let Some(mut width) = self.width {
1058             // for the sign-aware zero padding, we render the sign first and
1059             // behave as if we had no sign from the beginning.
1060             let mut formatted = formatted.clone();
1061             let mut align = self.align;
1062             let old_fill = self.fill;
1063             if self.sign_aware_zero_pad() {
1064                 // a sign always goes first
1065                 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1066                 self.buf.write_str(sign)?;
1067
1068                 // remove the sign from the formatted parts
1069                 formatted.sign = b"";
1070                 width = if width < sign.len() { 0 } else { width - sign.len() };
1071                 align = rt::v1::Alignment::Right;
1072                 self.fill = '0';
1073             }
1074
1075             // remaining parts go through the ordinary padding process.
1076             let len = formatted.len();
1077             let ret = if width <= len { // no padding
1078                 self.write_formatted_parts(&formatted)
1079             } else {
1080                 self.with_padding(width - len, align, |f| {
1081                     f.write_formatted_parts(&formatted)
1082                 })
1083             };
1084             self.fill = old_fill;
1085             ret
1086         } else {
1087             // this is the common case and we take a shortcut
1088             self.write_formatted_parts(formatted)
1089         }
1090     }
1091
1092     fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1093         fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1094             buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1095         }
1096
1097         if !formatted.sign.is_empty() {
1098             write_bytes(self.buf, formatted.sign)?;
1099         }
1100         for part in formatted.parts {
1101             match *part {
1102                 flt2dec::Part::Zero(mut nzeroes) => {
1103                     const ZEROES: &'static str = // 64 zeroes
1104                         "0000000000000000000000000000000000000000000000000000000000000000";
1105                     while nzeroes > ZEROES.len() {
1106                         self.buf.write_str(ZEROES)?;
1107                         nzeroes -= ZEROES.len();
1108                     }
1109                     if nzeroes > 0 {
1110                         self.buf.write_str(&ZEROES[..nzeroes])?;
1111                     }
1112                 }
1113                 flt2dec::Part::Num(mut v) => {
1114                     let mut s = [0; 5];
1115                     let len = part.len();
1116                     for c in s[..len].iter_mut().rev() {
1117                         *c = b'0' + (v % 10) as u8;
1118                         v /= 10;
1119                     }
1120                     write_bytes(self.buf, &s[..len])?;
1121                 }
1122                 flt2dec::Part::Copy(buf) => {
1123                     write_bytes(self.buf, buf)?;
1124                 }
1125             }
1126         }
1127         Ok(())
1128     }
1129
1130     /// Writes some data to the underlying buffer contained within this
1131     /// formatter.
1132     #[stable(feature = "rust1", since = "1.0.0")]
1133     pub fn write_str(&mut self, data: &str) -> Result {
1134         self.buf.write_str(data)
1135     }
1136
1137     /// Writes some formatted information into this instance
1138     #[stable(feature = "rust1", since = "1.0.0")]
1139     pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1140         write(self.buf, fmt)
1141     }
1142
1143     /// Flags for formatting (packed version of rt::Flag)
1144     #[stable(feature = "rust1", since = "1.0.0")]
1145     pub fn flags(&self) -> u32 { self.flags }
1146
1147     /// Character used as 'fill' whenever there is alignment
1148     #[stable(feature = "fmt_flags", since = "1.5.0")]
1149     pub fn fill(&self) -> char { self.fill }
1150
1151     /// Flag indicating what form of alignment was requested
1152     #[unstable(feature = "fmt_flags_align", reason = "method was just created",
1153                issue = "27726")]
1154     pub fn align(&self) -> Alignment {
1155         match self.align {
1156             rt::v1::Alignment::Left => Alignment::Left,
1157             rt::v1::Alignment::Right => Alignment::Right,
1158             rt::v1::Alignment::Center => Alignment::Center,
1159             rt::v1::Alignment::Unknown => Alignment::Unknown,
1160         }
1161     }
1162
1163     /// Optionally specified integer width that the output should be
1164     #[stable(feature = "fmt_flags", since = "1.5.0")]
1165     pub fn width(&self) -> Option<usize> { self.width }
1166
1167     /// Optionally specified precision for numeric types
1168     #[stable(feature = "fmt_flags", since = "1.5.0")]
1169     pub fn precision(&self) -> Option<usize> { self.precision }
1170
1171     /// Determines if the `+` flag was specified.
1172     #[stable(feature = "fmt_flags", since = "1.5.0")]
1173     pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1174
1175     /// Determines if the `-` flag was specified.
1176     #[stable(feature = "fmt_flags", since = "1.5.0")]
1177     pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1178
1179     /// Determines if the `#` flag was specified.
1180     #[stable(feature = "fmt_flags", since = "1.5.0")]
1181     pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1182
1183     /// Determines if the `0` flag was specified.
1184     #[stable(feature = "fmt_flags", since = "1.5.0")]
1185     pub fn sign_aware_zero_pad(&self) -> bool {
1186         self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1187     }
1188
1189     /// Creates a `DebugStruct` builder designed to assist with creation of
1190     /// `fmt::Debug` implementations for structs.
1191     ///
1192     /// # Examples
1193     ///
1194     /// ```rust
1195     /// use std::fmt;
1196     ///
1197     /// struct Foo {
1198     ///     bar: i32,
1199     ///     baz: String,
1200     /// }
1201     ///
1202     /// impl fmt::Debug for Foo {
1203     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1204     ///         fmt.debug_struct("Foo")
1205     ///             .field("bar", &self.bar)
1206     ///             .field("baz", &self.baz)
1207     ///             .finish()
1208     ///     }
1209     /// }
1210     ///
1211     /// // prints "Foo { bar: 10, baz: "Hello World" }"
1212     /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1213     /// ```
1214     #[stable(feature = "debug_builders", since = "1.2.0")]
1215     #[inline]
1216     pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1217         builders::debug_struct_new(self, name)
1218     }
1219
1220     /// Creates a `DebugTuple` builder designed to assist with creation of
1221     /// `fmt::Debug` implementations for tuple structs.
1222     ///
1223     /// # Examples
1224     ///
1225     /// ```rust
1226     /// use std::fmt;
1227     ///
1228     /// struct Foo(i32, String);
1229     ///
1230     /// impl fmt::Debug for Foo {
1231     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1232     ///         fmt.debug_tuple("Foo")
1233     ///             .field(&self.0)
1234     ///             .field(&self.1)
1235     ///             .finish()
1236     ///     }
1237     /// }
1238     ///
1239     /// // prints "Foo(10, "Hello World")"
1240     /// println!("{:?}", Foo(10, "Hello World".to_string()));
1241     /// ```
1242     #[stable(feature = "debug_builders", since = "1.2.0")]
1243     #[inline]
1244     pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1245         builders::debug_tuple_new(self, name)
1246     }
1247
1248     /// Creates a `DebugList` builder designed to assist with creation of
1249     /// `fmt::Debug` implementations for list-like structures.
1250     ///
1251     /// # Examples
1252     ///
1253     /// ```rust
1254     /// use std::fmt;
1255     ///
1256     /// struct Foo(Vec<i32>);
1257     ///
1258     /// impl fmt::Debug for Foo {
1259     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1260     ///         fmt.debug_list().entries(self.0.iter()).finish()
1261     ///     }
1262     /// }
1263     ///
1264     /// // prints "[10, 11]"
1265     /// println!("{:?}", Foo(vec![10, 11]));
1266     /// ```
1267     #[stable(feature = "debug_builders", since = "1.2.0")]
1268     #[inline]
1269     pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1270         builders::debug_list_new(self)
1271     }
1272
1273     /// Creates a `DebugSet` builder designed to assist with creation of
1274     /// `fmt::Debug` implementations for set-like structures.
1275     ///
1276     /// # Examples
1277     ///
1278     /// ```rust
1279     /// use std::fmt;
1280     ///
1281     /// struct Foo(Vec<i32>);
1282     ///
1283     /// impl fmt::Debug for Foo {
1284     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1285     ///         fmt.debug_set().entries(self.0.iter()).finish()
1286     ///     }
1287     /// }
1288     ///
1289     /// // prints "{10, 11}"
1290     /// println!("{:?}", Foo(vec![10, 11]));
1291     /// ```
1292     #[stable(feature = "debug_builders", since = "1.2.0")]
1293     #[inline]
1294     pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1295         builders::debug_set_new(self)
1296     }
1297
1298     /// Creates a `DebugMap` builder designed to assist with creation of
1299     /// `fmt::Debug` implementations for map-like structures.
1300     ///
1301     /// # Examples
1302     ///
1303     /// ```rust
1304     /// use std::fmt;
1305     ///
1306     /// struct Foo(Vec<(String, i32)>);
1307     ///
1308     /// impl fmt::Debug for Foo {
1309     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1310     ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1311     ///     }
1312     /// }
1313     ///
1314     /// // prints "{"A": 10, "B": 11}"
1315     /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1316     /// ```
1317     #[stable(feature = "debug_builders", since = "1.2.0")]
1318     #[inline]
1319     pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1320         builders::debug_map_new(self)
1321     }
1322 }
1323
1324 #[stable(since = "1.2.0", feature = "formatter_write")]
1325 impl<'a> Write for Formatter<'a> {
1326     fn write_str(&mut self, s: &str) -> Result {
1327         self.buf.write_str(s)
1328     }
1329
1330     fn write_char(&mut self, c: char) -> Result {
1331         self.buf.write_char(c)
1332     }
1333
1334     fn write_fmt(&mut self, args: Arguments) -> Result {
1335         write(self.buf, args)
1336     }
1337 }
1338
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl Display for Error {
1341     fn fmt(&self, f: &mut Formatter) -> Result {
1342         Display::fmt("an error occurred when formatting an argument", f)
1343     }
1344 }
1345
1346 // Implementations of the core formatting traits
1347
1348 macro_rules! fmt_refs {
1349     ($($tr:ident),*) => {
1350         $(
1351         #[stable(feature = "rust1", since = "1.0.0")]
1352         impl<'a, T: ?Sized + $tr> $tr for &'a T {
1353             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1354         }
1355         #[stable(feature = "rust1", since = "1.0.0")]
1356         impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1357             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1358         }
1359         )*
1360     }
1361 }
1362
1363 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1364
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl Debug for bool {
1367     fn fmt(&self, f: &mut Formatter) -> Result {
1368         Display::fmt(self, f)
1369     }
1370 }
1371
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl Display for bool {
1374     fn fmt(&self, f: &mut Formatter) -> Result {
1375         Display::fmt(if *self { "true" } else { "false" }, f)
1376     }
1377 }
1378
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl Debug for str {
1381     fn fmt(&self, f: &mut Formatter) -> Result {
1382         f.write_char('"')?;
1383         let mut from = 0;
1384         for (i, c) in self.char_indices() {
1385             let esc = c.escape_default();
1386             // If char needs escaping, flush backlog so far and write, else skip
1387             if esc.size_hint() != (1, Some(1)) {
1388                 f.write_str(&self[from..i])?;
1389                 for c in esc {
1390                     f.write_char(c)?;
1391                 }
1392                 from = i + c.len_utf8();
1393             }
1394         }
1395         f.write_str(&self[from..])?;
1396         f.write_char('"')
1397     }
1398 }
1399
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl Display for str {
1402     fn fmt(&self, f: &mut Formatter) -> Result {
1403         f.pad(self)
1404     }
1405 }
1406
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 impl Debug for char {
1409     fn fmt(&self, f: &mut Formatter) -> Result {
1410         f.write_char('\'')?;
1411         for c in self.escape_default() {
1412             f.write_char(c)?
1413         }
1414         f.write_char('\'')
1415     }
1416 }
1417
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 impl Display for char {
1420     fn fmt(&self, f: &mut Formatter) -> Result {
1421         if f.width.is_none() && f.precision.is_none() {
1422             f.write_char(*self)
1423         } else {
1424             f.pad(unsafe {
1425                 str::from_utf8_unchecked(self.encode_utf8().as_slice())
1426             })
1427         }
1428     }
1429 }
1430
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 impl<T: ?Sized> Pointer for *const T {
1433     fn fmt(&self, f: &mut Formatter) -> Result {
1434         let old_width = f.width;
1435         let old_flags = f.flags;
1436
1437         // The alternate flag is already treated by LowerHex as being special-
1438         // it denotes whether to prefix with 0x. We use it to work out whether
1439         // or not to zero extend, and then unconditionally set it to get the
1440         // prefix.
1441         if f.alternate() {
1442             f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1443
1444             if let None = f.width {
1445                 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
1446             }
1447         }
1448         f.flags |= 1 << (FlagV1::Alternate as u32);
1449
1450         let ret = LowerHex::fmt(&(*self as *const () as usize), f);
1451
1452         f.width = old_width;
1453         f.flags = old_flags;
1454
1455         ret
1456     }
1457 }
1458
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 impl<T: ?Sized> Pointer for *mut T {
1461     fn fmt(&self, f: &mut Formatter) -> Result {
1462         Pointer::fmt(&(*self as *const T), f)
1463     }
1464 }
1465
1466 #[stable(feature = "rust1", since = "1.0.0")]
1467 impl<'a, T: ?Sized> Pointer for &'a T {
1468     fn fmt(&self, f: &mut Formatter) -> Result {
1469         Pointer::fmt(&(*self as *const T), f)
1470     }
1471 }
1472
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<'a, T: ?Sized> Pointer for &'a mut T {
1475     fn fmt(&self, f: &mut Formatter) -> Result {
1476         Pointer::fmt(&(&**self as *const T), f)
1477     }
1478 }
1479
1480 // Common code of floating point Debug and Display.
1481 fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
1482     where T: flt2dec::DecodableFloat
1483 {
1484     let force_sign = fmt.sign_plus();
1485     let sign = match (force_sign, negative_zero) {
1486         (false, false) => flt2dec::Sign::Minus,
1487         (false, true)  => flt2dec::Sign::MinusRaw,
1488         (true,  false) => flt2dec::Sign::MinusPlus,
1489         (true,  true)  => flt2dec::Sign::MinusPlusRaw,
1490     };
1491
1492     let mut buf = [0; 1024]; // enough for f32 and f64
1493     let mut parts = [flt2dec::Part::Zero(0); 16];
1494     let formatted = if let Some(precision) = fmt.precision {
1495         flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1496                                     precision, false, &mut buf, &mut parts)
1497     } else {
1498         flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1499                                  0, false, &mut buf, &mut parts)
1500     };
1501     fmt.pad_formatted_parts(&formatted)
1502 }
1503
1504 // Common code of floating point LowerExp and UpperExp.
1505 fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
1506     where T: flt2dec::DecodableFloat
1507 {
1508     let force_sign = fmt.sign_plus();
1509     let sign = match force_sign {
1510         false => flt2dec::Sign::Minus,
1511         true  => flt2dec::Sign::MinusPlus,
1512     };
1513
1514     let mut buf = [0; 1024]; // enough for f32 and f64
1515     let mut parts = [flt2dec::Part::Zero(0); 16];
1516     let formatted = if let Some(precision) = fmt.precision {
1517         // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1518         flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1519                                   precision + 1, upper, &mut buf, &mut parts)
1520     } else {
1521         flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1522                                      (0, 0), upper, &mut buf, &mut parts)
1523     };
1524     fmt.pad_formatted_parts(&formatted)
1525 }
1526
1527 macro_rules! floating { ($ty:ident) => {
1528
1529     #[stable(feature = "rust1", since = "1.0.0")]
1530     impl Debug for $ty {
1531         fn fmt(&self, fmt: &mut Formatter) -> Result {
1532             float_to_decimal_common(fmt, self, true)
1533         }
1534     }
1535
1536     #[stable(feature = "rust1", since = "1.0.0")]
1537     impl Display for $ty {
1538         fn fmt(&self, fmt: &mut Formatter) -> Result {
1539             float_to_decimal_common(fmt, self, false)
1540         }
1541     }
1542
1543     #[stable(feature = "rust1", since = "1.0.0")]
1544     impl LowerExp for $ty {
1545         fn fmt(&self, fmt: &mut Formatter) -> Result {
1546             float_to_exponential_common(fmt, self, false)
1547         }
1548     }
1549
1550     #[stable(feature = "rust1", since = "1.0.0")]
1551     impl UpperExp for $ty {
1552         fn fmt(&self, fmt: &mut Formatter) -> Result {
1553             float_to_exponential_common(fmt, self, true)
1554         }
1555     }
1556 } }
1557 floating! { f32 }
1558 floating! { f64 }
1559
1560 // Implementation of Display/Debug for various core types
1561
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl<T> Debug for *const T {
1564     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1565 }
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 impl<T> Debug for *mut T {
1568     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1569 }
1570
1571 macro_rules! peel {
1572     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1573 }
1574
1575 macro_rules! tuple {
1576     () => ();
1577     ( $($name:ident,)+ ) => (
1578         #[stable(feature = "rust1", since = "1.0.0")]
1579         impl<$($name:Debug),*> Debug for ($($name,)*) {
1580             #[allow(non_snake_case, unused_assignments, deprecated)]
1581             fn fmt(&self, f: &mut Formatter) -> Result {
1582                 let mut builder = f.debug_tuple("");
1583                 let ($(ref $name,)*) = *self;
1584                 $(
1585                     builder.field($name);
1586                 )*
1587
1588                 builder.finish()
1589             }
1590         }
1591         peel! { $($name,)* }
1592     )
1593 }
1594
1595 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1596
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl<T: Debug> Debug for [T] {
1599     fn fmt(&self, f: &mut Formatter) -> Result {
1600         f.debug_list().entries(self.iter()).finish()
1601     }
1602 }
1603
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl Debug for () {
1606     fn fmt(&self, f: &mut Formatter) -> Result {
1607         f.pad("()")
1608     }
1609 }
1610 #[stable(feature = "rust1", since = "1.0.0")]
1611 impl<T: ?Sized> Debug for PhantomData<T> {
1612     fn fmt(&self, f: &mut Formatter) -> Result {
1613         f.pad("PhantomData")
1614     }
1615 }
1616
1617 #[stable(feature = "rust1", since = "1.0.0")]
1618 impl<T: Copy + Debug> Debug for Cell<T> {
1619     fn fmt(&self, f: &mut Formatter) -> Result {
1620         f.debug_struct("Cell")
1621             .field("value", &self.get())
1622             .finish()
1623     }
1624 }
1625
1626 #[stable(feature = "rust1", since = "1.0.0")]
1627 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1628     fn fmt(&self, f: &mut Formatter) -> Result {
1629         match self.borrow_state() {
1630             BorrowState::Unused | BorrowState::Reading => {
1631                 f.debug_struct("RefCell")
1632                     .field("value", &self.borrow())
1633                     .finish()
1634             }
1635             BorrowState::Writing => {
1636                 f.debug_struct("RefCell")
1637                     .field("value", &"<borrowed>")
1638                     .finish()
1639             }
1640         }
1641     }
1642 }
1643
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1646     fn fmt(&self, f: &mut Formatter) -> Result {
1647         Debug::fmt(&**self, f)
1648     }
1649 }
1650
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1653     fn fmt(&self, f: &mut Formatter) -> Result {
1654         Debug::fmt(&*(self.deref()), f)
1655     }
1656 }
1657
1658 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1659 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
1660     fn fmt(&self, f: &mut Formatter) -> Result {
1661         f.pad("UnsafeCell")
1662     }
1663 }
1664
1665 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1666 // it's a lot easier than creating all of the rt::Piece structures here.