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.
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.
11 //! Utilities for formatting and printing strings.
13 #![stable(feature = "rust1", since = "1.0.0")]
15 use cell::{UnsafeCell, Cell, RefCell, Ref, RefMut};
16 use marker::PhantomData;
28 #[unstable(feature = "fmt_flags_align", issue = "27726")]
29 /// Possible alignments returned by `Formatter::align`
32 /// Indication that contents should be left-aligned.
34 /// Indication that contents should be right-aligned.
36 /// Indication that contents should be center-aligned.
38 /// No alignment was requested.
42 #[stable(feature = "debug_builders", since = "1.2.0")]
43 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
45 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
52 /// The type returned by formatter methods.
66 /// impl fmt::Display for Triangle {
67 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
72 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
74 /// println!("{}", pythagorean_triple);
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub type Result = result::Result<(), Error>;
79 /// The error type which is returned from formatting a message into a stream.
81 /// This type does not support transmission of an error other than that an error
82 /// occurred. Any extra information must be arranged to be transmitted through
85 /// An important thing to remember is that the type `fmt::Error` should not be
86 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
89 /// [`std::io::Error`]: ../../std/io/struct.Error.html
90 /// [`std::error::Error`]: ../../std/error/trait.Error.html
95 /// use std::fmt::{self, write};
97 /// let mut output = String::new();
98 /// match write(&mut output, format_args!("Hello {}!", "world")) {
99 /// Err(fmt::Error) => panic!("An error occurred"),
103 #[stable(feature = "rust1", since = "1.0.0")]
104 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
107 /// A collection of methods that are required to format a message into a stream.
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.
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.
117 /// [`write!`]: ../../std/macro.write.html
118 /// [`io::Write`]: ../../std/io/trait.Write.html
119 #[stable(feature = "rust1", since = "1.0.0")]
121 /// Writes a slice of bytes into this writer, returning whether the write
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.
130 /// This function will return an instance of [`Error`] on error.
132 /// [`Error`]: struct.Error.html
137 /// use std::fmt::{Error, Write};
139 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
143 /// let mut buf = String::new();
144 /// writer(&mut buf, "hola").unwrap();
145 /// assert_eq!(&buf, "hola");
147 #[stable(feature = "rust1", since = "1.0.0")]
148 fn write_str(&mut self, s: &str) -> Result;
150 /// Writes a [`char`] into this writer, returning whether the write succeeded.
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.
159 /// This function will return an instance of [`Error`] on error.
161 /// [`char`]: ../../std/primitive.char.html
162 /// [`Error`]: struct.Error.html
167 /// use std::fmt::{Error, Write};
169 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
173 /// let mut buf = String::new();
174 /// writer(&mut buf, 'a').unwrap();
175 /// writer(&mut buf, 'b').unwrap();
176 /// assert_eq!(&buf, "ab");
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]))
183 /// Glue for usage of the [`write!`] macro with implementors of this trait.
185 /// This method should generally not be invoked manually, but rather through
186 /// the [`write!`] macro itself.
188 /// [`write!`]: ../../std/macro.write.html
193 /// use std::fmt::{Error, Write};
195 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
196 /// f.write_fmt(format_args!("{}", s))
199 /// let mut buf = String::new();
200 /// writer(&mut buf, "world").unwrap();
201 /// assert_eq!(&buf, "world");
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);
210 impl<'a, T: ?Sized> Write for Adapter<'a, T>
213 fn write_str(&mut self, s: &str) -> Result {
217 fn write_char(&mut self, c: char) -> Result {
221 fn write_fmt(&mut self, args: Arguments) -> Result {
222 self.0.write_fmt(args)
226 write(&mut Adapter(self), args)
230 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
231 impl<'a, W: Write + ?Sized> Write for &'a mut W {
232 fn write_str(&mut self, s: &str) -> Result {
233 (**self).write_str(s)
236 fn write_char(&mut self, c: char) -> Result {
237 (**self).write_char(c)
240 fn write_fmt(&mut self, args: Arguments) -> Result {
241 (**self).write_fmt(args)
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
248 #[allow(missing_debug_implementations)]
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub struct Formatter<'a> {
253 align: rt::v1::Alignment,
254 width: Option<usize>,
255 precision: Option<usize>,
257 buf: &'a mut (Write+'a),
258 curarg: slice::Iter<'a, ArgumentV1<'a>>,
259 args: &'a [ArgumentV1<'a>],
262 // NB. Argument is essentially an optimized partially applied formatting function,
263 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
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.
272 /// It was added after #45197 showed that one could share a `!Sync`
273 /// object across threads by passing it into `format_args!`.
274 _oibit_remover: PhantomData<*mut Fn()>,
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.
282 #[allow(missing_debug_implementations)]
283 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
286 pub struct ArgumentV1<'a> {
288 formatter: fn(&Void, &mut Formatter) -> Result,
291 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
293 impl<'a> Clone for ArgumentV1<'a> {
294 fn clone(&self) -> ArgumentV1<'a> {
299 impl<'a> ArgumentV1<'a> {
301 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
306 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
308 pub fn new<'b, T>(x: &'b T,
309 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
312 formatter: mem::transmute(f),
313 value: mem::transmute(x)
319 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
321 pub fn from_usize(x: &usize) -> ArgumentV1 {
322 ArgumentV1::new(x, ArgumentV1::show_usize)
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) })
334 // flags available in the v1 format of format_args
335 #[derive(Copy, Clone)]
336 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, DebugLowerHex, DebugUpperHex }
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!",
344 pub fn new_v1(pieces: &'a [&'a str],
345 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
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!",
362 pub fn new_v1_formatted(pieces: &'a [&'a str],
363 args: &'a [ArgumentV1<'a>],
364 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
372 /// Estimates the length of the formatted text.
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!",
379 pub fn estimated_capacity(&self) -> usize {
380 let pieces_length: usize = self.pieces.iter()
381 .map(|x| x.len()).sum();
383 if self.args.is_empty() {
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.
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)
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.
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.
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!`.
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);
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],
429 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
430 fmt: Option<&'a [rt::v1::Argument]>,
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>],
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl<'a> Debug for Arguments<'a> {
439 fn fmt(&self, fmt: &mut Formatter) -> Result {
440 Display::fmt(self, fmt)
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl<'a> Display for Arguments<'a> {
446 fn fmt(&self, fmt: &mut Formatter) -> Result {
447 write(fmt.buf, *self)
453 /// `Debug` should format the output in a programmer-facing, debugging context.
455 /// Generally speaking, you should just `derive` a `Debug` implementation.
457 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
459 /// For more information on formatters, see [the module-level documentation][module].
461 /// [module]: ../../std/fmt/index.html
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 `)`.
471 /// Deriving an implementation:
480 /// let origin = Point { x: 0, y: 0 };
482 /// println!("The origin is: {:?}", origin);
485 /// Manually implementing:
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)
501 /// let origin = Point { x: 0, y: 0 };
503 /// println!("The origin is: {:?}", origin);
509 /// The origin is: Point { x: 0, y: 0 }
512 /// There are a number of `debug_*` methods on [`Formatter`] to help you with manual
513 /// implementations, such as [`debug_struct`][debug_struct].
515 /// `Debug` implementations using either `derive` or the debug builder API
516 /// on [`Formatter`] support pretty printing using the alternate flag: `{:#?}`.
518 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
519 /// [`Formatter`]: ../../std/fmt/struct.Formatter.html
521 /// Pretty printing with `#?`:
530 /// let origin = Point { x: 0, y: 0 };
532 /// println!("The origin is: {:#?}", origin);
538 /// The origin is: Point {
543 #[stable(feature = "rust1", since = "1.0.0")]
544 #[rustc_on_unimplemented(
545 on(crate_local, label="`{Self}` cannot be formatted using `:?`; \
546 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}`",
550 #[doc(alias = "{:?}")]
551 #[lang = "debug_trait"]
553 /// Formats the value using the given formatter.
560 /// struct Position {
565 /// impl fmt::Debug for Position {
566 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
567 /// write!(f, "({:?}, {:?})", self.longitude, self.latitude)
571 /// assert_eq!("(1.987, 2.983)".to_owned(),
572 /// format!("{:?}", Position { longitude: 1.987, latitude: 2.983, }));
574 #[stable(feature = "rust1", since = "1.0.0")]
575 fn fmt(&self, f: &mut Formatter) -> Result;
578 /// Format trait for an empty format, `{}`.
580 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
581 /// output, and so cannot be derived.
583 /// [debug]: trait.Debug.html
585 /// For more information on formatters, see [the module-level documentation][module].
587 /// [module]: ../../std/fmt/index.html
591 /// Implementing `Display` on a type:
601 /// impl fmt::Display for Point {
602 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
603 /// write!(f, "({}, {})", self.x, self.y)
607 /// let origin = Point { x: 0, y: 0 };
609 /// println!("The origin is: {}", origin);
611 #[rustc_on_unimplemented(
612 message="`{Self}` doesn't implement `{Display}`",
613 label="`{Self}` cannot be formatted with the default formatter; \
614 try using `:?` instead if you are using a format string",
617 #[stable(feature = "rust1", since = "1.0.0")]
619 /// Formats the value using the given formatter.
626 /// struct Position {
631 /// impl fmt::Display for Position {
632 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
633 /// write!(f, "({}, {})", self.longitude, self.latitude)
637 /// assert_eq!("(1.987, 2.983)".to_owned(),
638 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
640 #[stable(feature = "rust1", since = "1.0.0")]
641 fn fmt(&self, f: &mut Formatter) -> Result;
646 /// The `Octal` trait should format its output as a number in base-8.
648 /// For primitive signed integers (`i8` to `i128`, and `isize`),
649 /// negative values are formatted as the two’s complement representation.
651 /// The alternate flag, `#`, adds a `0o` in front of the output.
653 /// For more information on formatters, see [the module-level documentation][module].
655 /// [module]: ../../std/fmt/index.html
659 /// Basic usage with `i32`:
662 /// let x = 42; // 42 is '52' in octal
664 /// assert_eq!(format!("{:o}", x), "52");
665 /// assert_eq!(format!("{:#o}", x), "0o52");
667 /// assert_eq!(format!("{:o}", -16), "37777777760");
670 /// Implementing `Octal` on a type:
675 /// struct Length(i32);
677 /// impl fmt::Octal for Length {
678 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
679 /// let val = self.0;
681 /// write!(f, "{:o}", val) // delegate to i32's implementation
685 /// let l = Length(9);
687 /// println!("l as octal is: {:o}", l);
689 #[stable(feature = "rust1", since = "1.0.0")]
691 /// Formats the value using the given formatter.
692 #[stable(feature = "rust1", since = "1.0.0")]
693 fn fmt(&self, f: &mut Formatter) -> Result;
698 /// The `Binary` trait should format its output as a number in binary.
700 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
701 /// negative values are formatted as the two’s complement representation.
703 /// The alternate flag, `#`, adds a `0b` in front of the output.
705 /// For more information on formatters, see [the module-level documentation][module].
709 /// Basic usage with [`i32`]:
712 /// let x = 42; // 42 is '101010' in binary
714 /// assert_eq!(format!("{:b}", x), "101010");
715 /// assert_eq!(format!("{:#b}", x), "0b101010");
717 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
720 /// Implementing `Binary` on a type:
725 /// struct Length(i32);
727 /// impl fmt::Binary for Length {
728 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
729 /// let val = self.0;
731 /// write!(f, "{:b}", val) // delegate to i32's implementation
735 /// let l = Length(107);
737 /// println!("l as binary is: {:b}", l);
740 /// [module]: ../../std/fmt/index.html
741 /// [`i8`]: ../../std/primitive.i8.html
742 /// [`i128`]: ../../std/primitive.i128.html
743 /// [`isize`]: ../../std/primitive.isize.html
744 /// [`i32`]: ../../std/primitive.i32.html
745 #[stable(feature = "rust1", since = "1.0.0")]
747 /// Formats the value using the given formatter.
748 #[stable(feature = "rust1", since = "1.0.0")]
749 fn fmt(&self, f: &mut Formatter) -> Result;
754 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
757 /// For primitive signed integers (`i8` to `i128`, and `isize`),
758 /// negative values are formatted as the two’s complement representation.
760 /// The alternate flag, `#`, adds a `0x` in front of the output.
762 /// For more information on formatters, see [the module-level documentation][module].
764 /// [module]: ../../std/fmt/index.html
768 /// Basic usage with `i32`:
771 /// let x = 42; // 42 is '2a' in hex
773 /// assert_eq!(format!("{:x}", x), "2a");
774 /// assert_eq!(format!("{:#x}", x), "0x2a");
776 /// assert_eq!(format!("{:x}", -16), "fffffff0");
779 /// Implementing `LowerHex` on a type:
784 /// struct Length(i32);
786 /// impl fmt::LowerHex for Length {
787 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
788 /// let val = self.0;
790 /// write!(f, "{:x}", val) // delegate to i32's implementation
794 /// let l = Length(9);
796 /// println!("l as hex is: {:x}", l);
798 #[stable(feature = "rust1", since = "1.0.0")]
800 /// Formats the value using the given formatter.
801 #[stable(feature = "rust1", since = "1.0.0")]
802 fn fmt(&self, f: &mut Formatter) -> Result;
807 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
810 /// For primitive signed integers (`i8` to `i128`, and `isize`),
811 /// negative values are formatted as the two’s complement representation.
813 /// The alternate flag, `#`, adds a `0x` in front of the output.
815 /// For more information on formatters, see [the module-level documentation][module].
817 /// [module]: ../../std/fmt/index.html
821 /// Basic usage with `i32`:
824 /// let x = 42; // 42 is '2A' in hex
826 /// assert_eq!(format!("{:X}", x), "2A");
827 /// assert_eq!(format!("{:#X}", x), "0x2A");
829 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
832 /// Implementing `UpperHex` on a type:
837 /// struct Length(i32);
839 /// impl fmt::UpperHex for Length {
840 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
841 /// let val = self.0;
843 /// write!(f, "{:X}", val) // delegate to i32's implementation
847 /// let l = Length(9);
849 /// println!("l as hex is: {:X}", l);
851 #[stable(feature = "rust1", since = "1.0.0")]
853 /// Formats the value using the given formatter.
854 #[stable(feature = "rust1", since = "1.0.0")]
855 fn fmt(&self, f: &mut Formatter) -> Result;
860 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
863 /// For more information on formatters, see [the module-level documentation][module].
865 /// [module]: ../../std/fmt/index.html
869 /// Basic usage with `&i32`:
874 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
877 /// Implementing `Pointer` on a type:
882 /// struct Length(i32);
884 /// impl fmt::Pointer for Length {
885 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
886 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
888 /// write!(f, "{:p}", self as *const Length)
892 /// let l = Length(42);
894 /// println!("l is in memory here: {:p}", l);
896 #[stable(feature = "rust1", since = "1.0.0")]
898 /// Formats the value using the given formatter.
899 #[stable(feature = "rust1", since = "1.0.0")]
900 fn fmt(&self, f: &mut Formatter) -> Result;
905 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
907 /// For more information on formatters, see [the module-level documentation][module].
909 /// [module]: ../../std/fmt/index.html
913 /// Basic usage with `i32`:
916 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
918 /// assert_eq!(format!("{:e}", x), "4.2e1");
921 /// Implementing `LowerExp` on a type:
926 /// struct Length(i32);
928 /// impl fmt::LowerExp for Length {
929 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
930 /// let val = self.0;
931 /// write!(f, "{}e1", val / 10)
935 /// let l = Length(100);
937 /// println!("l in scientific notation is: {:e}", l);
939 #[stable(feature = "rust1", since = "1.0.0")]
941 /// Formats the value using the given formatter.
942 #[stable(feature = "rust1", since = "1.0.0")]
943 fn fmt(&self, f: &mut Formatter) -> Result;
948 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
950 /// For more information on formatters, see [the module-level documentation][module].
952 /// [module]: ../../std/fmt/index.html
956 /// Basic usage with `f32`:
959 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
961 /// assert_eq!(format!("{:E}", x), "4.2E1");
964 /// Implementing `UpperExp` on a type:
969 /// struct Length(i32);
971 /// impl fmt::UpperExp for Length {
972 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
973 /// let val = self.0;
974 /// write!(f, "{}E1", val / 10)
978 /// let l = Length(100);
980 /// println!("l in scientific notation is: {:E}", l);
982 #[stable(feature = "rust1", since = "1.0.0")]
984 /// Formats the value using the given formatter.
985 #[stable(feature = "rust1", since = "1.0.0")]
986 fn fmt(&self, f: &mut Formatter) -> Result;
989 /// The `write` function takes an output stream, and an `Arguments` struct
990 /// that can be precompiled with the `format_args!` macro.
992 /// The arguments will be formatted according to the specified format string
993 /// into the output stream provided.
1002 /// let mut output = String::new();
1003 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1004 /// .expect("Error occurred while trying to write in String");
1005 /// assert_eq!(output, "Hello world!");
1008 /// Please note that using [`write!`] might be preferable. Example:
1011 /// use std::fmt::Write;
1013 /// let mut output = String::new();
1014 /// write!(&mut output, "Hello {}!", "world")
1015 /// .expect("Error occurred while trying to write in String");
1016 /// assert_eq!(output, "Hello world!");
1019 /// [`write!`]: ../../std/macro.write.html
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub fn write(output: &mut Write, args: Arguments) -> Result {
1022 let mut formatter = Formatter {
1027 align: rt::v1::Alignment::Unknown,
1030 curarg: args.args.iter(),
1033 let mut pieces = args.pieces.iter();
1037 // We can use default formatting parameters for all arguments.
1038 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
1039 formatter.buf.write_str(*piece)?;
1040 (arg.formatter)(arg.value, &mut formatter)?;
1044 // Every spec has a corresponding argument that is preceded by
1046 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
1047 formatter.buf.write_str(*piece)?;
1048 formatter.run(arg)?;
1053 // There can be only one trailing string piece left.
1054 if let Some(piece) = pieces.next() {
1055 formatter.buf.write_str(*piece)?;
1061 impl<'a> Formatter<'a> {
1062 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1063 where 'b: 'c, F: FnOnce(&'b mut (Write+'b)) -> &'c mut (Write+'c)
1066 // We want to change this
1067 buf: wrap(self.buf),
1069 // And preserve these
1074 precision: self.precision,
1076 // These only exist in the struct for the `run` method,
1077 // which won’t be used together with this method.
1078 curarg: self.curarg.clone(),
1083 // First up is the collection of functions used to execute a format string
1084 // at runtime. This consumes all of the compile-time statics generated by
1085 // the format! syntax extension.
1086 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1087 // Fill in the format parameters into the formatter
1088 self.fill = arg.format.fill;
1089 self.align = arg.format.align;
1090 self.flags = arg.format.flags;
1091 self.width = self.getcount(&arg.format.width);
1092 self.precision = self.getcount(&arg.format.precision);
1094 // Extract the correct argument
1095 let value = match arg.position {
1096 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
1097 rt::v1::Position::At(i) => self.args[i],
1100 // Then actually do some printing
1101 (value.formatter)(value.value, self)
1104 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1106 rt::v1::Count::Is(n) => Some(n),
1107 rt::v1::Count::Implied => None,
1108 rt::v1::Count::Param(i) => {
1109 self.args[i].as_usize()
1111 rt::v1::Count::NextParam => {
1112 self.curarg.next().and_then(|arg| arg.as_usize())
1117 // Helper methods used for padding and processing formatting arguments that
1118 // all formatting traits can use.
1120 /// Performs the correct padding for an integer which has already been
1121 /// emitted into a str. The str should *not* contain the sign for the
1122 /// integer, that will be added by this method.
1126 /// * is_nonnegative - whether the original integer was either positive or zero.
1127 /// * prefix - if the '#' character (Alternate) is provided, this
1128 /// is the prefix to put in front of the number.
1129 /// * buf - the byte array that the number has been formatted into
1131 /// This function will correctly account for the flags provided as well as
1132 /// the minimum width. It will not take precision into account.
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 pub fn pad_integral(&mut self,
1135 is_nonnegative: bool,
1139 let mut width = buf.len();
1141 let mut sign = None;
1142 if !is_nonnegative {
1143 sign = Some('-'); width += 1;
1144 } else if self.sign_plus() {
1145 sign = Some('+'); width += 1;
1148 let mut prefixed = false;
1149 if self.alternate() {
1150 prefixed = true; width += prefix.chars().count();
1153 // Writes the sign if it exists, and then the prefix if it was requested
1154 let write_prefix = |f: &mut Formatter| {
1155 if let Some(c) = sign {
1156 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
1158 if prefixed { f.buf.write_str(prefix) }
1162 // The `width` field is more of a `min-width` parameter at this point.
1164 // If there's no minimum length requirements then we can just
1167 write_prefix(self)?; self.buf.write_str(buf)
1169 // Check if we're over the minimum width, if so then we can also
1170 // just write the bytes.
1171 Some(min) if width >= min => {
1172 write_prefix(self)?; self.buf.write_str(buf)
1174 // The sign and prefix goes before the padding if the fill character
1176 Some(min) if self.sign_aware_zero_pad() => {
1178 self.align = rt::v1::Alignment::Right;
1179 write_prefix(self)?;
1180 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1181 f.buf.write_str(buf)
1184 // Otherwise, the sign and prefix goes after the padding
1186 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1187 write_prefix(f)?; f.buf.write_str(buf)
1193 /// This function takes a string slice and emits it to the internal buffer
1194 /// after applying the relevant formatting flags specified. The flags
1195 /// recognized for generic strings are:
1197 /// * width - the minimum width of what to emit
1198 /// * fill/align - what to emit and where to emit it if the string
1199 /// provided needs to be padded
1200 /// * precision - the maximum length to emit, the string is truncated if it
1201 /// is longer than this length
1203 /// Notably this function ignores the `flag` parameters.
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 pub fn pad(&mut self, s: &str) -> Result {
1206 // Make sure there's a fast path up front
1207 if self.width.is_none() && self.precision.is_none() {
1208 return self.buf.write_str(s);
1210 // The `precision` field can be interpreted as a `max-width` for the
1211 // string being formatted.
1212 let s = if let Some(max) = self.precision {
1213 // If our string is longer that the precision, then we must have
1214 // truncation. However other flags like `fill`, `width` and `align`
1215 // must act as always.
1216 if let Some((i, _)) = s.char_indices().skip(max).next() {
1217 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1218 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1219 // `unsafe` and otherwise don't emit any panic-related code
1221 s.get(..i).unwrap_or(&s)
1228 // The `width` field is more of a `min-width` parameter at this point.
1230 // If we're under the maximum length, and there's no minimum length
1231 // requirements, then we can just emit the string
1232 None => self.buf.write_str(s),
1233 // If we're under the maximum width, check if we're over the minimum
1234 // width, if so it's as easy as just emitting the string.
1235 Some(width) if s.chars().count() >= width => {
1236 self.buf.write_str(s)
1238 // If we're under both the maximum and the minimum width, then fill
1239 // up the minimum width with the specified string + some alignment.
1241 let align = rt::v1::Alignment::Left;
1242 self.with_padding(width - s.chars().count(), align, |me| {
1249 /// Runs a callback, emitting the correct padding either before or
1250 /// afterwards depending on whether right or left alignment is requested.
1251 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1253 where F: FnOnce(&mut Formatter) -> Result,
1255 let align = match self.align {
1256 rt::v1::Alignment::Unknown => default,
1260 let (pre_pad, post_pad) = match align {
1261 rt::v1::Alignment::Left => (0, padding),
1262 rt::v1::Alignment::Right |
1263 rt::v1::Alignment::Unknown => (padding, 0),
1264 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1267 let mut fill = [0; 4];
1268 let fill = self.fill.encode_utf8(&mut fill);
1270 for _ in 0..pre_pad {
1271 self.buf.write_str(fill)?;
1276 for _ in 0..post_pad {
1277 self.buf.write_str(fill)?;
1283 /// Takes the formatted parts and applies the padding.
1284 /// Assumes that the caller already has rendered the parts with required precision,
1285 /// so that `self.precision` can be ignored.
1286 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1287 if let Some(mut width) = self.width {
1288 // for the sign-aware zero padding, we render the sign first and
1289 // behave as if we had no sign from the beginning.
1290 let mut formatted = formatted.clone();
1291 let old_fill = self.fill;
1292 let old_align = self.align;
1293 let mut align = old_align;
1294 if self.sign_aware_zero_pad() {
1295 // a sign always goes first
1296 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1297 self.buf.write_str(sign)?;
1299 // remove the sign from the formatted parts
1300 formatted.sign = b"";
1301 width = if width < sign.len() { 0 } else { width - sign.len() };
1302 align = rt::v1::Alignment::Right;
1304 self.align = rt::v1::Alignment::Right;
1307 // remaining parts go through the ordinary padding process.
1308 let len = formatted.len();
1309 let ret = if width <= len { // no padding
1310 self.write_formatted_parts(&formatted)
1312 self.with_padding(width - len, align, |f| {
1313 f.write_formatted_parts(&formatted)
1316 self.fill = old_fill;
1317 self.align = old_align;
1320 // this is the common case and we take a shortcut
1321 self.write_formatted_parts(formatted)
1325 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1326 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1327 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1330 if !formatted.sign.is_empty() {
1331 write_bytes(self.buf, formatted.sign)?;
1333 for part in formatted.parts {
1335 flt2dec::Part::Zero(mut nzeroes) => {
1336 const ZEROES: &'static str = // 64 zeroes
1337 "0000000000000000000000000000000000000000000000000000000000000000";
1338 while nzeroes > ZEROES.len() {
1339 self.buf.write_str(ZEROES)?;
1340 nzeroes -= ZEROES.len();
1343 self.buf.write_str(&ZEROES[..nzeroes])?;
1346 flt2dec::Part::Num(mut v) => {
1348 let len = part.len();
1349 for c in s[..len].iter_mut().rev() {
1350 *c = b'0' + (v % 10) as u8;
1353 write_bytes(self.buf, &s[..len])?;
1355 flt2dec::Part::Copy(buf) => {
1356 write_bytes(self.buf, buf)?;
1363 /// Writes some data to the underlying buffer contained within this
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 pub fn write_str(&mut self, data: &str) -> Result {
1367 self.buf.write_str(data)
1370 /// Writes some formatted information into this instance
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1373 write(self.buf, fmt)
1376 /// Flags for formatting
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 #[rustc_deprecated(since = "1.24.0",
1379 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1380 or `sign_aware_zero_pad` methods instead")]
1381 pub fn flags(&self) -> u32 { self.flags }
1383 /// Character used as 'fill' whenever there is alignment
1384 #[stable(feature = "fmt_flags", since = "1.5.0")]
1385 pub fn fill(&self) -> char { self.fill }
1387 /// Flag indicating what form of alignment was requested
1388 #[unstable(feature = "fmt_flags_align", reason = "method was just created",
1390 pub fn align(&self) -> Alignment {
1392 rt::v1::Alignment::Left => Alignment::Left,
1393 rt::v1::Alignment::Right => Alignment::Right,
1394 rt::v1::Alignment::Center => Alignment::Center,
1395 rt::v1::Alignment::Unknown => Alignment::Unknown,
1399 /// Optionally specified integer width that the output should be.
1406 /// struct Foo(i32);
1408 /// impl fmt::Display for Foo {
1409 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1410 /// if let Some(width) = formatter.width() {
1411 /// // If we received a width, we use it
1412 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1414 /// // Otherwise we do nothing special
1415 /// write!(formatter, "Foo({})", self.0)
1420 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1421 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1423 #[stable(feature = "fmt_flags", since = "1.5.0")]
1424 pub fn width(&self) -> Option<usize> { self.width }
1426 /// Optionally specified precision for numeric types.
1433 /// struct Foo(f32);
1435 /// impl fmt::Display for Foo {
1436 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1437 /// if let Some(precision) = formatter.precision() {
1438 /// // If we received a precision, we use it.
1439 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1441 /// // Otherwise we default to 2.
1442 /// write!(formatter, "Foo({:.2})", self.0)
1447 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1448 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1450 #[stable(feature = "fmt_flags", since = "1.5.0")]
1451 pub fn precision(&self) -> Option<usize> { self.precision }
1453 /// Determines if the `+` flag was specified.
1460 /// struct Foo(i32);
1462 /// impl fmt::Display for Foo {
1463 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1464 /// if formatter.sign_plus() {
1465 /// write!(formatter,
1467 /// if self.0 < 0 { '-' } else { '+' },
1470 /// write!(formatter, "Foo({})", self.0)
1475 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1476 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1478 #[stable(feature = "fmt_flags", since = "1.5.0")]
1479 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1481 /// Determines if the `-` flag was specified.
1488 /// struct Foo(i32);
1490 /// impl fmt::Display for Foo {
1491 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1492 /// if formatter.sign_minus() {
1493 /// // You want a minus sign? Have one!
1494 /// write!(formatter, "-Foo({})", self.0)
1496 /// write!(formatter, "Foo({})", self.0)
1501 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1502 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1504 #[stable(feature = "fmt_flags", since = "1.5.0")]
1505 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1507 /// Determines if the `#` flag was specified.
1514 /// struct Foo(i32);
1516 /// impl fmt::Display for Foo {
1517 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1518 /// if formatter.alternate() {
1519 /// write!(formatter, "Foo({})", self.0)
1521 /// write!(formatter, "{}", self.0)
1526 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1527 /// assert_eq!(&format!("{}", Foo(23)), "23");
1529 #[stable(feature = "fmt_flags", since = "1.5.0")]
1530 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1532 /// Determines if the `0` flag was specified.
1539 /// struct Foo(i32);
1541 /// impl fmt::Display for Foo {
1542 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1543 /// assert!(formatter.sign_aware_zero_pad());
1544 /// assert_eq!(formatter.width(), Some(4));
1545 /// // We ignore the formatter's options.
1546 /// write!(formatter, "{}", self.0)
1550 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1552 #[stable(feature = "fmt_flags", since = "1.5.0")]
1553 pub fn sign_aware_zero_pad(&self) -> bool {
1554 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1557 // FIXME: Decide what public API we want for these two flags.
1558 // https://github.com/rust-lang/rust/issues/48584
1559 fn debug_lower_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0 }
1561 fn debug_upper_hex(&self) -> bool { self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0 }
1563 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1564 /// [`fmt::Debug`] implementations for structs.
1566 /// [`DebugStruct`]: ../../std/fmt/struct.DebugStruct.html
1567 /// [`fmt::Debug`]: ../../std/fmt/trait.Debug.html
1573 /// use std::net::Ipv4Addr;
1581 /// impl fmt::Debug for Foo {
1582 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1583 /// fmt.debug_struct("Foo")
1584 /// .field("bar", &self.bar)
1585 /// .field("baz", &self.baz)
1586 /// .field("addr", &format_args!("{}", self.addr))
1592 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1593 /// format!("{:?}", Foo {
1595 /// baz: "Hello World".to_string(),
1596 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1600 #[stable(feature = "debug_builders", since = "1.2.0")]
1601 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1602 builders::debug_struct_new(self, name)
1605 /// Creates a `DebugTuple` builder designed to assist with creation of
1606 /// `fmt::Debug` implementations for tuple structs.
1612 /// use std::marker::PhantomData;
1614 /// struct Foo<T>(i32, String, PhantomData<T>);
1616 /// impl<T> fmt::Debug for Foo<T> {
1617 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1618 /// fmt.debug_tuple("Foo")
1621 /// .field(&format_args!("_"))
1627 /// "Foo(10, \"Hello\", _)",
1628 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1631 #[stable(feature = "debug_builders", since = "1.2.0")]
1632 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1633 builders::debug_tuple_new(self, name)
1636 /// Creates a `DebugList` builder designed to assist with creation of
1637 /// `fmt::Debug` implementations for list-like structures.
1644 /// struct Foo(Vec<i32>);
1646 /// impl fmt::Debug for Foo {
1647 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1648 /// fmt.debug_list().entries(self.0.iter()).finish()
1652 /// // prints "[10, 11]"
1653 /// println!("{:?}", Foo(vec![10, 11]));
1655 #[stable(feature = "debug_builders", since = "1.2.0")]
1656 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1657 builders::debug_list_new(self)
1660 /// Creates a `DebugSet` builder designed to assist with creation of
1661 /// `fmt::Debug` implementations for set-like structures.
1668 /// struct Foo(Vec<i32>);
1670 /// impl fmt::Debug for Foo {
1671 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1672 /// fmt.debug_set().entries(self.0.iter()).finish()
1676 /// // prints "{10, 11}"
1677 /// println!("{:?}", Foo(vec![10, 11]));
1680 /// [`format_args!`]: ../../std/macro.format_args.html
1682 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1683 /// to build a list of match arms:
1688 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1689 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1691 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1693 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1695 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1696 /// L::fmt(&(self.0).0, fmt)?;
1697 /// fmt.write_str(" => ")?;
1698 /// R::fmt(&(self.0).1, fmt)
1702 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1704 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1706 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1708 /// .entries(self.0.iter().map(Arm))
1709 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1714 #[stable(feature = "debug_builders", since = "1.2.0")]
1715 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1716 builders::debug_set_new(self)
1719 /// Creates a `DebugMap` builder designed to assist with creation of
1720 /// `fmt::Debug` implementations for map-like structures.
1727 /// struct Foo(Vec<(String, i32)>);
1729 /// impl fmt::Debug for Foo {
1730 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1731 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1735 /// // prints "{"A": 10, "B": 11}"
1736 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1738 #[stable(feature = "debug_builders", since = "1.2.0")]
1739 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1740 builders::debug_map_new(self)
1744 #[stable(since = "1.2.0", feature = "formatter_write")]
1745 impl<'a> Write for Formatter<'a> {
1746 fn write_str(&mut self, s: &str) -> Result {
1747 self.buf.write_str(s)
1750 fn write_char(&mut self, c: char) -> Result {
1751 self.buf.write_char(c)
1754 fn write_fmt(&mut self, args: Arguments) -> Result {
1755 write(self.buf, args)
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl Display for Error {
1761 fn fmt(&self, f: &mut Formatter) -> Result {
1762 Display::fmt("an error occurred when formatting an argument", f)
1766 // Implementations of the core formatting traits
1768 macro_rules! fmt_refs {
1769 ($($tr:ident),*) => {
1771 #[stable(feature = "rust1", since = "1.0.0")]
1772 impl<'a, T: ?Sized + $tr> $tr for &'a T {
1773 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1775 #[stable(feature = "rust1", since = "1.0.0")]
1776 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1777 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1783 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1785 #[unstable(feature = "never_type", issue = "35121")]
1787 fn fmt(&self, _: &mut Formatter) -> Result {
1792 #[unstable(feature = "never_type", issue = "35121")]
1793 impl Display for ! {
1794 fn fmt(&self, _: &mut Formatter) -> Result {
1799 #[stable(feature = "rust1", since = "1.0.0")]
1800 impl Debug for bool {
1802 fn fmt(&self, f: &mut Formatter) -> Result {
1803 Display::fmt(self, f)
1807 #[stable(feature = "rust1", since = "1.0.0")]
1808 impl Display for bool {
1809 fn fmt(&self, f: &mut Formatter) -> Result {
1810 Display::fmt(if *self { "true" } else { "false" }, f)
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 impl Debug for str {
1816 fn fmt(&self, f: &mut Formatter) -> Result {
1819 for (i, c) in self.char_indices() {
1820 let esc = c.escape_debug();
1821 // If char needs escaping, flush backlog so far and write, else skip
1823 f.write_str(&self[from..i])?;
1827 from = i + c.len_utf8();
1830 f.write_str(&self[from..])?;
1835 #[stable(feature = "rust1", since = "1.0.0")]
1836 impl Display for str {
1837 fn fmt(&self, f: &mut Formatter) -> Result {
1842 #[stable(feature = "rust1", since = "1.0.0")]
1843 impl Debug for char {
1844 fn fmt(&self, f: &mut Formatter) -> Result {
1845 f.write_char('\'')?;
1846 for c in self.escape_debug() {
1853 #[stable(feature = "rust1", since = "1.0.0")]
1854 impl Display for char {
1855 fn fmt(&self, f: &mut Formatter) -> Result {
1856 if f.width.is_none() && f.precision.is_none() {
1859 f.pad(self.encode_utf8(&mut [0; 4]))
1864 #[stable(feature = "rust1", since = "1.0.0")]
1865 impl<T: ?Sized> Pointer for *const T {
1866 fn fmt(&self, f: &mut Formatter) -> Result {
1867 let old_width = f.width;
1868 let old_flags = f.flags;
1870 // The alternate flag is already treated by LowerHex as being special-
1871 // it denotes whether to prefix with 0x. We use it to work out whether
1872 // or not to zero extend, and then unconditionally set it to get the
1875 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1877 if let None = f.width {
1878 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
1881 f.flags |= 1 << (FlagV1::Alternate as u32);
1883 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
1885 f.width = old_width;
1886 f.flags = old_flags;
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 impl<T: ?Sized> Pointer for *mut T {
1894 fn fmt(&self, f: &mut Formatter) -> Result {
1895 Pointer::fmt(&(*self as *const T), f)
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 impl<'a, T: ?Sized> Pointer for &'a T {
1901 fn fmt(&self, f: &mut Formatter) -> Result {
1902 Pointer::fmt(&(*self as *const T), f)
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 impl<'a, T: ?Sized> Pointer for &'a mut T {
1908 fn fmt(&self, f: &mut Formatter) -> Result {
1909 Pointer::fmt(&(&**self as *const T), f)
1913 // Implementation of Display/Debug for various core types
1915 #[stable(feature = "rust1", since = "1.0.0")]
1916 impl<T: ?Sized> Debug for *const T {
1917 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 impl<T: ?Sized> Debug for *mut T {
1921 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1925 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1928 macro_rules! tuple {
1930 ( $($name:ident,)+ ) => (
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 impl<$($name:Debug),*> Debug for ($($name,)*) where last_type!($($name,)+): ?Sized {
1933 #[allow(non_snake_case, unused_assignments, deprecated)]
1934 fn fmt(&self, f: &mut Formatter) -> Result {
1935 let mut builder = f.debug_tuple("");
1936 let ($(ref $name,)*) = *self;
1938 builder.field(&$name);
1944 peel! { $($name,)* }
1948 macro_rules! last_type {
1949 ($a:ident,) => { $a };
1950 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
1953 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl<T: Debug> Debug for [T] {
1957 fn fmt(&self, f: &mut Formatter) -> Result {
1958 f.debug_list().entries(self.iter()).finish()
1962 #[stable(feature = "rust1", since = "1.0.0")]
1965 fn fmt(&self, f: &mut Formatter) -> Result {
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl<T: ?Sized> Debug for PhantomData<T> {
1971 fn fmt(&self, f: &mut Formatter) -> Result {
1972 f.pad("PhantomData")
1976 #[stable(feature = "rust1", since = "1.0.0")]
1977 impl<T: Copy + Debug> Debug for Cell<T> {
1978 fn fmt(&self, f: &mut Formatter) -> Result {
1979 f.debug_struct("Cell")
1980 .field("value", &self.get())
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1987 fn fmt(&self, f: &mut Formatter) -> Result {
1988 match self.try_borrow() {
1990 f.debug_struct("RefCell")
1991 .field("value", &borrow)
1995 // The RefCell is mutably borrowed so we can't look at its value
1996 // here. Show a placeholder instead.
1997 struct BorrowedPlaceholder;
1999 impl Debug for BorrowedPlaceholder {
2000 fn fmt(&self, f: &mut Formatter) -> Result {
2001 f.write_str("<borrowed>")
2005 f.debug_struct("RefCell")
2006 .field("value", &BorrowedPlaceholder)
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
2015 fn fmt(&self, f: &mut Formatter) -> Result {
2016 Debug::fmt(&**self, f)
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
2022 fn fmt(&self, f: &mut Formatter) -> Result {
2023 Debug::fmt(&*(self.deref()), f)
2027 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2028 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2029 fn fmt(&self, f: &mut Formatter) -> Result {
2034 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
2035 // it's a lot easier than creating all of the rt::Piece structures here.