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