]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/mod.rs
reduce list to functions callable in const ctx.
[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     message="`{Self}` doesn't implement `{Display}`",
613     label="`{Self}` cannot be formatted with the default formatter",
614     note="in format strings you may be able to use `{{:?}}` \
615           (or {{:#?}} for pretty-print) instead",
616 )]
617 #[doc(alias = "{}")]
618 #[stable(feature = "rust1", since = "1.0.0")]
619 pub trait Display {
620     /// Formats the value using the given formatter.
621     ///
622     /// # Examples
623     ///
624     /// ```
625     /// use std::fmt;
626     ///
627     /// struct Position {
628     ///     longitude: f32,
629     ///     latitude: f32,
630     /// }
631     ///
632     /// impl fmt::Display for Position {
633     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
634     ///         write!(f, "({}, {})", self.longitude, self.latitude)
635     ///     }
636     /// }
637     ///
638     /// assert_eq!("(1.987, 2.983)".to_owned(),
639     ///            format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
640     /// ```
641     #[stable(feature = "rust1", since = "1.0.0")]
642     fn fmt(&self, f: &mut Formatter) -> Result;
643 }
644
645 /// `o` formatting.
646 ///
647 /// The `Octal` trait should format its output as a number in base-8.
648 ///
649 /// For primitive signed integers (`i8` to `i128`, and `isize`),
650 /// negative values are formatted as the two’s complement representation.
651 ///
652 /// The alternate flag, `#`, adds a `0o` in front of the output.
653 ///
654 /// For more information on formatters, see [the module-level documentation][module].
655 ///
656 /// [module]: ../../std/fmt/index.html
657 ///
658 /// # Examples
659 ///
660 /// Basic usage with `i32`:
661 ///
662 /// ```
663 /// let x = 42; // 42 is '52' in octal
664 ///
665 /// assert_eq!(format!("{:o}", x), "52");
666 /// assert_eq!(format!("{:#o}", x), "0o52");
667 ///
668 /// assert_eq!(format!("{:o}", -16), "37777777760");
669 /// ```
670 ///
671 /// Implementing `Octal` on a type:
672 ///
673 /// ```
674 /// use std::fmt;
675 ///
676 /// struct Length(i32);
677 ///
678 /// impl fmt::Octal for Length {
679 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
680 ///         let val = self.0;
681 ///
682 ///         write!(f, "{:o}", val) // delegate to i32's implementation
683 ///     }
684 /// }
685 ///
686 /// let l = Length(9);
687 ///
688 /// println!("l as octal is: {:o}", l);
689 /// ```
690 #[stable(feature = "rust1", since = "1.0.0")]
691 pub trait Octal {
692     /// Formats the value using the given formatter.
693     #[stable(feature = "rust1", since = "1.0.0")]
694     fn fmt(&self, f: &mut Formatter) -> Result;
695 }
696
697 /// `b` formatting.
698 ///
699 /// The `Binary` trait should format its output as a number in binary.
700 ///
701 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
702 /// negative values are formatted as the two’s complement representation.
703 ///
704 /// The alternate flag, `#`, adds a `0b` in front of the output.
705 ///
706 /// For more information on formatters, see [the module-level documentation][module].
707 ///
708 /// # Examples
709 ///
710 /// Basic usage with [`i32`]:
711 ///
712 /// ```
713 /// let x = 42; // 42 is '101010' in binary
714 ///
715 /// assert_eq!(format!("{:b}", x), "101010");
716 /// assert_eq!(format!("{:#b}", x), "0b101010");
717 ///
718 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
719 /// ```
720 ///
721 /// Implementing `Binary` on a type:
722 ///
723 /// ```
724 /// use std::fmt;
725 ///
726 /// struct Length(i32);
727 ///
728 /// impl fmt::Binary for Length {
729 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
730 ///         let val = self.0;
731 ///
732 ///         write!(f, "{:b}", val) // delegate to i32's implementation
733 ///     }
734 /// }
735 ///
736 /// let l = Length(107);
737 ///
738 /// println!("l as binary is: {:b}", l);
739 /// ```
740 ///
741 /// [module]: ../../std/fmt/index.html
742 /// [`i8`]: ../../std/primitive.i8.html
743 /// [`i128`]: ../../std/primitive.i128.html
744 /// [`isize`]: ../../std/primitive.isize.html
745 /// [`i32`]: ../../std/primitive.i32.html
746 #[stable(feature = "rust1", since = "1.0.0")]
747 pub trait Binary {
748     /// Formats the value using the given formatter.
749     #[stable(feature = "rust1", since = "1.0.0")]
750     fn fmt(&self, f: &mut Formatter) -> Result;
751 }
752
753 /// `x` formatting.
754 ///
755 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
756 /// in lower case.
757 ///
758 /// For primitive signed integers (`i8` to `i128`, and `isize`),
759 /// negative values are formatted as the two’s complement representation.
760 ///
761 /// The alternate flag, `#`, adds a `0x` in front of the output.
762 ///
763 /// For more information on formatters, see [the module-level documentation][module].
764 ///
765 /// [module]: ../../std/fmt/index.html
766 ///
767 /// # Examples
768 ///
769 /// Basic usage with `i32`:
770 ///
771 /// ```
772 /// let x = 42; // 42 is '2a' in hex
773 ///
774 /// assert_eq!(format!("{:x}", x), "2a");
775 /// assert_eq!(format!("{:#x}", x), "0x2a");
776 ///
777 /// assert_eq!(format!("{:x}", -16), "fffffff0");
778 /// ```
779 ///
780 /// Implementing `LowerHex` on a type:
781 ///
782 /// ```
783 /// use std::fmt;
784 ///
785 /// struct Length(i32);
786 ///
787 /// impl fmt::LowerHex for Length {
788 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
789 ///         let val = self.0;
790 ///
791 ///         write!(f, "{:x}", val) // delegate to i32's implementation
792 ///     }
793 /// }
794 ///
795 /// let l = Length(9);
796 ///
797 /// println!("l as hex is: {:x}", l);
798 /// ```
799 #[stable(feature = "rust1", since = "1.0.0")]
800 pub trait LowerHex {
801     /// Formats the value using the given formatter.
802     #[stable(feature = "rust1", since = "1.0.0")]
803     fn fmt(&self, f: &mut Formatter) -> Result;
804 }
805
806 /// `X` formatting.
807 ///
808 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
809 /// in upper case.
810 ///
811 /// For primitive signed integers (`i8` to `i128`, and `isize`),
812 /// negative values are formatted as the two’s complement representation.
813 ///
814 /// The alternate flag, `#`, adds a `0x` in front of the output.
815 ///
816 /// For more information on formatters, see [the module-level documentation][module].
817 ///
818 /// [module]: ../../std/fmt/index.html
819 ///
820 /// # Examples
821 ///
822 /// Basic usage with `i32`:
823 ///
824 /// ```
825 /// let x = 42; // 42 is '2A' in hex
826 ///
827 /// assert_eq!(format!("{:X}", x), "2A");
828 /// assert_eq!(format!("{:#X}", x), "0x2A");
829 ///
830 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
831 /// ```
832 ///
833 /// Implementing `UpperHex` on a type:
834 ///
835 /// ```
836 /// use std::fmt;
837 ///
838 /// struct Length(i32);
839 ///
840 /// impl fmt::UpperHex for Length {
841 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
842 ///         let val = self.0;
843 ///
844 ///         write!(f, "{:X}", val) // delegate to i32's implementation
845 ///     }
846 /// }
847 ///
848 /// let l = Length(9);
849 ///
850 /// println!("l as hex is: {:X}", l);
851 /// ```
852 #[stable(feature = "rust1", since = "1.0.0")]
853 pub trait UpperHex {
854     /// Formats the value using the given formatter.
855     #[stable(feature = "rust1", since = "1.0.0")]
856     fn fmt(&self, f: &mut Formatter) -> Result;
857 }
858
859 /// `p` formatting.
860 ///
861 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
862 /// as hexadecimal.
863 ///
864 /// For more information on formatters, see [the module-level documentation][module].
865 ///
866 /// [module]: ../../std/fmt/index.html
867 ///
868 /// # Examples
869 ///
870 /// Basic usage with `&i32`:
871 ///
872 /// ```
873 /// let x = &42;
874 ///
875 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
876 /// ```
877 ///
878 /// Implementing `Pointer` on a type:
879 ///
880 /// ```
881 /// use std::fmt;
882 ///
883 /// struct Length(i32);
884 ///
885 /// impl fmt::Pointer for Length {
886 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
887 ///         // use `as` to convert to a `*const T`, which implements Pointer, which we can use
888 ///
889 ///         write!(f, "{:p}", self as *const Length)
890 ///     }
891 /// }
892 ///
893 /// let l = Length(42);
894 ///
895 /// println!("l is in memory here: {:p}", l);
896 /// ```
897 #[stable(feature = "rust1", since = "1.0.0")]
898 pub trait Pointer {
899     /// Formats the value using the given formatter.
900     #[stable(feature = "rust1", since = "1.0.0")]
901     fn fmt(&self, f: &mut Formatter) -> Result;
902 }
903
904 /// `e` formatting.
905 ///
906 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
907 ///
908 /// For more information on formatters, see [the module-level documentation][module].
909 ///
910 /// [module]: ../../std/fmt/index.html
911 ///
912 /// # Examples
913 ///
914 /// Basic usage with `i32`:
915 ///
916 /// ```
917 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
918 ///
919 /// assert_eq!(format!("{:e}", x), "4.2e1");
920 /// ```
921 ///
922 /// Implementing `LowerExp` on a type:
923 ///
924 /// ```
925 /// use std::fmt;
926 ///
927 /// struct Length(i32);
928 ///
929 /// impl fmt::LowerExp for Length {
930 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
931 ///         let val = self.0;
932 ///         write!(f, "{}e1", val / 10)
933 ///     }
934 /// }
935 ///
936 /// let l = Length(100);
937 ///
938 /// println!("l in scientific notation is: {:e}", l);
939 /// ```
940 #[stable(feature = "rust1", since = "1.0.0")]
941 pub trait LowerExp {
942     /// Formats the value using the given formatter.
943     #[stable(feature = "rust1", since = "1.0.0")]
944     fn fmt(&self, f: &mut Formatter) -> Result;
945 }
946
947 /// `E` formatting.
948 ///
949 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
950 ///
951 /// For more information on formatters, see [the module-level documentation][module].
952 ///
953 /// [module]: ../../std/fmt/index.html
954 ///
955 /// # Examples
956 ///
957 /// Basic usage with `f32`:
958 ///
959 /// ```
960 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
961 ///
962 /// assert_eq!(format!("{:E}", x), "4.2E1");
963 /// ```
964 ///
965 /// Implementing `UpperExp` on a type:
966 ///
967 /// ```
968 /// use std::fmt;
969 ///
970 /// struct Length(i32);
971 ///
972 /// impl fmt::UpperExp for Length {
973 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
974 ///         let val = self.0;
975 ///         write!(f, "{}E1", val / 10)
976 ///     }
977 /// }
978 ///
979 /// let l = Length(100);
980 ///
981 /// println!("l in scientific notation is: {:E}", l);
982 /// ```
983 #[stable(feature = "rust1", since = "1.0.0")]
984 pub trait UpperExp {
985     /// Formats the value using the given formatter.
986     #[stable(feature = "rust1", since = "1.0.0")]
987     fn fmt(&self, f: &mut Formatter) -> Result;
988 }
989
990 /// The `write` function takes an output stream, and an `Arguments` struct
991 /// that can be precompiled with the `format_args!` macro.
992 ///
993 /// The arguments will be formatted according to the specified format string
994 /// into the output stream provided.
995 ///
996 /// # Examples
997 ///
998 /// Basic usage:
999 ///
1000 /// ```
1001 /// use std::fmt;
1002 ///
1003 /// let mut output = String::new();
1004 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1005 ///     .expect("Error occurred while trying to write in String");
1006 /// assert_eq!(output, "Hello world!");
1007 /// ```
1008 ///
1009 /// Please note that using [`write!`] might be preferable. Example:
1010 ///
1011 /// ```
1012 /// use std::fmt::Write;
1013 ///
1014 /// let mut output = String::new();
1015 /// write!(&mut output, "Hello {}!", "world")
1016 ///     .expect("Error occurred while trying to write in String");
1017 /// assert_eq!(output, "Hello world!");
1018 /// ```
1019 ///
1020 /// [`write!`]: ../../std/macro.write.html
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub fn write(output: &mut dyn Write, args: Arguments) -> Result {
1023     let mut formatter = Formatter {
1024         flags: 0,
1025         width: None,
1026         precision: None,
1027         buf: output,
1028         align: rt::v1::Alignment::Unknown,
1029         fill: ' ',
1030         args: args.args,
1031         curarg: args.args.iter(),
1032     };
1033
1034     let mut pieces = args.pieces.iter();
1035
1036     match args.fmt {
1037         None => {
1038             // We can use default formatting parameters for all arguments.
1039             for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
1040                 formatter.buf.write_str(*piece)?;
1041                 (arg.formatter)(arg.value, &mut formatter)?;
1042             }
1043         }
1044         Some(fmt) => {
1045             // Every spec has a corresponding argument that is preceded by
1046             // a string piece.
1047             for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
1048                 formatter.buf.write_str(*piece)?;
1049                 formatter.run(arg)?;
1050             }
1051         }
1052     }
1053
1054     // There can be only one trailing string piece left.
1055     if let Some(piece) = pieces.next() {
1056         formatter.buf.write_str(*piece)?;
1057     }
1058
1059     Ok(())
1060 }
1061
1062 impl<'a> Formatter<'a> {
1063     fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1064         where 'b: 'c, F: FnOnce(&'b mut (dyn Write+'b)) -> &'c mut (dyn Write+'c)
1065     {
1066         Formatter {
1067             // We want to change this
1068             buf: wrap(self.buf),
1069
1070             // And preserve these
1071             flags: self.flags,
1072             fill: self.fill,
1073             align: self.align,
1074             width: self.width,
1075             precision: self.precision,
1076
1077             // These only exist in the struct for the `run` method,
1078             // which won’t be used together with this method.
1079             curarg: self.curarg.clone(),
1080             args: self.args,
1081         }
1082     }
1083
1084     // First up is the collection of functions used to execute a format string
1085     // at runtime. This consumes all of the compile-time statics generated by
1086     // the format! syntax extension.
1087     fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1088         // Fill in the format parameters into the formatter
1089         self.fill = arg.format.fill;
1090         self.align = arg.format.align;
1091         self.flags = arg.format.flags;
1092         self.width = self.getcount(&arg.format.width);
1093         self.precision = self.getcount(&arg.format.precision);
1094
1095         // Extract the correct argument
1096         let value = match arg.position {
1097             rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1098             rt::v1::Position::At(i) => self.args[i],
1099         };
1100
1101         // Then actually do some printing
1102         (value.formatter)(value.value, self)
1103     }
1104
1105     fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1106         match *cnt {
1107             rt::v1::Count::Is(n) => Some(n),
1108             rt::v1::Count::Implied => None,
1109             rt::v1::Count::Param(i) => {
1110                 self.args[i].as_usize()
1111             }
1112             rt::v1::Count::NextParam => {
1113                 self.curarg.next().and_then(|arg| arg.as_usize())
1114             }
1115         }
1116     }
1117
1118     // Helper methods used for padding and processing formatting arguments that
1119     // all formatting traits can use.
1120
1121     /// Performs the correct padding for an integer which has already been
1122     /// emitted into a str. The str should *not* contain the sign for the
1123     /// integer, that will be added by this method.
1124     ///
1125     /// # Arguments
1126     ///
1127     /// * is_nonnegative - whether the original integer was either positive or zero.
1128     /// * prefix - if the '#' character (Alternate) is provided, this
1129     ///   is the prefix to put in front of the number.
1130     /// * buf - the byte array that the number has been formatted into
1131     ///
1132     /// This function will correctly account for the flags provided as well as
1133     /// the minimum width. It will not take precision into account.
1134     ///
1135     /// # Examples
1136     ///
1137     /// ```
1138     /// use std::fmt;
1139     ///
1140     /// struct Foo { nb: i32 };
1141     ///
1142     /// impl Foo {
1143     ///     fn new(nb: i32) -> Foo {
1144     ///         Foo {
1145     ///             nb,
1146     ///         }
1147     ///     }
1148     /// }
1149     ///
1150     /// impl fmt::Display for Foo {
1151     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1152     ///         // We need to remove "-" from the number output.
1153     ///         let tmp = self.nb.abs().to_string();
1154     ///
1155     ///         formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1156     ///     }
1157     /// }
1158     ///
1159     /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1160     /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1161     /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1162     /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1163     /// ```
1164     #[stable(feature = "rust1", since = "1.0.0")]
1165     pub fn pad_integral(&mut self,
1166                         is_nonnegative: bool,
1167                         prefix: &str,
1168                         buf: &str)
1169                         -> Result {
1170         let mut width = buf.len();
1171
1172         let mut sign = None;
1173         if !is_nonnegative {
1174             sign = Some('-'); width += 1;
1175         } else if self.sign_plus() {
1176             sign = Some('+'); width += 1;
1177         }
1178
1179         let mut prefixed = false;
1180         if self.alternate() {
1181             prefixed = true; width += prefix.chars().count();
1182         }
1183
1184         // Writes the sign if it exists, and then the prefix if it was requested
1185         let write_prefix = |f: &mut Formatter| {
1186             if let Some(c) = sign {
1187                 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
1188             }
1189             if prefixed { f.buf.write_str(prefix) }
1190             else { Ok(()) }
1191         };
1192
1193         // The `width` field is more of a `min-width` parameter at this point.
1194         match self.width {
1195             // If there's no minimum length requirements then we can just
1196             // write the bytes.
1197             None => {
1198                 write_prefix(self)?; self.buf.write_str(buf)
1199             }
1200             // Check if we're over the minimum width, if so then we can also
1201             // just write the bytes.
1202             Some(min) if width >= min => {
1203                 write_prefix(self)?; self.buf.write_str(buf)
1204             }
1205             // The sign and prefix goes before the padding if the fill character
1206             // is zero
1207             Some(min) if self.sign_aware_zero_pad() => {
1208                 self.fill = '0';
1209                 self.align = rt::v1::Alignment::Right;
1210                 write_prefix(self)?;
1211                 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1212                     f.buf.write_str(buf)
1213                 })
1214             }
1215             // Otherwise, the sign and prefix goes after the padding
1216             Some(min) => {
1217                 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1218                     write_prefix(f)?; f.buf.write_str(buf)
1219                 })
1220             }
1221         }
1222     }
1223
1224     /// This function takes a string slice and emits it to the internal buffer
1225     /// after applying the relevant formatting flags specified. The flags
1226     /// recognized for generic strings are:
1227     ///
1228     /// * width - the minimum width of what to emit
1229     /// * fill/align - what to emit and where to emit it if the string
1230     ///                provided needs to be padded
1231     /// * precision - the maximum length to emit, the string is truncated if it
1232     ///               is longer than this length
1233     ///
1234     /// Notably this function ignores the `flag` parameters.
1235     ///
1236     /// # Examples
1237     ///
1238     /// ```
1239     /// use std::fmt;
1240     ///
1241     /// struct Foo;
1242     ///
1243     /// impl fmt::Display for Foo {
1244     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1245     ///         formatter.pad("Foo")
1246     ///     }
1247     /// }
1248     ///
1249     /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1250     /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1251     /// ```
1252     #[stable(feature = "rust1", since = "1.0.0")]
1253     pub fn pad(&mut self, s: &str) -> Result {
1254         // Make sure there's a fast path up front
1255         if self.width.is_none() && self.precision.is_none() {
1256             return self.buf.write_str(s);
1257         }
1258         // The `precision` field can be interpreted as a `max-width` for the
1259         // string being formatted.
1260         let s = if let Some(max) = self.precision {
1261             // If our string is longer that the precision, then we must have
1262             // truncation. However other flags like `fill`, `width` and `align`
1263             // must act as always.
1264             if let Some((i, _)) = s.char_indices().nth(max) {
1265                 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1266                 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1267                 // `unsafe` and otherwise don't emit any panic-related code
1268                 // here.
1269                 s.get(..i).unwrap_or(&s)
1270             } else {
1271                 &s
1272             }
1273         } else {
1274             &s
1275         };
1276         // The `width` field is more of a `min-width` parameter at this point.
1277         match self.width {
1278             // If we're under the maximum length, and there's no minimum length
1279             // requirements, then we can just emit the string
1280             None => self.buf.write_str(s),
1281             // If we're under the maximum width, check if we're over the minimum
1282             // width, if so it's as easy as just emitting the string.
1283             Some(width) if s.chars().count() >= width => {
1284                 self.buf.write_str(s)
1285             }
1286             // If we're under both the maximum and the minimum width, then fill
1287             // up the minimum width with the specified string + some alignment.
1288             Some(width) => {
1289                 let align = rt::v1::Alignment::Left;
1290                 self.with_padding(width - s.chars().count(), align, |me| {
1291                     me.buf.write_str(s)
1292                 })
1293             }
1294         }
1295     }
1296
1297     /// Runs a callback, emitting the correct padding either before or
1298     /// afterwards depending on whether right or left alignment is requested.
1299     fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1300                        f: F) -> Result
1301         where F: FnOnce(&mut Formatter) -> Result,
1302     {
1303         let align = match self.align {
1304             rt::v1::Alignment::Unknown => default,
1305             _ => self.align
1306         };
1307
1308         let (pre_pad, post_pad) = match align {
1309             rt::v1::Alignment::Left => (0, padding),
1310             rt::v1::Alignment::Right |
1311             rt::v1::Alignment::Unknown => (padding, 0),
1312             rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1313         };
1314
1315         let mut fill = [0; 4];
1316         let fill = self.fill.encode_utf8(&mut fill);
1317
1318         for _ in 0..pre_pad {
1319             self.buf.write_str(fill)?;
1320         }
1321
1322         f(self)?;
1323
1324         for _ in 0..post_pad {
1325             self.buf.write_str(fill)?;
1326         }
1327
1328         Ok(())
1329     }
1330
1331     /// Takes the formatted parts and applies the padding.
1332     /// Assumes that the caller already has rendered the parts with required precision,
1333     /// so that `self.precision` can be ignored.
1334     fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1335         if let Some(mut width) = self.width {
1336             // for the sign-aware zero padding, we render the sign first and
1337             // behave as if we had no sign from the beginning.
1338             let mut formatted = formatted.clone();
1339             let old_fill = self.fill;
1340             let old_align = self.align;
1341             let mut align = old_align;
1342             if self.sign_aware_zero_pad() {
1343                 // a sign always goes first
1344                 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1345                 self.buf.write_str(sign)?;
1346
1347                 // remove the sign from the formatted parts
1348                 formatted.sign = b"";
1349                 width = if width < sign.len() { 0 } else { width - sign.len() };
1350                 align = rt::v1::Alignment::Right;
1351                 self.fill = '0';
1352                 self.align = rt::v1::Alignment::Right;
1353             }
1354
1355             // remaining parts go through the ordinary padding process.
1356             let len = formatted.len();
1357             let ret = if width <= len { // no padding
1358                 self.write_formatted_parts(&formatted)
1359             } else {
1360                 self.with_padding(width - len, align, |f| {
1361                     f.write_formatted_parts(&formatted)
1362                 })
1363             };
1364             self.fill = old_fill;
1365             self.align = old_align;
1366             ret
1367         } else {
1368             // this is the common case and we take a shortcut
1369             self.write_formatted_parts(formatted)
1370         }
1371     }
1372
1373     fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1374         fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1375             buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1376         }
1377
1378         if !formatted.sign.is_empty() {
1379             write_bytes(self.buf, formatted.sign)?;
1380         }
1381         for part in formatted.parts {
1382             match *part {
1383                 flt2dec::Part::Zero(mut nzeroes) => {
1384                     const ZEROES: &'static str = // 64 zeroes
1385                         "0000000000000000000000000000000000000000000000000000000000000000";
1386                     while nzeroes > ZEROES.len() {
1387                         self.buf.write_str(ZEROES)?;
1388                         nzeroes -= ZEROES.len();
1389                     }
1390                     if nzeroes > 0 {
1391                         self.buf.write_str(&ZEROES[..nzeroes])?;
1392                     }
1393                 }
1394                 flt2dec::Part::Num(mut v) => {
1395                     let mut s = [0; 5];
1396                     let len = part.len();
1397                     for c in s[..len].iter_mut().rev() {
1398                         *c = b'0' + (v % 10) as u8;
1399                         v /= 10;
1400                     }
1401                     write_bytes(self.buf, &s[..len])?;
1402                 }
1403                 flt2dec::Part::Copy(buf) => {
1404                     write_bytes(self.buf, buf)?;
1405                 }
1406             }
1407         }
1408         Ok(())
1409     }
1410
1411     /// Writes some data to the underlying buffer contained within this
1412     /// formatter.
1413     ///
1414     /// # Examples
1415     ///
1416     /// ```
1417     /// use std::fmt;
1418     ///
1419     /// struct Foo;
1420     ///
1421     /// impl fmt::Display for Foo {
1422     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1423     ///         formatter.write_str("Foo")
1424     ///         // This is equivalent to:
1425     ///         // write!(formatter, "Foo")
1426     ///     }
1427     /// }
1428     ///
1429     /// assert_eq!(&format!("{}", Foo), "Foo");
1430     /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1431     /// ```
1432     #[stable(feature = "rust1", since = "1.0.0")]
1433     pub fn write_str(&mut self, data: &str) -> Result {
1434         self.buf.write_str(data)
1435     }
1436
1437     /// Writes some formatted information into this instance.
1438     ///
1439     /// # Examples
1440     ///
1441     /// ```
1442     /// use std::fmt;
1443     ///
1444     /// struct Foo(i32);
1445     ///
1446     /// impl fmt::Display for Foo {
1447     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1448     ///         formatter.write_fmt(format_args!("Foo {}", self.0))
1449     ///     }
1450     /// }
1451     ///
1452     /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1453     /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1454     /// ```
1455     #[stable(feature = "rust1", since = "1.0.0")]
1456     pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1457         write(self.buf, fmt)
1458     }
1459
1460     /// Flags for formatting
1461     #[stable(feature = "rust1", since = "1.0.0")]
1462     #[rustc_deprecated(since = "1.24.0",
1463                        reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1464                                  or `sign_aware_zero_pad` methods instead")]
1465     pub fn flags(&self) -> u32 { self.flags }
1466
1467     /// Character used as 'fill' whenever there is alignment.
1468     ///
1469     /// # Examples
1470     ///
1471     /// ```
1472     /// use std::fmt;
1473     ///
1474     /// struct Foo;
1475     ///
1476     /// impl fmt::Display for Foo {
1477     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1478     ///         let c = formatter.fill();
1479     ///         if let Some(width) = formatter.width() {
1480     ///             for _ in 0..width {
1481     ///                 write!(formatter, "{}", c)?;
1482     ///             }
1483     ///             Ok(())
1484     ///         } else {
1485     ///             write!(formatter, "{}", c)
1486     ///         }
1487     ///     }
1488     /// }
1489     ///
1490     /// // We set alignment to the left with ">".
1491     /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1492     /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1493     /// ```
1494     #[stable(feature = "fmt_flags", since = "1.5.0")]
1495     pub fn fill(&self) -> char { self.fill }
1496
1497     /// Flag indicating what form of alignment was requested.
1498     ///
1499     /// # Examples
1500     ///
1501     /// ```
1502     /// extern crate core;
1503     ///
1504     /// use std::fmt::{self, Alignment};
1505     ///
1506     /// struct Foo;
1507     ///
1508     /// impl fmt::Display for Foo {
1509     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1510     ///         let s = if let Some(s) = formatter.align() {
1511     ///             match s {
1512     ///                 Alignment::Left    => "left",
1513     ///                 Alignment::Right   => "right",
1514     ///                 Alignment::Center  => "center",
1515     ///             }
1516     ///         } else {
1517     ///             "into the void"
1518     ///         };
1519     ///         write!(formatter, "{}", s)
1520     ///     }
1521     /// }
1522     ///
1523     /// fn main() {
1524     ///     assert_eq!(&format!("{:<}", Foo), "left");
1525     ///     assert_eq!(&format!("{:>}", Foo), "right");
1526     ///     assert_eq!(&format!("{:^}", Foo), "center");
1527     ///     assert_eq!(&format!("{}", Foo), "into the void");
1528     /// }
1529     /// ```
1530     #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1531     pub fn align(&self) -> Option<Alignment> {
1532         match self.align {
1533             rt::v1::Alignment::Left => Some(Alignment::Left),
1534             rt::v1::Alignment::Right => Some(Alignment::Right),
1535             rt::v1::Alignment::Center => Some(Alignment::Center),
1536             rt::v1::Alignment::Unknown => None,
1537         }
1538     }
1539
1540     /// Optionally specified integer width that the output should be.
1541     ///
1542     /// # Examples
1543     ///
1544     /// ```
1545     /// use std::fmt;
1546     ///
1547     /// struct Foo(i32);
1548     ///
1549     /// impl fmt::Display for Foo {
1550     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1551     ///         if let Some(width) = formatter.width() {
1552     ///             // If we received a width, we use it
1553     ///             write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1554     ///         } else {
1555     ///             // Otherwise we do nothing special
1556     ///             write!(formatter, "Foo({})", self.0)
1557     ///         }
1558     ///     }
1559     /// }
1560     ///
1561     /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23)   ");
1562     /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1563     /// ```
1564     #[stable(feature = "fmt_flags", since = "1.5.0")]
1565     pub fn width(&self) -> Option<usize> { self.width }
1566
1567     /// Optionally specified precision for numeric types.
1568     ///
1569     /// # Examples
1570     ///
1571     /// ```
1572     /// use std::fmt;
1573     ///
1574     /// struct Foo(f32);
1575     ///
1576     /// impl fmt::Display for Foo {
1577     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1578     ///         if let Some(precision) = formatter.precision() {
1579     ///             // If we received a precision, we use it.
1580     ///             write!(formatter, "Foo({1:.*})", precision, self.0)
1581     ///         } else {
1582     ///             // Otherwise we default to 2.
1583     ///             write!(formatter, "Foo({:.2})", self.0)
1584     ///         }
1585     ///     }
1586     /// }
1587     ///
1588     /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1589     /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1590     /// ```
1591     #[stable(feature = "fmt_flags", since = "1.5.0")]
1592     pub fn precision(&self) -> Option<usize> { self.precision }
1593
1594     /// Determines if the `+` flag was specified.
1595     ///
1596     /// # Examples
1597     ///
1598     /// ```
1599     /// use std::fmt;
1600     ///
1601     /// struct Foo(i32);
1602     ///
1603     /// impl fmt::Display for Foo {
1604     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1605     ///         if formatter.sign_plus() {
1606     ///             write!(formatter,
1607     ///                    "Foo({}{})",
1608     ///                    if self.0 < 0 { '-' } else { '+' },
1609     ///                    self.0)
1610     ///         } else {
1611     ///             write!(formatter, "Foo({})", self.0)
1612     ///         }
1613     ///     }
1614     /// }
1615     ///
1616     /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1617     /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1618     /// ```
1619     #[stable(feature = "fmt_flags", since = "1.5.0")]
1620     pub fn sign_plus(&self) -> bool {
1621         self.flags & (1 << FlagV1::SignPlus as u32) != 0
1622     }
1623
1624     /// Determines if the `-` flag was specified.
1625     ///
1626     /// # Examples
1627     ///
1628     /// ```
1629     /// use std::fmt;
1630     ///
1631     /// struct Foo(i32);
1632     ///
1633     /// impl fmt::Display for Foo {
1634     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1635     ///         if formatter.sign_minus() {
1636     ///             // You want a minus sign? Have one!
1637     ///             write!(formatter, "-Foo({})", self.0)
1638     ///         } else {
1639     ///             write!(formatter, "Foo({})", self.0)
1640     ///         }
1641     ///     }
1642     /// }
1643     ///
1644     /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1645     /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1646     /// ```
1647     #[stable(feature = "fmt_flags", since = "1.5.0")]
1648     pub fn sign_minus(&self) -> bool {
1649         self.flags & (1 << FlagV1::SignMinus as u32) != 0
1650     }
1651
1652     /// Determines if the `#` flag was specified.
1653     ///
1654     /// # Examples
1655     ///
1656     /// ```
1657     /// use std::fmt;
1658     ///
1659     /// struct Foo(i32);
1660     ///
1661     /// impl fmt::Display for Foo {
1662     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1663     ///         if formatter.alternate() {
1664     ///             write!(formatter, "Foo({})", self.0)
1665     ///         } else {
1666     ///             write!(formatter, "{}", self.0)
1667     ///         }
1668     ///     }
1669     /// }
1670     ///
1671     /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1672     /// assert_eq!(&format!("{}", Foo(23)), "23");
1673     /// ```
1674     #[stable(feature = "fmt_flags", since = "1.5.0")]
1675     pub fn alternate(&self) -> bool {
1676         self.flags & (1 << FlagV1::Alternate as u32) != 0
1677     }
1678
1679     /// Determines if the `0` flag was specified.
1680     ///
1681     /// # Examples
1682     ///
1683     /// ```
1684     /// use std::fmt;
1685     ///
1686     /// struct Foo(i32);
1687     ///
1688     /// impl fmt::Display for Foo {
1689     ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1690     ///         assert!(formatter.sign_aware_zero_pad());
1691     ///         assert_eq!(formatter.width(), Some(4));
1692     ///         // We ignore the formatter's options.
1693     ///         write!(formatter, "{}", self.0)
1694     ///     }
1695     /// }
1696     ///
1697     /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1698     /// ```
1699     #[stable(feature = "fmt_flags", since = "1.5.0")]
1700     pub fn sign_aware_zero_pad(&self) -> bool {
1701         self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1702     }
1703
1704     // FIXME: Decide what public API we want for these two flags.
1705     // https://github.com/rust-lang/rust/issues/48584
1706     const fn debug_lower_hex(&self) -> bool {
1707         self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1708     }
1709
1710     const fn debug_upper_hex(&self) -> bool {
1711         self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1712     }
1713
1714     /// Creates a [`DebugStruct`] builder designed to assist with creation of
1715     /// [`fmt::Debug`] implementations for structs.
1716     ///
1717     /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1718     /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1719     ///
1720     /// # Examples
1721     ///
1722     /// ```rust
1723     /// use std::fmt;
1724     /// use std::net::Ipv4Addr;
1725     ///
1726     /// struct Foo {
1727     ///     bar: i32,
1728     ///     baz: String,
1729     ///     addr: Ipv4Addr,
1730     /// }
1731     ///
1732     /// impl fmt::Debug for Foo {
1733     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1734     ///         fmt.debug_struct("Foo")
1735     ///             .field("bar", &self.bar)
1736     ///             .field("baz", &self.baz)
1737     ///             .field("addr", &format_args!("{}", self.addr))
1738     ///             .finish()
1739     ///     }
1740     /// }
1741     ///
1742     /// assert_eq!(
1743     ///     "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1744     ///     format!("{:?}", Foo {
1745     ///         bar: 10,
1746     ///         baz: "Hello World".to_string(),
1747     ///         addr: Ipv4Addr::new(127, 0, 0, 1),
1748     ///     })
1749     /// );
1750     /// ```
1751     #[stable(feature = "debug_builders", since = "1.2.0")]
1752     pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1753         builders::debug_struct_new(self, name)
1754     }
1755
1756     /// Creates a `DebugTuple` builder designed to assist with creation of
1757     /// `fmt::Debug` implementations for tuple structs.
1758     ///
1759     /// # Examples
1760     ///
1761     /// ```rust
1762     /// use std::fmt;
1763     /// use std::marker::PhantomData;
1764     ///
1765     /// struct Foo<T>(i32, String, PhantomData<T>);
1766     ///
1767     /// impl<T> fmt::Debug for Foo<T> {
1768     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1769     ///         fmt.debug_tuple("Foo")
1770     ///             .field(&self.0)
1771     ///             .field(&self.1)
1772     ///             .field(&format_args!("_"))
1773     ///             .finish()
1774     ///     }
1775     /// }
1776     ///
1777     /// assert_eq!(
1778     ///     "Foo(10, \"Hello\", _)",
1779     ///     format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1780     /// );
1781     /// ```
1782     #[stable(feature = "debug_builders", since = "1.2.0")]
1783     pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1784         builders::debug_tuple_new(self, name)
1785     }
1786
1787     /// Creates a `DebugList` builder designed to assist with creation of
1788     /// `fmt::Debug` implementations for list-like structures.
1789     ///
1790     /// # Examples
1791     ///
1792     /// ```rust
1793     /// use std::fmt;
1794     ///
1795     /// struct Foo(Vec<i32>);
1796     ///
1797     /// impl fmt::Debug for Foo {
1798     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1799     ///         fmt.debug_list().entries(self.0.iter()).finish()
1800     ///     }
1801     /// }
1802     ///
1803     /// // prints "[10, 11]"
1804     /// println!("{:?}", Foo(vec![10, 11]));
1805     /// ```
1806     #[stable(feature = "debug_builders", since = "1.2.0")]
1807     pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1808         builders::debug_list_new(self)
1809     }
1810
1811     /// Creates a `DebugSet` builder designed to assist with creation of
1812     /// `fmt::Debug` implementations for set-like structures.
1813     ///
1814     /// # Examples
1815     ///
1816     /// ```rust
1817     /// use std::fmt;
1818     ///
1819     /// struct Foo(Vec<i32>);
1820     ///
1821     /// impl fmt::Debug for Foo {
1822     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1823     ///         fmt.debug_set().entries(self.0.iter()).finish()
1824     ///     }
1825     /// }
1826     ///
1827     /// // prints "{10, 11}"
1828     /// println!("{:?}", Foo(vec![10, 11]));
1829     /// ```
1830     ///
1831     /// [`format_args!`]: ../../std/macro.format_args.html
1832     ///
1833     /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1834     /// to build a list of match arms:
1835     ///
1836     /// ```rust
1837     /// use std::fmt;
1838     ///
1839     /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1840     /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1841     ///
1842     /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1843     /// where
1844     ///     L: 'a + fmt::Debug, R: 'a + fmt::Debug
1845     /// {
1846     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1847     ///         L::fmt(&(self.0).0, fmt)?;
1848     ///         fmt.write_str(" => ")?;
1849     ///         R::fmt(&(self.0).1, fmt)
1850     ///     }
1851     /// }
1852     ///
1853     /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1854     /// where
1855     ///     K: 'a + fmt::Debug, V: 'a + fmt::Debug
1856     /// {
1857     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1858     ///         fmt.debug_set()
1859     ///         .entries(self.0.iter().map(Arm))
1860     ///         .entry(&Arm(&(format_args!("_"), &self.1)))
1861     ///         .finish()
1862     ///     }
1863     /// }
1864     /// ```
1865     #[stable(feature = "debug_builders", since = "1.2.0")]
1866     pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1867         builders::debug_set_new(self)
1868     }
1869
1870     /// Creates a `DebugMap` builder designed to assist with creation of
1871     /// `fmt::Debug` implementations for map-like structures.
1872     ///
1873     /// # Examples
1874     ///
1875     /// ```rust
1876     /// use std::fmt;
1877     ///
1878     /// struct Foo(Vec<(String, i32)>);
1879     ///
1880     /// impl fmt::Debug for Foo {
1881     ///     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1882     ///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1883     ///     }
1884     /// }
1885     ///
1886     /// // prints "{"A": 10, "B": 11}"
1887     /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1888     /// ```
1889     #[stable(feature = "debug_builders", since = "1.2.0")]
1890     pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1891         builders::debug_map_new(self)
1892     }
1893 }
1894
1895 #[stable(since = "1.2.0", feature = "formatter_write")]
1896 impl Write for Formatter<'_> {
1897     fn write_str(&mut self, s: &str) -> Result {
1898         self.buf.write_str(s)
1899     }
1900
1901     fn write_char(&mut self, c: char) -> Result {
1902         self.buf.write_char(c)
1903     }
1904
1905     fn write_fmt(&mut self, args: Arguments) -> Result {
1906         write(self.buf, args)
1907     }
1908 }
1909
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 impl Display for Error {
1912     fn fmt(&self, f: &mut Formatter) -> Result {
1913         Display::fmt("an error occurred when formatting an argument", f)
1914     }
1915 }
1916
1917 // Implementations of the core formatting traits
1918
1919 macro_rules! fmt_refs {
1920     ($($tr:ident),*) => {
1921         $(
1922         #[stable(feature = "rust1", since = "1.0.0")]
1923         impl<T: ?Sized + $tr> $tr for &T {
1924             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1925         }
1926         #[stable(feature = "rust1", since = "1.0.0")]
1927         impl<T: ?Sized + $tr> $tr for &mut T {
1928             fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1929         }
1930         )*
1931     }
1932 }
1933
1934 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1935
1936 #[unstable(feature = "never_type", issue = "35121")]
1937 impl Debug for ! {
1938     fn fmt(&self, _: &mut Formatter) -> Result {
1939         *self
1940     }
1941 }
1942
1943 #[unstable(feature = "never_type", issue = "35121")]
1944 impl Display for ! {
1945     fn fmt(&self, _: &mut Formatter) -> Result {
1946         *self
1947     }
1948 }
1949
1950 #[stable(feature = "rust1", since = "1.0.0")]
1951 impl Debug for bool {
1952     #[inline]
1953     fn fmt(&self, f: &mut Formatter) -> Result {
1954         Display::fmt(self, f)
1955     }
1956 }
1957
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 impl Display for bool {
1960     fn fmt(&self, f: &mut Formatter) -> Result {
1961         Display::fmt(if *self { "true" } else { "false" }, f)
1962     }
1963 }
1964
1965 #[stable(feature = "rust1", since = "1.0.0")]
1966 impl Debug for str {
1967     fn fmt(&self, f: &mut Formatter) -> Result {
1968         f.write_char('"')?;
1969         let mut from = 0;
1970         for (i, c) in self.char_indices() {
1971             let esc = c.escape_debug();
1972             // If char needs escaping, flush backlog so far and write, else skip
1973             if esc.len() != 1 {
1974                 f.write_str(&self[from..i])?;
1975                 for c in esc {
1976                     f.write_char(c)?;
1977                 }
1978                 from = i + c.len_utf8();
1979             }
1980         }
1981         f.write_str(&self[from..])?;
1982         f.write_char('"')
1983     }
1984 }
1985
1986 #[stable(feature = "rust1", since = "1.0.0")]
1987 impl Display for str {
1988     fn fmt(&self, f: &mut Formatter) -> Result {
1989         f.pad(self)
1990     }
1991 }
1992
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 impl Debug for char {
1995     fn fmt(&self, f: &mut Formatter) -> Result {
1996         f.write_char('\'')?;
1997         for c in self.escape_debug() {
1998             f.write_char(c)?
1999         }
2000         f.write_char('\'')
2001     }
2002 }
2003
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 impl Display for char {
2006     fn fmt(&self, f: &mut Formatter) -> Result {
2007         if f.width.is_none() && f.precision.is_none() {
2008             f.write_char(*self)
2009         } else {
2010             f.pad(self.encode_utf8(&mut [0; 4]))
2011         }
2012     }
2013 }
2014
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 impl<T: ?Sized> Pointer for *const T {
2017     fn fmt(&self, f: &mut Formatter) -> Result {
2018         let old_width = f.width;
2019         let old_flags = f.flags;
2020
2021         // The alternate flag is already treated by LowerHex as being special-
2022         // it denotes whether to prefix with 0x. We use it to work out whether
2023         // or not to zero extend, and then unconditionally set it to get the
2024         // prefix.
2025         if f.alternate() {
2026             f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2027
2028             if let None = f.width {
2029                 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2030             }
2031         }
2032         f.flags |= 1 << (FlagV1::Alternate as u32);
2033
2034         let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2035
2036         f.width = old_width;
2037         f.flags = old_flags;
2038
2039         ret
2040     }
2041 }
2042
2043 #[stable(feature = "rust1", since = "1.0.0")]
2044 impl<T: ?Sized> Pointer for *mut T {
2045     fn fmt(&self, f: &mut Formatter) -> Result {
2046         Pointer::fmt(&(*self as *const T), f)
2047     }
2048 }
2049
2050 #[stable(feature = "rust1", since = "1.0.0")]
2051 impl<T: ?Sized> Pointer for &T {
2052     fn fmt(&self, f: &mut Formatter) -> Result {
2053         Pointer::fmt(&(*self as *const T), f)
2054     }
2055 }
2056
2057 #[stable(feature = "rust1", since = "1.0.0")]
2058 impl<T: ?Sized> Pointer for &mut T {
2059     fn fmt(&self, f: &mut Formatter) -> Result {
2060         Pointer::fmt(&(&**self as *const T), f)
2061     }
2062 }
2063
2064 // Implementation of Display/Debug for various core types
2065
2066 #[stable(feature = "rust1", since = "1.0.0")]
2067 impl<T: ?Sized> Debug for *const T {
2068     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2069 }
2070 #[stable(feature = "rust1", since = "1.0.0")]
2071 impl<T: ?Sized> Debug for *mut T {
2072     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
2073 }
2074
2075 macro_rules! peel {
2076     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2077 }
2078
2079 macro_rules! tuple {
2080     () => ();
2081     ( $($name:ident,)+ ) => (
2082         #[stable(feature = "rust1", since = "1.0.0")]
2083         impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
2084             #[allow(non_snake_case, unused_assignments, deprecated)]
2085             fn fmt(&self, f: &mut Formatter) -> Result {
2086                 let mut builder = f.debug_tuple("");
2087                 let ($(ref $name,)*) = *self;
2088                 $(
2089                     builder.field(&$name);
2090                 )*
2091
2092                 builder.finish()
2093             }
2094         }
2095         peel! { $($name,)* }
2096     )
2097 }
2098
2099 macro_rules! last_type {
2100     ($a:ident,) => { $a };
2101     ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2102 }
2103
2104 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2105
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 impl<T: Debug> Debug for [T] {
2108     fn fmt(&self, f: &mut Formatter) -> Result {
2109         f.debug_list().entries(self.iter()).finish()
2110     }
2111 }
2112
2113 #[stable(feature = "rust1", since = "1.0.0")]
2114 impl Debug for () {
2115     #[inline]
2116     fn fmt(&self, f: &mut Formatter) -> Result {
2117         f.pad("()")
2118     }
2119 }
2120 #[stable(feature = "rust1", since = "1.0.0")]
2121 impl<T: ?Sized> Debug for PhantomData<T> {
2122     fn fmt(&self, f: &mut Formatter) -> Result {
2123         f.pad("PhantomData")
2124     }
2125 }
2126
2127 #[stable(feature = "rust1", since = "1.0.0")]
2128 impl<T: Copy + Debug> Debug for Cell<T> {
2129     fn fmt(&self, f: &mut Formatter) -> Result {
2130         f.debug_struct("Cell")
2131             .field("value", &self.get())
2132             .finish()
2133     }
2134 }
2135
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2138     fn fmt(&self, f: &mut Formatter) -> Result {
2139         match self.try_borrow() {
2140             Ok(borrow) => {
2141                 f.debug_struct("RefCell")
2142                     .field("value", &borrow)
2143                     .finish()
2144             }
2145             Err(_) => {
2146                 // The RefCell is mutably borrowed so we can't look at its value
2147                 // here. Show a placeholder instead.
2148                 struct BorrowedPlaceholder;
2149
2150                 impl Debug for BorrowedPlaceholder {
2151                     fn fmt(&self, f: &mut Formatter) -> Result {
2152                         f.write_str("<borrowed>")
2153                     }
2154                 }
2155
2156                 f.debug_struct("RefCell")
2157                     .field("value", &BorrowedPlaceholder)
2158                     .finish()
2159             }
2160         }
2161     }
2162 }
2163
2164 #[stable(feature = "rust1", since = "1.0.0")]
2165 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2166     fn fmt(&self, f: &mut Formatter) -> Result {
2167         Debug::fmt(&**self, f)
2168     }
2169 }
2170
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2173     fn fmt(&self, f: &mut Formatter) -> Result {
2174         Debug::fmt(&*(self.deref()), f)
2175     }
2176 }
2177
2178 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2179 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2180     fn fmt(&self, f: &mut Formatter) -> Result {
2181         f.pad("UnsafeCell")
2182     }
2183 }
2184
2185 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
2186 // it's a lot easier than creating all of the rt::Piece structures here.