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