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