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")]
17 use cell::{Cell, RefCell, Ref, RefMut, BorrowState};
18 use marker::PhantomData;
26 #[unstable(feature = "fmt_flags_align", issue = "27726")]
27 /// Possible alignments returned by `Formatter::align`
29 /// Indication that contents should be left-aligned.
31 /// Indication that contents should be right-aligned.
33 /// Indication that contents should be center-aligned.
35 /// No alignment was requested.
39 #[stable(feature = "debug_builders", since = "1.2.0")]
40 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
45 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
52 #[stable(feature = "rust1", since = "1.0.0")]
53 /// The type returned by formatter methods.
54 pub type Result = result::Result<(), Error>;
56 /// The error type which is returned from formatting a message into a stream.
58 /// This type does not support transmission of an error other than that an error
59 /// occurred. Any extra information must be arranged to be transmitted through
61 #[stable(feature = "rust1", since = "1.0.0")]
62 #[derive(Copy, Clone, Debug)]
65 /// A collection of methods that are required to format a message into a stream.
67 /// This trait is the type which this modules requires when formatting
68 /// information. This is similar to the standard library's `io::Write` trait,
69 /// but it is only intended for use in libcore.
71 /// This trait should generally not be implemented by consumers of the standard
72 /// library. The `write!` macro accepts an instance of `io::Write`, and the
73 /// `io::Write` trait is favored over implementing this trait.
74 #[stable(feature = "rust1", since = "1.0.0")]
76 /// Writes a slice of bytes into this writer, returning whether the write
79 /// This method can only succeed if the entire byte slice was successfully
80 /// written, and this method will not return until all data has been
81 /// written or an error occurs.
85 /// This function will return an instance of `Error` on error.
86 #[stable(feature = "rust1", since = "1.0.0")]
87 fn write_str(&mut self, s: &str) -> Result;
89 /// Writes a `char` into this writer, returning whether the write succeeded.
91 /// A single `char` may be encoded as more than one byte.
92 /// This method can only succeed if the entire byte sequence was successfully
93 /// written, and this method will not return until all data has been
94 /// written or an error occurs.
98 /// This function will return an instance of `Error` on error.
99 #[stable(feature = "fmt_write_char", since = "1.1.0")]
100 fn write_char(&mut self, c: char) -> Result {
101 let mut utf_8 = [0u8; 4];
102 let bytes_written = c.encode_utf8(&mut utf_8).unwrap_or(0);
103 self.write_str(unsafe { str::from_utf8_unchecked(&utf_8[..bytes_written]) })
106 /// Glue for usage of the `write!` macro with implementors of this trait.
108 /// This method should generally not be invoked manually, but rather through
109 /// the `write!` macro itself.
110 #[stable(feature = "rust1", since = "1.0.0")]
111 fn write_fmt(&mut self, args: Arguments) -> Result {
112 // This Adapter is needed to allow `self` (of type `&mut
113 // Self`) to be cast to a Write (below) without
114 // requiring a `Sized` bound.
115 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
117 impl<'a, T: ?Sized> Write for Adapter<'a, T>
120 fn write_str(&mut self, s: &str) -> Result {
124 fn write_char(&mut self, c: char) -> Result {
128 fn write_fmt(&mut self, args: Arguments) -> Result {
129 self.0.write_fmt(args)
133 write(&mut Adapter(self), args)
137 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
138 impl<'a, W: Write + ?Sized> Write for &'a mut W {
139 fn write_str(&mut self, s: &str) -> Result {
140 (**self).write_str(s)
143 fn write_char(&mut self, c: char) -> Result {
144 (**self).write_char(c)
147 fn write_fmt(&mut self, args: Arguments) -> Result {
148 (**self).write_fmt(args)
152 /// A struct to represent both where to emit formatting strings to and how they
153 /// should be formatted. A mutable version of this is passed to all formatting
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub struct Formatter<'a> {
159 align: rt::v1::Alignment,
160 width: Option<usize>,
161 precision: Option<usize>,
163 buf: &'a mut (Write+'a),
164 curarg: slice::Iter<'a, ArgumentV1<'a>>,
165 args: &'a [ArgumentV1<'a>],
168 // NB. Argument is essentially an optimized partially applied formatting function,
169 // 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 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
181 pub struct ArgumentV1<'a> {
183 formatter: fn(&Void, &mut Formatter) -> Result,
186 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
188 impl<'a> Clone for ArgumentV1<'a> {
189 fn clone(&self) -> ArgumentV1<'a> {
194 impl<'a> ArgumentV1<'a> {
196 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
201 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
203 pub fn new<'b, T>(x: &'b T,
204 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
207 formatter: mem::transmute(f),
208 value: mem::transmute(x)
214 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
216 pub fn from_usize(x: &usize) -> ArgumentV1 {
217 ArgumentV1::new(x, ArgumentV1::show_usize)
220 fn as_usize(&self) -> Option<usize> {
221 if self.formatter as usize == ArgumentV1::show_usize as usize {
222 Some(unsafe { *(self.value as *const _ as *const usize) })
229 // flags available in the v1 format of format_args
230 #[derive(Copy, Clone)]
231 #[allow(dead_code)] // SignMinus isn't currently used
232 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
234 impl<'a> Arguments<'a> {
235 /// When using the format_args!() macro, this function is used to generate the
236 /// Arguments structure.
237 #[doc(hidden)] #[inline]
238 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
240 pub fn new_v1(pieces: &'a [&'a str],
241 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
249 /// This function is used to specify nonstandard formatting parameters.
250 /// The `pieces` array must be at least as long as `fmt` to construct
251 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
252 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
253 /// created with `argumentusize`. However, failing to do so doesn't cause
254 /// unsafety, but will ignore invalid .
255 #[doc(hidden)] #[inline]
256 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
258 pub fn new_v1_formatted(pieces: &'a [&'a str],
259 args: &'a [ArgumentV1<'a>],
260 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
269 /// This structure represents a safely precompiled version of a format string
270 /// and its arguments. This cannot be generated at runtime because it cannot
271 /// safely be done so, so no constructors are given and the fields are private
272 /// to prevent modification.
274 /// The `format_args!` macro will safely create an instance of this structure
275 /// and pass it to a function or closure, passed as the first argument. The
276 /// macro validates the format string at compile-time so usage of the `write`
277 /// and `format` functions can be safely performed.
278 #[stable(feature = "rust1", since = "1.0.0")]
279 #[derive(Copy, Clone)]
280 pub struct Arguments<'a> {
281 // Format string pieces to print.
282 pieces: &'a [&'a str],
284 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
285 fmt: Option<&'a [rt::v1::Argument]>,
287 // Dynamic arguments for interpolation, to be interleaved with string
288 // pieces. (Every argument is preceded by a string piece.)
289 args: &'a [ArgumentV1<'a>],
292 #[stable(feature = "rust1", since = "1.0.0")]
293 impl<'a> Debug for Arguments<'a> {
294 fn fmt(&self, fmt: &mut Formatter) -> Result {
295 Display::fmt(self, fmt)
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl<'a> Display for Arguments<'a> {
301 fn fmt(&self, fmt: &mut Formatter) -> Result {
302 write(fmt.buf, *self)
306 /// Format trait for the `?` character.
308 /// `Debug` should format the output in a programmer-facing, debugging context.
310 /// Generally speaking, you should just `derive` a `Debug` implementation.
312 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
314 /// For more information on formatters, see [the module-level documentation][module].
316 /// [module]: ../../std/fmt/index.html
318 /// This trait can be used with `#[derive]`.
322 /// Deriving an implementation:
331 /// let origin = Point { x: 0, y: 0 };
333 /// println!("The origin is: {:?}", origin);
336 /// Manually implementing:
346 /// impl fmt::Debug for Point {
347 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
348 /// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
352 /// let origin = Point { x: 0, y: 0 };
354 /// println!("The origin is: {:?}", origin);
360 /// The origin is: Point { x: 0, y: 0 }
363 /// There are a number of `debug_*` methods on `Formatter` to help you with manual
364 /// implementations, such as [`debug_struct`][debug_struct].
366 /// `Debug` implementations using either `derive` or the debug builder API
367 /// on `Formatter` support pretty printing using the alternate flag: `{:#?}`.
369 /// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
371 /// Pretty printing with `#?`:
380 /// let origin = Point { x: 0, y: 0 };
382 /// println!("The origin is: {:#?}", origin);
388 /// The origin is: Point {
393 #[stable(feature = "rust1", since = "1.0.0")]
394 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
395 defined in your crate, add `#[derive(Debug)]` or \
396 manually implement it"]
397 #[lang = "debug_trait"]
399 /// Formats the value using the given formatter.
400 #[stable(feature = "rust1", since = "1.0.0")]
401 fn fmt(&self, &mut Formatter) -> Result;
404 /// Format trait for an empty format, `{}`.
406 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
407 /// output, and so cannot be derived.
409 /// [debug]: trait.Debug.html
411 /// For more information on formatters, see [the module-level documentation][module].
413 /// [module]: ../../std/fmt/index.html
417 /// Implementing `Display` on a type:
427 /// impl fmt::Display for Point {
428 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
429 /// write!(f, "({}, {})", self.x, self.y)
433 /// let origin = Point { x: 0, y: 0 };
435 /// println!("The origin is: {}", origin);
437 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
438 formatter; try using `:?` instead if you are using \
440 #[stable(feature = "rust1", since = "1.0.0")]
442 /// Formats the value using the given formatter.
443 #[stable(feature = "rust1", since = "1.0.0")]
444 fn fmt(&self, &mut Formatter) -> Result;
447 /// Format trait for the `o` character.
449 /// The `Octal` trait should format its output as a number in base-8.
451 /// The alternate flag, `#`, adds a `0o` in front of the output.
453 /// For more information on formatters, see [the module-level documentation][module].
455 /// [module]: ../../std/fmt/index.html
459 /// Basic usage with `i32`:
462 /// let x = 42; // 42 is '52' in octal
464 /// assert_eq!(format!("{:o}", x), "52");
465 /// assert_eq!(format!("{:#o}", x), "0o52");
468 /// Implementing `Octal` on a type:
473 /// struct Length(i32);
475 /// impl fmt::Octal for Length {
476 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
477 /// let val = self.0;
479 /// write!(f, "{:o}", val) // delegate to i32's implementation
483 /// let l = Length(9);
485 /// println!("l as octal is: {:o}", l);
487 #[stable(feature = "rust1", since = "1.0.0")]
489 /// Formats the value using the given formatter.
490 #[stable(feature = "rust1", since = "1.0.0")]
491 fn fmt(&self, &mut Formatter) -> Result;
494 /// Format trait for the `b` character.
496 /// The `Binary` trait should format its output as a number in binary.
498 /// The alternate flag, `#`, adds a `0b` in front of the output.
500 /// For more information on formatters, see [the module-level documentation][module].
502 /// [module]: ../../std/fmt/index.html
506 /// Basic usage with `i32`:
509 /// let x = 42; // 42 is '101010' in binary
511 /// assert_eq!(format!("{:b}", x), "101010");
512 /// assert_eq!(format!("{:#b}", x), "0b101010");
515 /// Implementing `Binary` on a type:
520 /// struct Length(i32);
522 /// impl fmt::Binary for Length {
523 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
524 /// let val = self.0;
526 /// write!(f, "{:b}", val) // delegate to i32's implementation
530 /// let l = Length(107);
532 /// println!("l as binary is: {:b}", l);
534 #[stable(feature = "rust1", since = "1.0.0")]
536 /// Formats the value using the given formatter.
537 #[stable(feature = "rust1", since = "1.0.0")]
538 fn fmt(&self, &mut Formatter) -> Result;
541 /// Format trait for the `x` character.
543 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
546 /// The alternate flag, `#`, adds a `0x` in front of the output.
548 /// For more information on formatters, see [the module-level documentation][module].
550 /// [module]: ../../std/fmt/index.html
554 /// Basic usage with `i32`:
557 /// let x = 42; // 42 is '2a' in hex
559 /// assert_eq!(format!("{:x}", x), "2a");
560 /// assert_eq!(format!("{:#x}", x), "0x2a");
563 /// Implementing `LowerHex` on a type:
568 /// struct Length(i32);
570 /// impl fmt::LowerHex for Length {
571 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
572 /// let val = self.0;
574 /// write!(f, "{:x}", val) // delegate to i32's implementation
578 /// let l = Length(9);
580 /// println!("l as hex is: {:x}", l);
582 #[stable(feature = "rust1", since = "1.0.0")]
584 /// Formats the value using the given formatter.
585 #[stable(feature = "rust1", since = "1.0.0")]
586 fn fmt(&self, &mut Formatter) -> Result;
589 /// Format trait for the `X` character.
591 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
594 /// The alternate flag, `#`, adds a `0x` in front of the output.
596 /// For more information on formatters, see [the module-level documentation][module].
598 /// [module]: ../../std/fmt/index.html
602 /// Basic usage with `i32`:
605 /// let x = 42; // 42 is '2A' in hex
607 /// assert_eq!(format!("{:X}", x), "2A");
608 /// assert_eq!(format!("{:#X}", x), "0x2A");
611 /// Implementing `UpperHex` on a type:
616 /// struct Length(i32);
618 /// impl fmt::UpperHex for Length {
619 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
620 /// let val = self.0;
622 /// write!(f, "{:X}", val) // delegate to i32's implementation
626 /// let l = Length(9);
628 /// println!("l as hex is: {:X}", l);
630 #[stable(feature = "rust1", since = "1.0.0")]
632 /// Formats the value using the given formatter.
633 #[stable(feature = "rust1", since = "1.0.0")]
634 fn fmt(&self, &mut Formatter) -> Result;
637 /// Format trait for the `p` character.
639 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
642 /// For more information on formatters, see [the module-level documentation][module].
644 /// [module]: ../../std/fmt/index.html
648 /// Basic usage with `&i32`:
653 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
656 /// Implementing `Pointer` on a type:
661 /// struct Length(i32);
663 /// impl fmt::Pointer for Length {
664 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
665 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
667 /// write!(f, "{:p}", self as *const Length)
671 /// let l = Length(42);
673 /// println!("l is in memory here: {:p}", l);
675 #[stable(feature = "rust1", since = "1.0.0")]
677 /// Formats the value using the given formatter.
678 #[stable(feature = "rust1", since = "1.0.0")]
679 fn fmt(&self, &mut Formatter) -> Result;
682 /// Format trait for the `e` character.
684 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
686 /// For more information on formatters, see [the module-level documentation][module].
688 /// [module]: ../../std/fmt/index.html
692 /// Basic usage with `i32`:
695 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
697 /// assert_eq!(format!("{:e}", x), "4.2e1");
700 /// Implementing `LowerExp` on a type:
705 /// struct Length(i32);
707 /// impl fmt::LowerExp for Length {
708 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
709 /// let val = self.0;
710 /// write!(f, "{}e1", val / 10)
714 /// let l = Length(100);
716 /// println!("l in scientific notation is: {:e}", l);
718 #[stable(feature = "rust1", since = "1.0.0")]
720 /// Formats the value using the given formatter.
721 #[stable(feature = "rust1", since = "1.0.0")]
722 fn fmt(&self, &mut Formatter) -> Result;
725 /// Format trait for the `E` character.
727 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
729 /// For more information on formatters, see [the module-level documentation][module].
731 /// [module]: ../../std/fmt/index.html
735 /// Basic usage with `f32`:
738 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
740 /// assert_eq!(format!("{:E}", x), "4.2E1");
743 /// Implementing `UpperExp` on a type:
748 /// struct Length(i32);
750 /// impl fmt::UpperExp for Length {
751 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
752 /// let val = self.0;
753 /// write!(f, "{}E1", val / 10)
757 /// let l = Length(100);
759 /// println!("l in scientific notation is: {:E}", l);
761 #[stable(feature = "rust1", since = "1.0.0")]
763 /// Formats the value using the given formatter.
764 #[stable(feature = "rust1", since = "1.0.0")]
765 fn fmt(&self, &mut Formatter) -> Result;
768 /// The `write` function takes an output stream, a precompiled format string,
769 /// and a list of arguments. The arguments will be formatted according to the
770 /// specified format string into the output stream provided.
774 /// * output - the buffer to write output to
775 /// * args - the precompiled arguments generated by `format_args!`
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn write(output: &mut Write, args: Arguments) -> Result {
778 let mut formatter = Formatter {
783 align: rt::v1::Alignment::Unknown,
786 curarg: args.args.iter(),
789 let mut pieces = args.pieces.iter();
793 // We can use default formatting parameters for all arguments.
794 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
795 try!(formatter.buf.write_str(*piece));
796 try!((arg.formatter)(arg.value, &mut formatter));
800 // Every spec has a corresponding argument that is preceded by
802 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
803 try!(formatter.buf.write_str(*piece));
804 try!(formatter.run(arg));
809 // There can be only one trailing string piece left.
810 match pieces.next() {
812 try!(formatter.buf.write_str(*piece));
820 impl<'a> Formatter<'a> {
822 // First up is the collection of functions used to execute a format string
823 // at runtime. This consumes all of the compile-time statics generated by
824 // the format! syntax extension.
825 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
826 // Fill in the format parameters into the formatter
827 self.fill = arg.format.fill;
828 self.align = arg.format.align;
829 self.flags = arg.format.flags;
830 self.width = self.getcount(&arg.format.width);
831 self.precision = self.getcount(&arg.format.precision);
833 // Extract the correct argument
834 let value = match arg.position {
835 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
836 rt::v1::Position::At(i) => self.args[i],
839 // Then actually do some printing
840 (value.formatter)(value.value, self)
843 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
845 rt::v1::Count::Is(n) => Some(n),
846 rt::v1::Count::Implied => None,
847 rt::v1::Count::Param(i) => {
848 self.args[i].as_usize()
850 rt::v1::Count::NextParam => {
851 self.curarg.next().and_then(|arg| arg.as_usize())
856 // Helper methods used for padding and processing formatting arguments that
857 // all formatting traits can use.
859 /// Performs the correct padding for an integer which has already been
860 /// emitted into a str. The str should *not* contain the sign for the
861 /// integer, that will be added by this method.
865 /// * is_nonnegative - whether the original integer was either positive or zero.
866 /// * prefix - if the '#' character (Alternate) is provided, this
867 /// is the prefix to put in front of the number.
868 /// * buf - the byte array that the number has been formatted into
870 /// This function will correctly account for the flags provided as well as
871 /// the minimum width. It will not take precision into account.
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn pad_integral(&mut self,
874 is_nonnegative: bool,
880 let mut width = buf.len();
884 sign = Some('-'); width += 1;
885 } else if self.sign_plus() {
886 sign = Some('+'); width += 1;
889 let mut prefixed = false;
890 if self.alternate() {
891 prefixed = true; width += prefix.chars().count();
894 // Writes the sign if it exists, and then the prefix if it was requested
895 let write_prefix = |f: &mut Formatter| {
896 if let Some(c) = sign {
898 let n = c.encode_utf8(&mut b).unwrap_or(0);
899 let b = unsafe { str::from_utf8_unchecked(&b[..n]) };
900 try!(f.buf.write_str(b));
902 if prefixed { f.buf.write_str(prefix) }
906 // The `width` field is more of a `min-width` parameter at this point.
908 // If there's no minimum length requirements then we can just
911 try!(write_prefix(self)); self.buf.write_str(buf)
913 // Check if we're over the minimum width, if so then we can also
914 // just write the bytes.
915 Some(min) if width >= min => {
916 try!(write_prefix(self)); self.buf.write_str(buf)
918 // The sign and prefix goes before the padding if the fill character
920 Some(min) if self.sign_aware_zero_pad() => {
922 try!(write_prefix(self));
923 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
927 // Otherwise, the sign and prefix goes after the padding
929 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
930 try!(write_prefix(f)); f.buf.write_str(buf)
936 /// This function takes a string slice and emits it to the internal buffer
937 /// after applying the relevant formatting flags specified. The flags
938 /// recognized for generic strings are:
940 /// * width - the minimum width of what to emit
941 /// * fill/align - what to emit and where to emit it if the string
942 /// provided needs to be padded
943 /// * precision - the maximum length to emit, the string is truncated if it
944 /// is longer than this length
946 /// Notably this function ignored the `flag` parameters
947 #[stable(feature = "rust1", since = "1.0.0")]
948 pub fn pad(&mut self, s: &str) -> Result {
949 // Make sure there's a fast path up front
950 if self.width.is_none() && self.precision.is_none() {
951 return self.buf.write_str(s);
953 // The `precision` field can be interpreted as a `max-width` for the
954 // string being formatted
955 if let Some(max) = self.precision {
956 // If there's a maximum width and our string is longer than
957 // that, then we must always have truncation. This is the only
958 // case where the maximum length will matter.
959 if let Some((i, _)) = s.char_indices().skip(max).next() {
960 return self.buf.write_str(&s[..i])
963 // The `width` field is more of a `min-width` parameter at this point.
965 // If we're under the maximum length, and there's no minimum length
966 // requirements, then we can just emit the string
967 None => self.buf.write_str(s),
968 // If we're under the maximum width, check if we're over the minimum
969 // width, if so it's as easy as just emitting the string.
970 Some(width) if s.chars().count() >= width => {
971 self.buf.write_str(s)
973 // If we're under both the maximum and the minimum width, then fill
974 // up the minimum width with the specified string + some alignment.
976 let align = rt::v1::Alignment::Left;
977 self.with_padding(width - s.chars().count(), align, |me| {
984 /// Runs a callback, emitting the correct padding either before or
985 /// afterwards depending on whether right or left alignment is requested.
986 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
988 where F: FnOnce(&mut Formatter) -> Result,
991 let align = match self.align {
992 rt::v1::Alignment::Unknown => default,
996 let (pre_pad, post_pad) = match align {
997 rt::v1::Alignment::Left => (0, padding),
998 rt::v1::Alignment::Right |
999 rt::v1::Alignment::Unknown => (padding, 0),
1000 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1003 let mut fill = [0; 4];
1004 let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
1005 let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) };
1007 for _ in 0..pre_pad {
1008 try!(self.buf.write_str(fill));
1013 for _ in 0..post_pad {
1014 try!(self.buf.write_str(fill));
1020 /// Takes the formatted parts and applies the padding.
1021 /// Assumes that the caller already has rendered the parts with required precision,
1022 /// so that `self.precision` can be ignored.
1023 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1024 if let Some(mut width) = self.width {
1025 // for the sign-aware zero padding, we render the sign first and
1026 // behave as if we had no sign from the beginning.
1027 let mut formatted = formatted.clone();
1028 let mut align = self.align;
1029 let old_fill = self.fill;
1030 if self.sign_aware_zero_pad() {
1031 // a sign always goes first
1032 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1033 try!(self.buf.write_str(sign));
1035 // remove the sign from the formatted parts
1036 formatted.sign = b"";
1037 width = if width < sign.len() { 0 } else { width - sign.len() };
1038 align = rt::v1::Alignment::Right;
1042 // remaining parts go through the ordinary padding process.
1043 let len = formatted.len();
1044 let ret = if width <= len { // no padding
1045 self.write_formatted_parts(&formatted)
1047 self.with_padding(width - len, align, |f| {
1048 f.write_formatted_parts(&formatted)
1051 self.fill = old_fill;
1054 // this is the common case and we take a shortcut
1055 self.write_formatted_parts(formatted)
1059 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1060 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1061 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1064 if !formatted.sign.is_empty() {
1065 try!(write_bytes(self.buf, formatted.sign));
1067 for part in formatted.parts {
1069 flt2dec::Part::Zero(mut nzeroes) => {
1070 const ZEROES: &'static str = // 64 zeroes
1071 "0000000000000000000000000000000000000000000000000000000000000000";
1072 while nzeroes > ZEROES.len() {
1073 try!(self.buf.write_str(ZEROES));
1074 nzeroes -= ZEROES.len();
1077 try!(self.buf.write_str(&ZEROES[..nzeroes]));
1080 flt2dec::Part::Num(mut v) => {
1082 let len = part.len();
1083 for c in s[..len].iter_mut().rev() {
1084 *c = b'0' + (v % 10) as u8;
1087 try!(write_bytes(self.buf, &s[..len]));
1089 flt2dec::Part::Copy(buf) => {
1090 try!(write_bytes(self.buf, buf));
1097 /// Writes some data to the underlying buffer contained within this
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 pub fn write_str(&mut self, data: &str) -> Result {
1101 self.buf.write_str(data)
1104 /// Writes some formatted information into this instance
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1107 write(self.buf, fmt)
1110 /// Flags for formatting (packed version of rt::Flag)
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 pub fn flags(&self) -> u32 { self.flags }
1114 /// Character used as 'fill' whenever there is alignment
1115 #[stable(feature = "fmt_flags", since = "1.5.0")]
1116 pub fn fill(&self) -> char { self.fill }
1118 /// Flag indicating what form of alignment was requested
1119 #[unstable(feature = "fmt_flags_align", reason = "method was just created",
1121 pub fn align(&self) -> Alignment {
1123 rt::v1::Alignment::Left => Alignment::Left,
1124 rt::v1::Alignment::Right => Alignment::Right,
1125 rt::v1::Alignment::Center => Alignment::Center,
1126 rt::v1::Alignment::Unknown => Alignment::Unknown,
1130 /// Optionally specified integer width that the output should be
1131 #[stable(feature = "fmt_flags", since = "1.5.0")]
1132 pub fn width(&self) -> Option<usize> { self.width }
1134 /// Optionally specified precision for numeric types
1135 #[stable(feature = "fmt_flags", since = "1.5.0")]
1136 pub fn precision(&self) -> Option<usize> { self.precision }
1138 /// Determines if the `+` flag was specified.
1139 #[stable(feature = "fmt_flags", since = "1.5.0")]
1140 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1142 /// Determines if the `-` flag was specified.
1143 #[stable(feature = "fmt_flags", since = "1.5.0")]
1144 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1146 /// Determines if the `#` flag was specified.
1147 #[stable(feature = "fmt_flags", since = "1.5.0")]
1148 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1150 /// Determines if the `0` flag was specified.
1151 #[stable(feature = "fmt_flags", since = "1.5.0")]
1152 pub fn sign_aware_zero_pad(&self) -> bool {
1153 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1156 /// Creates a `DebugStruct` builder designed to assist with creation of
1157 /// `fmt::Debug` implementations for structs.
1169 /// impl fmt::Debug for Foo {
1170 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1171 /// fmt.debug_struct("Foo")
1172 /// .field("bar", &self.bar)
1173 /// .field("baz", &self.baz)
1178 /// // prints "Foo { bar: 10, baz: "Hello World" }"
1179 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1181 #[stable(feature = "debug_builders", since = "1.2.0")]
1183 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1184 builders::debug_struct_new(self, name)
1187 /// Creates a `DebugTuple` builder designed to assist with creation of
1188 /// `fmt::Debug` implementations for tuple structs.
1195 /// struct Foo(i32, String);
1197 /// impl fmt::Debug for Foo {
1198 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1199 /// fmt.debug_tuple("Foo")
1206 /// // prints "Foo(10, "Hello World")"
1207 /// println!("{:?}", Foo(10, "Hello World".to_string()));
1209 #[stable(feature = "debug_builders", since = "1.2.0")]
1211 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1212 builders::debug_tuple_new(self, name)
1215 /// Creates a `DebugList` builder designed to assist with creation of
1216 /// `fmt::Debug` implementations for list-like structures.
1223 /// struct Foo(Vec<i32>);
1225 /// impl fmt::Debug for Foo {
1226 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1227 /// fmt.debug_list().entries(self.0.iter()).finish()
1231 /// // prints "[10, 11]"
1232 /// println!("{:?}", Foo(vec![10, 11]));
1234 #[stable(feature = "debug_builders", since = "1.2.0")]
1236 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1237 builders::debug_list_new(self)
1240 /// Creates a `DebugSet` builder designed to assist with creation of
1241 /// `fmt::Debug` implementations for set-like structures.
1248 /// struct Foo(Vec<i32>);
1250 /// impl fmt::Debug for Foo {
1251 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1252 /// fmt.debug_set().entries(self.0.iter()).finish()
1256 /// // prints "{10, 11}"
1257 /// println!("{:?}", Foo(vec![10, 11]));
1259 #[stable(feature = "debug_builders", since = "1.2.0")]
1261 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1262 builders::debug_set_new(self)
1265 /// Creates a `DebugMap` builder designed to assist with creation of
1266 /// `fmt::Debug` implementations for map-like structures.
1273 /// struct Foo(Vec<(String, i32)>);
1275 /// impl fmt::Debug for Foo {
1276 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1277 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1281 /// // prints "{"A": 10, "B": 11}"
1282 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1284 #[stable(feature = "debug_builders", since = "1.2.0")]
1286 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1287 builders::debug_map_new(self)
1291 #[stable(since = "1.2.0", feature = "formatter_write")]
1292 impl<'a> Write for Formatter<'a> {
1293 fn write_str(&mut self, s: &str) -> Result {
1294 self.buf.write_str(s)
1297 fn write_char(&mut self, c: char) -> Result {
1298 self.buf.write_char(c)
1301 fn write_fmt(&mut self, args: Arguments) -> Result {
1302 write(self.buf, args)
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl Display for Error {
1308 fn fmt(&self, f: &mut Formatter) -> Result {
1309 Display::fmt("an error occurred when formatting an argument", f)
1313 // Implementations of the core formatting traits
1315 macro_rules! fmt_refs {
1316 ($($tr:ident),*) => {
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl<'a, T: ?Sized + $tr> $tr for &'a T {
1320 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1324 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1330 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1332 #[stable(feature = "rust1", since = "1.0.0")]
1333 impl Debug for bool {
1334 fn fmt(&self, f: &mut Formatter) -> Result {
1335 Display::fmt(self, f)
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl Display for bool {
1341 fn fmt(&self, f: &mut Formatter) -> Result {
1342 Display::fmt(if *self { "true" } else { "false" }, f)
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 impl Debug for str {
1348 fn fmt(&self, f: &mut Formatter) -> Result {
1349 try!(f.write_char('"'));
1351 for (i, c) in self.char_indices() {
1352 let esc = c.escape_default();
1353 // If char needs escaping, flush backlog so far and write, else skip
1354 if esc.size_hint() != (1, Some(1)) {
1355 try!(f.write_str(&self[from..i]));
1357 try!(f.write_char(c));
1359 from = i + c.len_utf8();
1362 try!(f.write_str(&self[from..]));
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 impl Display for str {
1369 fn fmt(&self, f: &mut Formatter) -> Result {
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 impl Debug for char {
1376 fn fmt(&self, f: &mut Formatter) -> Result {
1377 try!(f.write_char('\''));
1378 for c in self.escape_default() {
1379 try!(f.write_char(c))
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 impl Display for char {
1387 fn fmt(&self, f: &mut Formatter) -> Result {
1388 if f.width.is_none() && f.precision.is_none() {
1391 let mut utf8 = [0; 4];
1392 let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
1393 let s: &str = unsafe { str::from_utf8_unchecked(&utf8[..amt]) };
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 impl<T: ?Sized> Pointer for *const T {
1401 fn fmt(&self, f: &mut Formatter) -> Result {
1402 let old_width = f.width;
1403 let old_flags = f.flags;
1405 // The alternate flag is already treated by LowerHex as being special-
1406 // it denotes whether to prefix with 0x. We use it to work out whether
1407 // or not to zero extend, and then unconditionally set it to get the
1410 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1412 if let None = f.width {
1413 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
1416 f.flags |= 1 << (FlagV1::Alternate as u32);
1418 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
1420 f.width = old_width;
1421 f.flags = old_flags;
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 impl<T: ?Sized> Pointer for *mut T {
1429 fn fmt(&self, f: &mut Formatter) -> Result {
1430 Pointer::fmt(&(*self as *const T), f)
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 impl<'a, T: ?Sized> Pointer for &'a T {
1436 fn fmt(&self, f: &mut Formatter) -> Result {
1437 Pointer::fmt(&(*self as *const T), f)
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 impl<'a, T: ?Sized> Pointer for &'a mut T {
1443 fn fmt(&self, f: &mut Formatter) -> Result {
1444 Pointer::fmt(&(&**self as *const T), f)
1448 // Common code of floating point Debug and Display.
1449 fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
1450 where T: flt2dec::DecodableFloat
1452 let force_sign = fmt.sign_plus();
1453 let sign = match (force_sign, negative_zero) {
1454 (false, false) => flt2dec::Sign::Minus,
1455 (false, true) => flt2dec::Sign::MinusRaw,
1456 (true, false) => flt2dec::Sign::MinusPlus,
1457 (true, true) => flt2dec::Sign::MinusPlusRaw,
1460 let mut buf = [0; 1024]; // enough for f32 and f64
1461 let mut parts = [flt2dec::Part::Zero(0); 16];
1462 let formatted = if let Some(precision) = fmt.precision {
1463 flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1464 precision, false, &mut buf, &mut parts)
1466 flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1467 0, false, &mut buf, &mut parts)
1469 fmt.pad_formatted_parts(&formatted)
1472 // Common code of floating point LowerExp and UpperExp.
1473 fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
1474 where T: flt2dec::DecodableFloat
1476 let force_sign = fmt.sign_plus();
1477 let sign = match force_sign {
1478 false => flt2dec::Sign::Minus,
1479 true => flt2dec::Sign::MinusPlus,
1482 let mut buf = [0; 1024]; // enough for f32 and f64
1483 let mut parts = [flt2dec::Part::Zero(0); 16];
1484 let formatted = if let Some(precision) = fmt.precision {
1485 // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1486 flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1487 precision + 1, upper, &mut buf, &mut parts)
1489 flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1490 (0, 0), upper, &mut buf, &mut parts)
1492 fmt.pad_formatted_parts(&formatted)
1495 macro_rules! floating { ($ty:ident) => {
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 impl Debug for $ty {
1499 fn fmt(&self, fmt: &mut Formatter) -> Result {
1500 float_to_decimal_common(fmt, self, true)
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 impl Display for $ty {
1506 fn fmt(&self, fmt: &mut Formatter) -> Result {
1507 float_to_decimal_common(fmt, self, false)
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 impl LowerExp for $ty {
1513 fn fmt(&self, fmt: &mut Formatter) -> Result {
1514 float_to_exponential_common(fmt, self, false)
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 impl UpperExp for $ty {
1520 fn fmt(&self, fmt: &mut Formatter) -> Result {
1521 float_to_exponential_common(fmt, self, true)
1528 // Implementation of Display/Debug for various core types
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl<T> Debug for *const T {
1532 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1534 #[stable(feature = "rust1", since = "1.0.0")]
1535 impl<T> Debug for *mut T {
1536 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1540 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1543 macro_rules! tuple {
1545 ( $($name:ident,)+ ) => (
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 impl<$($name:Debug),*> Debug for ($($name,)*) {
1548 #[allow(non_snake_case, unused_assignments, deprecated)]
1549 fn fmt(&self, f: &mut Formatter) -> Result {
1550 let mut builder = f.debug_tuple("");
1551 let ($(ref $name,)*) = *self;
1553 builder.field($name);
1559 peel! { $($name,)* }
1563 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 impl<T: Debug> Debug for [T] {
1567 fn fmt(&self, f: &mut Formatter) -> Result {
1568 f.debug_list().entries(self.iter()).finish()
1572 #[stable(feature = "rust1", since = "1.0.0")]
1574 fn fmt(&self, f: &mut Formatter) -> Result {
1578 #[stable(feature = "rust1", since = "1.0.0")]
1579 impl<T: ?Sized> Debug for PhantomData<T> {
1580 fn fmt(&self, f: &mut Formatter) -> Result {
1581 f.pad("PhantomData")
1585 #[stable(feature = "rust1", since = "1.0.0")]
1586 impl<T: Copy + Debug> Debug for Cell<T> {
1587 fn fmt(&self, f: &mut Formatter) -> Result {
1588 write!(f, "Cell {{ value: {:?} }}", self.get())
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1594 fn fmt(&self, f: &mut Formatter) -> Result {
1595 match self.borrow_state() {
1596 BorrowState::Unused | BorrowState::Reading => {
1597 write!(f, "RefCell {{ value: {:?} }}", self.borrow())
1599 BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1606 fn fmt(&self, f: &mut Formatter) -> Result {
1607 Debug::fmt(&**self, f)
1611 #[stable(feature = "rust1", since = "1.0.0")]
1612 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1613 fn fmt(&self, f: &mut Formatter) -> Result {
1614 Debug::fmt(&*(self.deref()), f)
1618 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1619 // it's a lot easier than creating all of the rt::Piece structures here.