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