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;
24 #[unstable(feature = "fmt_flags_align", issue = "27726")]
25 /// Possible alignments returned by `Formatter::align`
28 /// Indication that contents should be left-aligned.
30 /// Indication that contents should be right-aligned.
32 /// Indication that contents should be center-aligned.
34 /// No alignment was requested.
38 #[stable(feature = "debug_builders", since = "1.2.0")]
39 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
44 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
51 #[stable(feature = "rust1", since = "1.0.0")]
52 /// The type returned by formatter methods.
53 pub type Result = result::Result<(), Error>;
55 /// The error type which is returned from formatting a message into a stream.
57 /// This type does not support transmission of an error other than that an error
58 /// occurred. Any extra information must be arranged to be transmitted through
60 #[stable(feature = "rust1", since = "1.0.0")]
61 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
64 /// A collection of methods that are required to format a message into a stream.
66 /// This trait is the type which this modules requires when formatting
67 /// information. This is similar to the standard library's `io::Write` trait,
68 /// but it is only intended for use in libcore.
70 /// This trait should generally not be implemented by consumers of the standard
71 /// library. The `write!` macro accepts an instance of `io::Write`, and the
72 /// `io::Write` trait is favored over implementing this trait.
73 #[stable(feature = "rust1", since = "1.0.0")]
75 /// Writes a slice of bytes into this writer, returning whether the write
78 /// This method can only succeed if the entire byte slice was successfully
79 /// written, and this method will not return until all data has been
80 /// written or an error occurs.
84 /// This function will return an instance of `Error` on error.
85 #[stable(feature = "rust1", since = "1.0.0")]
86 fn write_str(&mut self, s: &str) -> Result;
88 /// Writes a `char` into this writer, returning whether the write succeeded.
90 /// A single `char` may be encoded as more than one byte.
91 /// This method can only succeed if the entire byte sequence was successfully
92 /// written, and this method will not return until all data has been
93 /// written or an error occurs.
97 /// This function will return an instance of `Error` on error.
98 #[stable(feature = "fmt_write_char", since = "1.1.0")]
99 fn write_char(&mut self, c: char) -> Result {
100 self.write_str(c.encode_utf8(&mut [0; 4]))
103 /// Glue for usage of the `write!` macro with implementors of this trait.
105 /// This method should generally not be invoked manually, but rather through
106 /// the `write!` macro itself.
107 #[stable(feature = "rust1", since = "1.0.0")]
108 fn write_fmt(&mut self, args: Arguments) -> Result {
109 // This Adapter is needed to allow `self` (of type `&mut
110 // Self`) to be cast to a Write (below) without
111 // requiring a `Sized` bound.
112 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
114 impl<'a, T: ?Sized> Write for Adapter<'a, T>
117 fn write_str(&mut self, s: &str) -> Result {
121 fn write_char(&mut self, c: char) -> Result {
125 fn write_fmt(&mut self, args: Arguments) -> Result {
126 self.0.write_fmt(args)
130 write(&mut Adapter(self), args)
134 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
135 impl<'a, W: Write + ?Sized> Write for &'a mut W {
136 fn write_str(&mut self, s: &str) -> Result {
137 (**self).write_str(s)
140 fn write_char(&mut self, c: char) -> Result {
141 (**self).write_char(c)
144 fn write_fmt(&mut self, args: Arguments) -> Result {
145 (**self).write_fmt(args)
149 /// A struct to represent both where to emit formatting strings to and how they
150 /// should be formatted. A mutable version of this is passed to all formatting
152 #[allow(missing_debug_implementations)]
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub struct Formatter<'a> {
157 align: rt::v1::Alignment,
158 width: Option<usize>,
159 precision: Option<usize>,
161 buf: &'a mut (Write+'a),
162 curarg: slice::Iter<'a, ArgumentV1<'a>>,
163 args: &'a [ArgumentV1<'a>],
166 // NB. Argument is essentially an optimized partially applied formatting function,
167 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
173 /// This struct represents the generic "argument" which is taken by the Xprintf
174 /// family of functions. It contains a function to format the given value. At
175 /// compile time it is ensured that the function and the value have the correct
176 /// types, and then this struct is used to canonicalize arguments to one type.
178 #[allow(missing_debug_implementations)]
179 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
182 pub struct ArgumentV1<'a> {
184 formatter: fn(&Void, &mut Formatter) -> Result,
187 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
189 impl<'a> Clone for ArgumentV1<'a> {
190 fn clone(&self) -> ArgumentV1<'a> {
195 impl<'a> ArgumentV1<'a> {
197 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
202 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
204 pub fn new<'b, T>(x: &'b T,
205 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
208 formatter: mem::transmute(f),
209 value: mem::transmute(x)
215 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
217 pub fn from_usize(x: &usize) -> ArgumentV1 {
218 ArgumentV1::new(x, ArgumentV1::show_usize)
221 fn as_usize(&self) -> Option<usize> {
222 if self.formatter as usize == ArgumentV1::show_usize as usize {
223 Some(unsafe { *(self.value as *const _ as *const usize) })
230 // flags available in the v1 format of format_args
231 #[derive(Copy, Clone)]
232 #[allow(dead_code)] // SignMinus isn't currently used
233 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
235 impl<'a> Arguments<'a> {
236 /// When using the format_args!() macro, this function is used to generate the
237 /// Arguments structure.
238 #[doc(hidden)] #[inline]
239 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
241 pub fn new_v1(pieces: &'a [&'a str],
242 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
250 /// This function is used to specify nonstandard formatting parameters.
251 /// The `pieces` array must be at least as long as `fmt` to construct
252 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
253 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
254 /// created with `argumentusize`. However, failing to do so doesn't cause
255 /// unsafety, but will ignore invalid .
256 #[doc(hidden)] #[inline]
257 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
259 pub fn new_v1_formatted(pieces: &'a [&'a str],
260 args: &'a [ArgumentV1<'a>],
261 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
269 /// Estimates the length of the formatted text.
271 /// This is intended to be used for setting initial `String` capacity
272 /// when using `format!`. Note: this is neither the lower nor upper bound.
273 #[doc(hidden)] #[inline]
274 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
276 pub fn estimated_capacity(&self) -> usize {
277 let pieces_length: usize = self.pieces.iter()
278 .map(|x| x.len()).sum();
280 if self.args.is_empty() {
282 } else if self.pieces[0] == "" && pieces_length < 16 {
283 // If the format string starts with an argument,
284 // don't preallocate anything, unless length
285 // of pieces is significant.
288 // There are some arguments, so any additional push
289 // will reallocate the string. To avoid that,
290 // we're "pre-doubling" the capacity here.
291 pieces_length.checked_mul(2).unwrap_or(0)
296 /// This structure represents a safely precompiled version of a format string
297 /// and its arguments. This cannot be generated at runtime because it cannot
298 /// safely be done so, so no constructors are given and the fields are private
299 /// to prevent modification.
301 /// The [`format_args!`] macro will safely create an instance of this structure
302 /// and pass it to a function or closure, passed as the first argument. The
303 /// macro validates the format string at compile-time so usage of the [`write`]
304 /// and [`format`] functions can be safely performed.
306 /// [`format_args!`]: ../../std/macro.format_args.html
307 /// [`format`]: ../../std/fmt/fn.format.html
308 /// [`write`]: ../../std/fmt/fn.write.html
309 #[stable(feature = "rust1", since = "1.0.0")]
310 #[derive(Copy, Clone)]
311 pub struct Arguments<'a> {
312 // Format string pieces to print.
313 pieces: &'a [&'a str],
315 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
316 fmt: Option<&'a [rt::v1::Argument]>,
318 // Dynamic arguments for interpolation, to be interleaved with string
319 // pieces. (Every argument is preceded by a string piece.)
320 args: &'a [ArgumentV1<'a>],
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<'a> Debug for Arguments<'a> {
325 fn fmt(&self, fmt: &mut Formatter) -> Result {
326 Display::fmt(self, fmt)
330 #[stable(feature = "rust1", since = "1.0.0")]
331 impl<'a> Display for Arguments<'a> {
332 fn fmt(&self, fmt: &mut Formatter) -> Result {
333 write(fmt.buf, *self)
337 /// Format trait for the `?` character.
339 /// `Debug` should format the output in a programmer-facing, debugging context.
341 /// Generally speaking, you should just `derive` a `Debug` implementation.
343 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
345 /// For more information on formatters, see [the module-level documentation][module].
347 /// [module]: ../../std/fmt/index.html
349 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
350 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
351 /// comma-separated list of each field's name and `Debug` value, then `}`. For
352 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
353 /// `Debug` values of the fields, then `)`.
357 /// Deriving an implementation:
366 /// let origin = Point { x: 0, y: 0 };
368 /// println!("The origin is: {:?}", origin);
371 /// Manually implementing:
381 /// impl fmt::Debug for Point {
382 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
383 /// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
387 /// let origin = Point { x: 0, y: 0 };
389 /// println!("The origin is: {:?}", origin);
395 /// The origin is: Point { x: 0, y: 0 }
398 /// There are a number of `debug_*` methods on `Formatter` to help you with manual
399 /// implementations, such as [`debug_struct`][debug_struct].
401 /// `Debug` implementations using either `derive` or the debug builder API
402 /// on `Formatter` support pretty printing using the alternate flag: `{:#?}`.
404 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
406 /// Pretty printing with `#?`:
415 /// let origin = Point { x: 0, y: 0 };
417 /// println!("The origin is: {:#?}", origin);
423 /// The origin is: Point {
428 #[stable(feature = "rust1", since = "1.0.0")]
429 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
430 defined in your crate, add `#[derive(Debug)]` or \
431 manually implement it"]
432 #[lang = "debug_trait"]
434 /// Formats the value using the given formatter.
435 #[stable(feature = "rust1", since = "1.0.0")]
436 fn fmt(&self, &mut Formatter) -> Result;
439 /// Format trait for an empty format, `{}`.
441 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
442 /// output, and so cannot be derived.
444 /// [debug]: trait.Debug.html
446 /// For more information on formatters, see [the module-level documentation][module].
448 /// [module]: ../../std/fmt/index.html
452 /// Implementing `Display` on a type:
462 /// impl fmt::Display for Point {
463 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
464 /// write!(f, "({}, {})", self.x, self.y)
468 /// let origin = Point { x: 0, y: 0 };
470 /// println!("The origin is: {}", origin);
472 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
473 formatter; try using `:?` instead if you are using \
475 #[stable(feature = "rust1", since = "1.0.0")]
477 /// Formats the value using the given formatter.
478 #[stable(feature = "rust1", since = "1.0.0")]
479 fn fmt(&self, &mut Formatter) -> Result;
482 /// Format trait for the `o` character.
484 /// The `Octal` trait should format its output as a number in base-8.
486 /// The alternate flag, `#`, adds a `0o` in front of the output.
488 /// For more information on formatters, see [the module-level documentation][module].
490 /// [module]: ../../std/fmt/index.html
494 /// Basic usage with `i32`:
497 /// let x = 42; // 42 is '52' in octal
499 /// assert_eq!(format!("{:o}", x), "52");
500 /// assert_eq!(format!("{:#o}", x), "0o52");
503 /// Implementing `Octal` on a type:
508 /// struct Length(i32);
510 /// impl fmt::Octal for Length {
511 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
512 /// let val = self.0;
514 /// write!(f, "{:o}", val) // delegate to i32's implementation
518 /// let l = Length(9);
520 /// println!("l as octal is: {:o}", l);
522 #[stable(feature = "rust1", since = "1.0.0")]
524 /// Formats the value using the given formatter.
525 #[stable(feature = "rust1", since = "1.0.0")]
526 fn fmt(&self, &mut Formatter) -> Result;
529 /// Format trait for the `b` character.
531 /// The `Binary` trait should format its output as a number in binary.
533 /// The alternate flag, `#`, adds a `0b` in front of the output.
535 /// For more information on formatters, see [the module-level documentation][module].
537 /// [module]: ../../std/fmt/index.html
541 /// Basic usage with `i32`:
544 /// let x = 42; // 42 is '101010' in binary
546 /// assert_eq!(format!("{:b}", x), "101010");
547 /// assert_eq!(format!("{:#b}", x), "0b101010");
550 /// Implementing `Binary` on a type:
555 /// struct Length(i32);
557 /// impl fmt::Binary for Length {
558 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
559 /// let val = self.0;
561 /// write!(f, "{:b}", val) // delegate to i32's implementation
565 /// let l = Length(107);
567 /// println!("l as binary is: {:b}", l);
569 #[stable(feature = "rust1", since = "1.0.0")]
571 /// Formats the value using the given formatter.
572 #[stable(feature = "rust1", since = "1.0.0")]
573 fn fmt(&self, &mut Formatter) -> Result;
576 /// Format trait for the `x` character.
578 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
581 /// The alternate flag, `#`, adds a `0x` in front of the output.
583 /// For more information on formatters, see [the module-level documentation][module].
585 /// [module]: ../../std/fmt/index.html
589 /// Basic usage with `i32`:
592 /// let x = 42; // 42 is '2a' in hex
594 /// assert_eq!(format!("{:x}", x), "2a");
595 /// assert_eq!(format!("{:#x}", x), "0x2a");
598 /// Implementing `LowerHex` on a type:
603 /// struct Length(i32);
605 /// impl fmt::LowerHex for Length {
606 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
607 /// let val = self.0;
609 /// write!(f, "{:x}", val) // delegate to i32's implementation
613 /// let l = Length(9);
615 /// println!("l as hex is: {:x}", l);
617 #[stable(feature = "rust1", since = "1.0.0")]
619 /// Formats the value using the given formatter.
620 #[stable(feature = "rust1", since = "1.0.0")]
621 fn fmt(&self, &mut Formatter) -> Result;
624 /// Format trait for the `X` character.
626 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
629 /// The alternate flag, `#`, adds a `0x` in front of the output.
631 /// For more information on formatters, see [the module-level documentation][module].
633 /// [module]: ../../std/fmt/index.html
637 /// Basic usage with `i32`:
640 /// let x = 42; // 42 is '2A' in hex
642 /// assert_eq!(format!("{:X}", x), "2A");
643 /// assert_eq!(format!("{:#X}", x), "0x2A");
646 /// Implementing `UpperHex` on a type:
651 /// struct Length(i32);
653 /// impl fmt::UpperHex for Length {
654 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
655 /// let val = self.0;
657 /// write!(f, "{:X}", val) // delegate to i32's implementation
661 /// let l = Length(9);
663 /// println!("l as hex is: {:X}", l);
665 #[stable(feature = "rust1", since = "1.0.0")]
667 /// Formats the value using the given formatter.
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn fmt(&self, &mut Formatter) -> Result;
672 /// Format trait for the `p` character.
674 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
677 /// For more information on formatters, see [the module-level documentation][module].
679 /// [module]: ../../std/fmt/index.html
683 /// Basic usage with `&i32`:
688 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
691 /// Implementing `Pointer` on a type:
696 /// struct Length(i32);
698 /// impl fmt::Pointer for Length {
699 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
700 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
702 /// write!(f, "{:p}", self as *const Length)
706 /// let l = Length(42);
708 /// println!("l is in memory here: {:p}", l);
710 #[stable(feature = "rust1", since = "1.0.0")]
712 /// Formats the value using the given formatter.
713 #[stable(feature = "rust1", since = "1.0.0")]
714 fn fmt(&self, &mut Formatter) -> Result;
717 /// Format trait for the `e` character.
719 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
721 /// For more information on formatters, see [the module-level documentation][module].
723 /// [module]: ../../std/fmt/index.html
727 /// Basic usage with `i32`:
730 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
732 /// assert_eq!(format!("{:e}", x), "4.2e1");
735 /// Implementing `LowerExp` on a type:
740 /// struct Length(i32);
742 /// impl fmt::LowerExp for Length {
743 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
744 /// let val = self.0;
745 /// write!(f, "{}e1", val / 10)
749 /// let l = Length(100);
751 /// println!("l in scientific notation is: {:e}", l);
753 #[stable(feature = "rust1", since = "1.0.0")]
755 /// Formats the value using the given formatter.
756 #[stable(feature = "rust1", since = "1.0.0")]
757 fn fmt(&self, &mut Formatter) -> Result;
760 /// Format trait for the `E` character.
762 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
764 /// For more information on formatters, see [the module-level documentation][module].
766 /// [module]: ../../std/fmt/index.html
770 /// Basic usage with `f32`:
773 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
775 /// assert_eq!(format!("{:E}", x), "4.2E1");
778 /// Implementing `UpperExp` on a type:
783 /// struct Length(i32);
785 /// impl fmt::UpperExp for Length {
786 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
787 /// let val = self.0;
788 /// write!(f, "{}E1", val / 10)
792 /// let l = Length(100);
794 /// println!("l in scientific notation is: {:E}", l);
796 #[stable(feature = "rust1", since = "1.0.0")]
798 /// Formats the value using the given formatter.
799 #[stable(feature = "rust1", since = "1.0.0")]
800 fn fmt(&self, &mut Formatter) -> Result;
803 /// The `write` function takes an output stream, a precompiled format string,
804 /// and a list of arguments. The arguments will be formatted according to the
805 /// specified format string into the output stream provided.
809 /// * output - the buffer to write output to
810 /// * args - the precompiled arguments generated by `format_args!`
819 /// let mut output = String::new();
820 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
821 /// .expect("Error occurred while trying to write in String");
822 /// assert_eq!(output, "Hello world!");
825 /// Please note that using [`write!`] might be preferrable. Example:
828 /// use std::fmt::Write;
830 /// let mut output = String::new();
831 /// write!(&mut output, "Hello {}!", "world")
832 /// .expect("Error occurred while trying to write in String");
833 /// assert_eq!(output, "Hello world!");
836 /// [`write!`]: ../../std/macro.write.html
837 #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn write(output: &mut Write, args: Arguments) -> Result {
839 let mut formatter = Formatter {
844 align: rt::v1::Alignment::Unknown,
847 curarg: args.args.iter(),
850 let mut pieces = args.pieces.iter();
854 // We can use default formatting parameters for all arguments.
855 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
856 formatter.buf.write_str(*piece)?;
857 (arg.formatter)(arg.value, &mut formatter)?;
861 // Every spec has a corresponding argument that is preceded by
863 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
864 formatter.buf.write_str(*piece)?;
870 // There can be only one trailing string piece left.
871 if let Some(piece) = pieces.next() {
872 formatter.buf.write_str(*piece)?;
878 impl<'a> Formatter<'a> {
880 // First up is the collection of functions used to execute a format string
881 // at runtime. This consumes all of the compile-time statics generated by
882 // the format! syntax extension.
883 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
884 // Fill in the format parameters into the formatter
885 self.fill = arg.format.fill;
886 self.align = arg.format.align;
887 self.flags = arg.format.flags;
888 self.width = self.getcount(&arg.format.width);
889 self.precision = self.getcount(&arg.format.precision);
891 // Extract the correct argument
892 let value = match arg.position {
893 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
894 rt::v1::Position::At(i) => self.args[i],
897 // Then actually do some printing
898 (value.formatter)(value.value, self)
901 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
903 rt::v1::Count::Is(n) => Some(n),
904 rt::v1::Count::Implied => None,
905 rt::v1::Count::Param(i) => {
906 self.args[i].as_usize()
908 rt::v1::Count::NextParam => {
909 self.curarg.next().and_then(|arg| arg.as_usize())
914 // Helper methods used for padding and processing formatting arguments that
915 // all formatting traits can use.
917 /// Performs the correct padding for an integer which has already been
918 /// emitted into a str. The str should *not* contain the sign for the
919 /// integer, that will be added by this method.
923 /// * is_nonnegative - whether the original integer was either positive or zero.
924 /// * prefix - if the '#' character (Alternate) is provided, this
925 /// is the prefix to put in front of the number.
926 /// * buf - the byte array that the number has been formatted into
928 /// This function will correctly account for the flags provided as well as
929 /// the minimum width. It will not take precision into account.
930 #[stable(feature = "rust1", since = "1.0.0")]
931 pub fn pad_integral(&mut self,
932 is_nonnegative: bool,
936 let mut width = buf.len();
940 sign = Some('-'); width += 1;
941 } else if self.sign_plus() {
942 sign = Some('+'); width += 1;
945 let mut prefixed = false;
946 if self.alternate() {
947 prefixed = true; width += prefix.chars().count();
950 // Writes the sign if it exists, and then the prefix if it was requested
951 let write_prefix = |f: &mut Formatter| {
952 if let Some(c) = sign {
953 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
955 if prefixed { f.buf.write_str(prefix) }
959 // The `width` field is more of a `min-width` parameter at this point.
961 // If there's no minimum length requirements then we can just
964 write_prefix(self)?; self.buf.write_str(buf)
966 // Check if we're over the minimum width, if so then we can also
967 // just write the bytes.
968 Some(min) if width >= min => {
969 write_prefix(self)?; self.buf.write_str(buf)
971 // The sign and prefix goes before the padding if the fill character
973 Some(min) if self.sign_aware_zero_pad() => {
976 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
980 // Otherwise, the sign and prefix goes after the padding
982 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
983 write_prefix(f)?; f.buf.write_str(buf)
989 /// This function takes a string slice and emits it to the internal buffer
990 /// after applying the relevant formatting flags specified. The flags
991 /// recognized for generic strings are:
993 /// * width - the minimum width of what to emit
994 /// * fill/align - what to emit and where to emit it if the string
995 /// provided needs to be padded
996 /// * precision - the maximum length to emit, the string is truncated if it
997 /// is longer than this length
999 /// Notably this function ignored the `flag` parameters
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 pub fn pad(&mut self, s: &str) -> Result {
1002 // Make sure there's a fast path up front
1003 if self.width.is_none() && self.precision.is_none() {
1004 return self.buf.write_str(s);
1006 // The `precision` field can be interpreted as a `max-width` for the
1007 // string being formatted.
1008 let s = if let Some(max) = self.precision {
1009 // If our string is longer that the precision, then we must have
1010 // truncation. However other flags like `fill`, `width` and `align`
1011 // must act as always.
1012 if let Some((i, _)) = s.char_indices().skip(max).next() {
1020 // The `width` field is more of a `min-width` parameter at this point.
1022 // If we're under the maximum length, and there's no minimum length
1023 // requirements, then we can just emit the string
1024 None => self.buf.write_str(s),
1025 // If we're under the maximum width, check if we're over the minimum
1026 // width, if so it's as easy as just emitting the string.
1027 Some(width) if s.chars().count() >= width => {
1028 self.buf.write_str(s)
1030 // If we're under both the maximum and the minimum width, then fill
1031 // up the minimum width with the specified string + some alignment.
1033 let align = rt::v1::Alignment::Left;
1034 self.with_padding(width - s.chars().count(), align, |me| {
1041 /// Runs a callback, emitting the correct padding either before or
1042 /// afterwards depending on whether right or left alignment is requested.
1043 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
1045 where F: FnOnce(&mut Formatter) -> Result,
1047 let align = match self.align {
1048 rt::v1::Alignment::Unknown => default,
1052 let (pre_pad, post_pad) = match align {
1053 rt::v1::Alignment::Left => (0, padding),
1054 rt::v1::Alignment::Right |
1055 rt::v1::Alignment::Unknown => (padding, 0),
1056 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1059 let mut fill = [0; 4];
1060 let fill = self.fill.encode_utf8(&mut fill);
1062 for _ in 0..pre_pad {
1063 self.buf.write_str(fill)?;
1068 for _ in 0..post_pad {
1069 self.buf.write_str(fill)?;
1075 /// Takes the formatted parts and applies the padding.
1076 /// Assumes that the caller already has rendered the parts with required precision,
1077 /// so that `self.precision` can be ignored.
1078 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1079 if let Some(mut width) = self.width {
1080 // for the sign-aware zero padding, we render the sign first and
1081 // behave as if we had no sign from the beginning.
1082 let mut formatted = formatted.clone();
1083 let mut align = self.align;
1084 let old_fill = self.fill;
1085 if self.sign_aware_zero_pad() {
1086 // a sign always goes first
1087 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1088 self.buf.write_str(sign)?;
1090 // remove the sign from the formatted parts
1091 formatted.sign = b"";
1092 width = if width < sign.len() { 0 } else { width - sign.len() };
1093 align = rt::v1::Alignment::Right;
1097 // remaining parts go through the ordinary padding process.
1098 let len = formatted.len();
1099 let ret = if width <= len { // no padding
1100 self.write_formatted_parts(&formatted)
1102 self.with_padding(width - len, align, |f| {
1103 f.write_formatted_parts(&formatted)
1106 self.fill = old_fill;
1109 // this is the common case and we take a shortcut
1110 self.write_formatted_parts(formatted)
1114 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1115 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1116 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1119 if !formatted.sign.is_empty() {
1120 write_bytes(self.buf, formatted.sign)?;
1122 for part in formatted.parts {
1124 flt2dec::Part::Zero(mut nzeroes) => {
1125 const ZEROES: &'static str = // 64 zeroes
1126 "0000000000000000000000000000000000000000000000000000000000000000";
1127 while nzeroes > ZEROES.len() {
1128 self.buf.write_str(ZEROES)?;
1129 nzeroes -= ZEROES.len();
1132 self.buf.write_str(&ZEROES[..nzeroes])?;
1135 flt2dec::Part::Num(mut v) => {
1137 let len = part.len();
1138 for c in s[..len].iter_mut().rev() {
1139 *c = b'0' + (v % 10) as u8;
1142 write_bytes(self.buf, &s[..len])?;
1144 flt2dec::Part::Copy(buf) => {
1145 write_bytes(self.buf, buf)?;
1152 /// Writes some data to the underlying buffer contained within this
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 pub fn write_str(&mut self, data: &str) -> Result {
1156 self.buf.write_str(data)
1159 /// Writes some formatted information into this instance
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1162 write(self.buf, fmt)
1165 /// Flags for formatting (packed version of rt::Flag)
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 pub fn flags(&self) -> u32 { self.flags }
1169 /// Character used as 'fill' whenever there is alignment
1170 #[stable(feature = "fmt_flags", since = "1.5.0")]
1171 pub fn fill(&self) -> char { self.fill }
1173 /// Flag indicating what form of alignment was requested
1174 #[unstable(feature = "fmt_flags_align", reason = "method was just created",
1176 pub fn align(&self) -> Alignment {
1178 rt::v1::Alignment::Left => Alignment::Left,
1179 rt::v1::Alignment::Right => Alignment::Right,
1180 rt::v1::Alignment::Center => Alignment::Center,
1181 rt::v1::Alignment::Unknown => Alignment::Unknown,
1185 /// Optionally specified integer width that the output should be
1186 #[stable(feature = "fmt_flags", since = "1.5.0")]
1187 pub fn width(&self) -> Option<usize> { self.width }
1189 /// Optionally specified precision for numeric types
1190 #[stable(feature = "fmt_flags", since = "1.5.0")]
1191 pub fn precision(&self) -> Option<usize> { self.precision }
1193 /// Determines if the `+` flag was specified.
1194 #[stable(feature = "fmt_flags", since = "1.5.0")]
1195 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1197 /// Determines if the `-` flag was specified.
1198 #[stable(feature = "fmt_flags", since = "1.5.0")]
1199 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1201 /// Determines if the `#` flag was specified.
1202 #[stable(feature = "fmt_flags", since = "1.5.0")]
1203 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1205 /// Determines if the `0` flag was specified.
1206 #[stable(feature = "fmt_flags", since = "1.5.0")]
1207 pub fn sign_aware_zero_pad(&self) -> bool {
1208 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1211 /// Creates a `DebugStruct` builder designed to assist with creation of
1212 /// `fmt::Debug` implementations for structs.
1224 /// impl fmt::Debug for Foo {
1225 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1226 /// fmt.debug_struct("Foo")
1227 /// .field("bar", &self.bar)
1228 /// .field("baz", &self.baz)
1233 /// // prints "Foo { bar: 10, baz: "Hello World" }"
1234 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1236 #[stable(feature = "debug_builders", since = "1.2.0")]
1238 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1239 builders::debug_struct_new(self, name)
1242 /// Creates a `DebugTuple` builder designed to assist with creation of
1243 /// `fmt::Debug` implementations for tuple structs.
1250 /// struct Foo(i32, String);
1252 /// impl fmt::Debug for Foo {
1253 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1254 /// fmt.debug_tuple("Foo")
1261 /// // prints "Foo(10, "Hello World")"
1262 /// println!("{:?}", Foo(10, "Hello World".to_string()));
1264 #[stable(feature = "debug_builders", since = "1.2.0")]
1266 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1267 builders::debug_tuple_new(self, name)
1270 /// Creates a `DebugList` builder designed to assist with creation of
1271 /// `fmt::Debug` implementations for list-like structures.
1278 /// struct Foo(Vec<i32>);
1280 /// impl fmt::Debug for Foo {
1281 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1282 /// fmt.debug_list().entries(self.0.iter()).finish()
1286 /// // prints "[10, 11]"
1287 /// println!("{:?}", Foo(vec![10, 11]));
1289 #[stable(feature = "debug_builders", since = "1.2.0")]
1291 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1292 builders::debug_list_new(self)
1295 /// Creates a `DebugSet` builder designed to assist with creation of
1296 /// `fmt::Debug` implementations for set-like structures.
1303 /// struct Foo(Vec<i32>);
1305 /// impl fmt::Debug for Foo {
1306 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1307 /// fmt.debug_set().entries(self.0.iter()).finish()
1311 /// // prints "{10, 11}"
1312 /// println!("{:?}", Foo(vec![10, 11]));
1314 #[stable(feature = "debug_builders", since = "1.2.0")]
1316 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1317 builders::debug_set_new(self)
1320 /// Creates a `DebugMap` builder designed to assist with creation of
1321 /// `fmt::Debug` implementations for map-like structures.
1328 /// struct Foo(Vec<(String, i32)>);
1330 /// impl fmt::Debug for Foo {
1331 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1332 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1336 /// // prints "{"A": 10, "B": 11}"
1337 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1339 #[stable(feature = "debug_builders", since = "1.2.0")]
1341 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1342 builders::debug_map_new(self)
1346 #[stable(since = "1.2.0", feature = "formatter_write")]
1347 impl<'a> Write for Formatter<'a> {
1348 fn write_str(&mut self, s: &str) -> Result {
1349 self.buf.write_str(s)
1352 fn write_char(&mut self, c: char) -> Result {
1353 self.buf.write_char(c)
1356 fn write_fmt(&mut self, args: Arguments) -> Result {
1357 write(self.buf, args)
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 impl Display for Error {
1363 fn fmt(&self, f: &mut Formatter) -> Result {
1364 Display::fmt("an error occurred when formatting an argument", f)
1368 // Implementations of the core formatting traits
1370 macro_rules! fmt_refs {
1371 ($($tr:ident),*) => {
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 impl<'a, T: ?Sized + $tr> $tr for &'a T {
1375 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1379 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1385 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1387 #[unstable(feature = "never_type_impls", issue = "35121")]
1389 fn fmt(&self, _: &mut Formatter) -> Result {
1394 #[unstable(feature = "never_type_impls", issue = "35121")]
1395 impl Display for ! {
1396 fn fmt(&self, _: &mut Formatter) -> Result {
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl Debug for bool {
1403 fn fmt(&self, f: &mut Formatter) -> Result {
1404 Display::fmt(self, f)
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 impl Display for bool {
1410 fn fmt(&self, f: &mut Formatter) -> Result {
1411 Display::fmt(if *self { "true" } else { "false" }, f)
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 impl Debug for str {
1417 fn fmt(&self, f: &mut Formatter) -> Result {
1420 for (i, c) in self.char_indices() {
1421 let esc = c.escape_debug();
1422 // If char needs escaping, flush backlog so far and write, else skip
1424 f.write_str(&self[from..i])?;
1428 from = i + c.len_utf8();
1431 f.write_str(&self[from..])?;
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 impl Display for str {
1438 fn fmt(&self, f: &mut Formatter) -> Result {
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl Debug for char {
1445 fn fmt(&self, f: &mut Formatter) -> Result {
1446 f.write_char('\'')?;
1447 for c in self.escape_debug() {
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 impl Display for char {
1456 fn fmt(&self, f: &mut Formatter) -> Result {
1457 if f.width.is_none() && f.precision.is_none() {
1460 f.pad(self.encode_utf8(&mut [0; 4]))
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 impl<T: ?Sized> Pointer for *const T {
1467 fn fmt(&self, f: &mut Formatter) -> Result {
1468 let old_width = f.width;
1469 let old_flags = f.flags;
1471 // The alternate flag is already treated by LowerHex as being special-
1472 // it denotes whether to prefix with 0x. We use it to work out whether
1473 // or not to zero extend, and then unconditionally set it to get the
1476 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1478 if let None = f.width {
1479 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
1482 f.flags |= 1 << (FlagV1::Alternate as u32);
1484 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
1486 f.width = old_width;
1487 f.flags = old_flags;
1493 #[stable(feature = "rust1", since = "1.0.0")]
1494 impl<T: ?Sized> Pointer for *mut T {
1495 fn fmt(&self, f: &mut Formatter) -> Result {
1496 Pointer::fmt(&(*self as *const T), f)
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 impl<'a, T: ?Sized> Pointer for &'a T {
1502 fn fmt(&self, f: &mut Formatter) -> Result {
1503 Pointer::fmt(&(*self as *const T), f)
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 impl<'a, T: ?Sized> Pointer for &'a mut T {
1509 fn fmt(&self, f: &mut Formatter) -> Result {
1510 Pointer::fmt(&(&**self as *const T), f)
1514 // Common code of floating point Debug and Display.
1515 fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
1516 where T: flt2dec::DecodableFloat
1518 let force_sign = fmt.sign_plus();
1519 let sign = match (force_sign, negative_zero) {
1520 (false, false) => flt2dec::Sign::Minus,
1521 (false, true) => flt2dec::Sign::MinusRaw,
1522 (true, false) => flt2dec::Sign::MinusPlus,
1523 (true, true) => flt2dec::Sign::MinusPlusRaw,
1526 let mut buf = [0; 1024]; // enough for f32 and f64
1527 let mut parts = [flt2dec::Part::Zero(0); 16];
1528 let formatted = if let Some(precision) = fmt.precision {
1529 flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1530 precision, false, &mut buf, &mut parts)
1532 flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1533 0, false, &mut buf, &mut parts)
1535 fmt.pad_formatted_parts(&formatted)
1538 // Common code of floating point LowerExp and UpperExp.
1539 fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
1540 where T: flt2dec::DecodableFloat
1542 let force_sign = fmt.sign_plus();
1543 let sign = match force_sign {
1544 false => flt2dec::Sign::Minus,
1545 true => flt2dec::Sign::MinusPlus,
1548 let mut buf = [0; 1024]; // enough for f32 and f64
1549 let mut parts = [flt2dec::Part::Zero(0); 16];
1550 let formatted = if let Some(precision) = fmt.precision {
1551 // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1552 flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1553 precision + 1, upper, &mut buf, &mut parts)
1555 flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1556 (0, 0), upper, &mut buf, &mut parts)
1558 fmt.pad_formatted_parts(&formatted)
1561 macro_rules! floating { ($ty:ident) => {
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 impl Debug for $ty {
1565 fn fmt(&self, fmt: &mut Formatter) -> Result {
1566 float_to_decimal_common(fmt, self, true)
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 impl Display for $ty {
1572 fn fmt(&self, fmt: &mut Formatter) -> Result {
1573 float_to_decimal_common(fmt, self, false)
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl LowerExp for $ty {
1579 fn fmt(&self, fmt: &mut Formatter) -> Result {
1580 float_to_exponential_common(fmt, self, false)
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 impl UpperExp for $ty {
1586 fn fmt(&self, fmt: &mut Formatter) -> Result {
1587 float_to_exponential_common(fmt, self, true)
1594 // Implementation of Display/Debug for various core types
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl<T: ?Sized> Debug for *const T {
1598 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl<T: ?Sized> Debug for *mut T {
1602 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1606 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1609 macro_rules! tuple {
1611 ( $($name:ident,)+ ) => (
1612 #[stable(feature = "rust1", since = "1.0.0")]
1613 impl<$($name:Debug),*> Debug for ($($name,)*) {
1614 #[allow(non_snake_case, unused_assignments, deprecated)]
1615 fn fmt(&self, f: &mut Formatter) -> Result {
1616 let mut builder = f.debug_tuple("");
1617 let ($(ref $name,)*) = *self;
1619 builder.field($name);
1625 peel! { $($name,)* }
1629 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 impl<T: Debug> Debug for [T] {
1633 fn fmt(&self, f: &mut Formatter) -> Result {
1634 f.debug_list().entries(self.iter()).finish()
1638 #[stable(feature = "rust1", since = "1.0.0")]
1640 fn fmt(&self, f: &mut Formatter) -> Result {
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 impl<T: ?Sized> Debug for PhantomData<T> {
1646 fn fmt(&self, f: &mut Formatter) -> Result {
1647 f.pad("PhantomData")
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 impl<T: Copy + Debug> Debug for Cell<T> {
1653 fn fmt(&self, f: &mut Formatter) -> Result {
1654 f.debug_struct("Cell")
1655 .field("value", &self.get())
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1662 fn fmt(&self, f: &mut Formatter) -> Result {
1663 match self.try_borrow() {
1665 f.debug_struct("RefCell")
1666 .field("value", &borrow)
1670 f.debug_struct("RefCell")
1671 .field("value", &"<borrowed>")
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1680 fn fmt(&self, f: &mut Formatter) -> Result {
1681 Debug::fmt(&**self, f)
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1687 fn fmt(&self, f: &mut Formatter) -> Result {
1688 Debug::fmt(&*(self.deref()), f)
1692 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1693 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
1694 fn fmt(&self, f: &mut Formatter) -> Result {
1699 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1700 // it's a lot easier than creating all of the rt::Piece structures here.