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