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;
25 use self::rt::v1::Alignment;
27 pub use self::num::radix;
28 pub use self::num::Radix;
29 pub use self::num::RadixFmt;
31 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
36 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
43 #[stable(feature = "rust1", since = "1.0.0")]
44 /// The type returned by formatter methods.
45 pub type Result = result::Result<(), Error>;
47 /// The error type which is returned from formatting a message into a stream.
49 /// This type does not support transmission of an error other than that an error
50 /// occurred. Any extra information must be arranged to be transmitted through
52 #[stable(feature = "rust1", since = "1.0.0")]
53 #[derive(Copy, Clone, Debug)]
56 /// A collection of methods that are required to format a message into a stream.
58 /// This trait is the type which this modules requires when formatting
59 /// information. This is similar to the standard library's `io::Write` trait,
60 /// but it is only intended for use in libcore.
62 /// This trait should generally not be implemented by consumers of the standard
63 /// library. The `write!` macro accepts an instance of `io::Write`, and the
64 /// `io::Write` trait is favored over implementing this trait.
65 #[stable(feature = "rust1", since = "1.0.0")]
67 /// Writes a slice of bytes into this writer, returning whether the write
70 /// This method can only succeed if the entire byte slice was successfully
71 /// written, and this method will not return until all data has been
72 /// written or an error occurs.
76 /// This function will return an instance of `Error` on error.
77 #[stable(feature = "rust1", since = "1.0.0")]
78 fn write_str(&mut self, s: &str) -> Result;
80 /// Writes a `char` into this writer, returning whether the write succeeded.
82 /// A single `char` may be encoded as more than one byte.
83 /// This method can only succeed if the entire byte sequence was successfully
84 /// written, and this method will not return until all data has been
85 /// written or an error occurs.
89 /// This function will return an instance of `Error` on error.
90 #[stable(feature = "fmt_write_char", since = "1.1.0")]
91 fn write_char(&mut self, c: char) -> Result {
92 let mut utf_8 = [0u8; 4];
93 let bytes_written = c.encode_utf8(&mut utf_8).unwrap_or(0);
94 self.write_str(unsafe { str::from_utf8_unchecked(&utf_8[..bytes_written]) })
97 /// Glue for usage of the `write!` macro with implementors of this trait.
99 /// This method should generally not be invoked manually, but rather through
100 /// the `write!` macro itself.
101 #[stable(feature = "rust1", since = "1.0.0")]
102 fn write_fmt(&mut self, args: Arguments) -> Result {
103 // This Adapter is needed to allow `self` (of type `&mut
104 // Self`) to be cast to a Write (below) without
105 // requiring a `Sized` bound.
106 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
108 impl<'a, T: ?Sized> Write for Adapter<'a, T>
111 fn write_str(&mut self, s: &str) -> Result {
115 fn write_fmt(&mut self, args: Arguments) -> Result {
116 self.0.write_fmt(args)
120 write(&mut Adapter(self), args)
124 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
125 impl<'a, W: Write + ?Sized> Write for &'a mut W {
126 fn write_str(&mut self, s: &str) -> Result {
127 (**self).write_str(s)
130 fn write_char(&mut self, c: char) -> Result {
131 (**self).write_char(c)
134 fn write_fmt(&mut self, args: Arguments) -> Result {
135 (**self).write_fmt(args)
139 /// A struct to represent both where to emit formatting strings to and how they
140 /// should be formatted. A mutable version of this is passed to all formatting
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub struct Formatter<'a> {
146 align: rt::v1::Alignment,
147 width: Option<usize>,
148 precision: Option<usize>,
150 buf: &'a mut (Write+'a),
151 curarg: slice::Iter<'a, ArgumentV1<'a>>,
152 args: &'a [ArgumentV1<'a>],
155 // NB. Argument is essentially an optimized partially applied formatting function,
156 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
160 /// This struct represents the generic "argument" which is taken by the Xprintf
161 /// family of functions. It contains a function to format the given value. At
162 /// compile time it is ensured that the function and the value have the correct
163 /// types, and then this struct is used to canonicalize arguments to one type.
165 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
168 pub struct ArgumentV1<'a> {
170 formatter: fn(&Void, &mut Formatter) -> Result,
173 impl<'a> Clone for ArgumentV1<'a> {
174 fn clone(&self) -> ArgumentV1<'a> {
179 impl<'a> ArgumentV1<'a> {
181 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
186 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
188 pub fn new<'b, T>(x: &'b T,
189 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
192 formatter: mem::transmute(f),
193 value: mem::transmute(x)
199 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
201 pub fn from_usize(x: &usize) -> ArgumentV1 {
202 ArgumentV1::new(x, ArgumentV1::show_usize)
205 fn as_usize(&self) -> Option<usize> {
206 if self.formatter as usize == ArgumentV1::show_usize as usize {
207 Some(unsafe { *(self.value as *const _ as *const usize) })
214 // flags available in the v1 format of format_args
215 #[derive(Copy, Clone)]
216 #[allow(dead_code)] // SignMinus isn't currently used
217 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
219 impl<'a> Arguments<'a> {
220 /// When using the format_args!() macro, this function is used to generate the
221 /// Arguments structure.
222 #[doc(hidden)] #[inline]
223 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
225 pub fn new_v1(pieces: &'a [&'a str],
226 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
234 /// This function is used to specify nonstandard formatting parameters.
235 /// The `pieces` array must be at least as long as `fmt` to construct
236 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
237 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
238 /// created with `argumentusize`. However, failing to do so doesn't cause
239 /// unsafety, but will ignore invalid .
240 #[doc(hidden)] #[inline]
241 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
243 pub fn new_v1_formatted(pieces: &'a [&'a str],
244 args: &'a [ArgumentV1<'a>],
245 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
254 /// This structure represents a safely precompiled version of a format string
255 /// and its arguments. This cannot be generated at runtime because it cannot
256 /// safely be done so, so no constructors are given and the fields are private
257 /// to prevent modification.
259 /// The `format_args!` macro will safely create an instance of this structure
260 /// and pass it to a function or closure, passed as the first argument. The
261 /// macro validates the format string at compile-time so usage of the `write`
262 /// and `format` functions can be safely performed.
263 #[stable(feature = "rust1", since = "1.0.0")]
264 #[derive(Copy, Clone)]
265 pub struct Arguments<'a> {
266 // Format string pieces to print.
267 pieces: &'a [&'a str],
269 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
270 fmt: Option<&'a [rt::v1::Argument]>,
272 // Dynamic arguments for interpolation, to be interleaved with string
273 // pieces. (Every argument is preceded by a string piece.)
274 args: &'a [ArgumentV1<'a>],
277 #[stable(feature = "rust1", since = "1.0.0")]
278 impl<'a> Debug for Arguments<'a> {
279 fn fmt(&self, fmt: &mut Formatter) -> Result {
280 Display::fmt(self, fmt)
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl<'a> Display for Arguments<'a> {
286 fn fmt(&self, fmt: &mut Formatter) -> Result {
287 write(fmt.buf, *self)
291 /// Format trait for the `?` character.
293 /// `Debug` should format the output in a programmer-facing, debugging context.
295 /// Generally speaking, you should just `derive` a `Debug` implementation.
297 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
299 /// For more information on formatters, see [the module-level documentation][module].
301 /// [module]: ../../std/fmt/index.html
305 /// Deriving an implementation:
314 /// let origin = Point { x: 0, y: 0 };
316 /// println!("The origin is: {:?}", origin);
319 /// Manually implementing:
329 /// impl fmt::Debug for Point {
330 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
331 /// write!(f, "({}, {})", self.x, self.y)
335 /// let origin = Point { x: 0, y: 0 };
337 /// println!("The origin is: {:?}", origin);
343 /// The origin is: Point { x: 0, y: 0 }
346 /// There are a number of `debug_*` methods on `Formatter` to help you with manual
347 /// implementations, such as [`debug_struct`][debug_struct].
349 /// `Debug` implementations using either `derive` or the debug builder API
350 /// on `Formatter` support pretty printing using the alternate flag: `{:#?}`.
352 /// [debug_struct]: ../std/fmt/struct.Formatter.html#method.debug_struct
354 /// Pretty printing with `#?`:
363 /// let origin = Point { x: 0, y: 0 };
365 /// println!("The origin is: {:#?}", origin);
371 /// The origin is: Point {
376 #[stable(feature = "rust1", since = "1.0.0")]
377 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
378 defined in your crate, add `#[derive(Debug)]` or \
379 manually implement it"]
380 #[lang = "debug_trait"]
382 /// Formats the value using the given formatter.
383 #[stable(feature = "rust1", since = "1.0.0")]
384 fn fmt(&self, &mut Formatter) -> Result;
387 /// Format trait for an empty format, `{}`.
389 /// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
390 /// output, and so cannot be derived.
392 /// [debug]: trait.Debug.html
394 /// For more information on formatters, see [the module-level documentation][module].
396 /// [module]: ../../std/fmt/index.html
400 /// Implementing `Display` on a type:
410 /// impl fmt::Display for Point {
411 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
412 /// write!(f, "({}, {})", self.x, self.y)
416 /// let origin = Point { x: 0, y: 0 };
418 /// println!("The origin is: {}", origin);
420 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
421 formatter; try using `:?` instead if you are using \
423 #[stable(feature = "rust1", since = "1.0.0")]
425 /// Formats the value using the given formatter.
426 #[stable(feature = "rust1", since = "1.0.0")]
427 fn fmt(&self, &mut Formatter) -> Result;
430 /// Format trait for the `o` character.
432 /// The `Octal` trait should format its output as a number in base-8.
434 /// The alternate flag, `#`, adds a `0o` in front of the output.
436 /// For more information on formatters, see [the module-level documentation][module].
438 /// [module]: ../../std/fmt/index.html
442 /// Basic usage with `i32`:
445 /// let x = 42; // 42 is '52' in octal
447 /// assert_eq!(format!("{:o}", x), "52");
448 /// assert_eq!(format!("{:#o}", x), "0o52");
451 /// Implementing `Octal` on a type:
456 /// struct Length(i32);
458 /// impl fmt::Octal for Length {
459 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
460 /// let val = self.0;
462 /// write!(f, "{:o}", val) // delegate to i32's implementation
466 /// let l = Length(9);
468 /// println!("l as octal is: {:o}", l);
470 #[stable(feature = "rust1", since = "1.0.0")]
472 /// Formats the value using the given formatter.
473 #[stable(feature = "rust1", since = "1.0.0")]
474 fn fmt(&self, &mut Formatter) -> Result;
477 /// Format trait for the `b` character.
479 /// The `Binary` trait should format its output as a number in binary.
481 /// The alternate flag, `#`, adds a `0b` in front of the output.
483 /// For more information on formatters, see [the module-level documentation][module].
485 /// [module]: ../../std/fmt/index.html
489 /// Basic usage with `i32`:
492 /// let x = 42; // 42 is '101010' in binary
494 /// assert_eq!(format!("{:b}", x), "101010");
495 /// assert_eq!(format!("{:#b}", x), "0b101010");
498 /// Implementing `Binary` on a type:
503 /// struct Length(i32);
505 /// impl fmt::Binary for Length {
506 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
507 /// let val = self.0;
509 /// write!(f, "{:b}", val) // delegate to i32's implementation
513 /// let l = Length(107);
515 /// println!("l as binary is: {:b}", l);
517 #[stable(feature = "rust1", since = "1.0.0")]
519 /// Formats the value using the given formatter.
520 #[stable(feature = "rust1", since = "1.0.0")]
521 fn fmt(&self, &mut Formatter) -> Result;
524 /// Format trait for the `x` character.
526 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
529 /// The alternate flag, `#`, adds a `0x` in front of the output.
531 /// For more information on formatters, see [the module-level documentation][module].
533 /// [module]: ../../std/fmt/index.html
537 /// Basic usage with `i32`:
540 /// let x = 42; // 42 is '2a' in hex
542 /// assert_eq!(format!("{:x}", x), "2a");
543 /// assert_eq!(format!("{:#x}", x), "0x2a");
546 /// Implementing `LowerHex` on a type:
551 /// struct Length(i32);
553 /// impl fmt::LowerHex for Length {
554 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
555 /// let val = self.0;
557 /// write!(f, "{:x}", val) // delegate to i32's implementation
561 /// let l = Length(9);
563 /// println!("l as hex is: {:x}", l);
565 #[stable(feature = "rust1", since = "1.0.0")]
567 /// Formats the value using the given formatter.
568 #[stable(feature = "rust1", since = "1.0.0")]
569 fn fmt(&self, &mut Formatter) -> Result;
572 /// Format trait for the `X` character.
574 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
577 /// The alternate flag, `#`, adds a `0x` in front of the output.
579 /// For more information on formatters, see [the module-level documentation][module].
581 /// [module]: ../../std/fmt/index.html
585 /// Basic usage with `i32`:
588 /// let x = 42; // 42 is '2A' in hex
590 /// assert_eq!(format!("{:X}", x), "2A");
591 /// assert_eq!(format!("{:#X}", x), "0x2A");
594 /// Implementing `UpperHex` on a type:
599 /// struct Length(i32);
601 /// impl fmt::UpperHex for Length {
602 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
603 /// let val = self.0;
605 /// write!(f, "{:X}", val) // delegate to i32's implementation
609 /// let l = Length(9);
611 /// println!("l as hex is: {:X}", l);
613 #[stable(feature = "rust1", since = "1.0.0")]
615 /// Formats the value using the given formatter.
616 #[stable(feature = "rust1", since = "1.0.0")]
617 fn fmt(&self, &mut Formatter) -> Result;
620 /// Format trait for the `p` character.
622 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
625 /// For more information on formatters, see [the module-level documentation][module].
627 /// [module]: ../../std/fmt/index.html
631 /// Basic usage with `&i32`:
636 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
639 /// Implementing `Pointer` on a type:
644 /// struct Length(i32);
646 /// impl fmt::Pointer for Length {
647 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
648 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
650 /// write!(f, "{:p}", self as *const Length)
654 /// let l = Length(42);
656 /// println!("l is in memory here: {:p}", l);
658 #[stable(feature = "rust1", since = "1.0.0")]
660 /// Formats the value using the given formatter.
661 #[stable(feature = "rust1", since = "1.0.0")]
662 fn fmt(&self, &mut Formatter) -> Result;
665 /// Format trait for the `e` character.
667 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
669 /// For more information on formatters, see [the module-level documentation][module].
671 /// [module]: ../../std/fmt/index.html
675 /// Basic usage with `i32`:
678 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
680 /// assert_eq!(format!("{:e}", x), "4.2e1");
683 /// Implementing `LowerExp` on a type:
688 /// struct Length(i32);
690 /// impl fmt::LowerExp for Length {
691 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
692 /// let val = self.0;
693 /// write!(f, "{}e1", val / 10)
697 /// let l = Length(100);
699 /// println!("l in scientific notation is: {:e}", l);
701 #[stable(feature = "rust1", since = "1.0.0")]
703 /// Formats the value using the given formatter.
704 #[stable(feature = "rust1", since = "1.0.0")]
705 fn fmt(&self, &mut Formatter) -> Result;
708 /// Format trait for the `E` character.
710 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
712 /// For more information on formatters, see [the module-level documentation][module].
714 /// [module]: ../../std/fmt/index.html
718 /// Basic usage with `f32`:
721 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
723 /// assert_eq!(format!("{:E}", x), "4.2E1");
726 /// Implementing `UpperExp` on a type:
731 /// struct Length(i32);
733 /// impl fmt::UpperExp for Length {
734 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
735 /// let val = self.0;
736 /// write!(f, "{}E1", val / 10)
740 /// let l = Length(100);
742 /// println!("l in scientific notation is: {:E}", l);
744 #[stable(feature = "rust1", since = "1.0.0")]
746 /// Formats the value using the given formatter.
747 #[stable(feature = "rust1", since = "1.0.0")]
748 fn fmt(&self, &mut Formatter) -> Result;
751 /// The `write` function takes an output stream, a precompiled format string,
752 /// and a list of arguments. The arguments will be formatted according to the
753 /// specified format string into the output stream provided.
757 /// * output - the buffer to write output to
758 /// * args - the precompiled arguments generated by `format_args!`
759 #[stable(feature = "rust1", since = "1.0.0")]
760 pub fn write(output: &mut Write, args: Arguments) -> Result {
761 let mut formatter = Formatter {
766 align: Alignment::Unknown,
769 curarg: args.args.iter(),
772 let mut pieces = args.pieces.iter();
776 // We can use default formatting parameters for all arguments.
777 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
778 try!(formatter.buf.write_str(*piece));
779 try!((arg.formatter)(arg.value, &mut formatter));
783 // Every spec has a corresponding argument that is preceded by
785 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
786 try!(formatter.buf.write_str(*piece));
787 try!(formatter.run(arg));
792 // There can be only one trailing string piece left.
793 match pieces.next() {
795 try!(formatter.buf.write_str(*piece));
803 impl<'a> Formatter<'a> {
805 // First up is the collection of functions used to execute a format string
806 // at runtime. This consumes all of the compile-time statics generated by
807 // the format! syntax extension.
808 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
809 // Fill in the format parameters into the formatter
810 self.fill = arg.format.fill;
811 self.align = arg.format.align;
812 self.flags = arg.format.flags;
813 self.width = self.getcount(&arg.format.width);
814 self.precision = self.getcount(&arg.format.precision);
816 // Extract the correct argument
817 let value = match arg.position {
818 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
819 rt::v1::Position::At(i) => self.args[i],
822 // Then actually do some printing
823 (value.formatter)(value.value, self)
826 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
828 rt::v1::Count::Is(n) => Some(n),
829 rt::v1::Count::Implied => None,
830 rt::v1::Count::Param(i) => {
831 self.args[i].as_usize()
833 rt::v1::Count::NextParam => {
834 self.curarg.next().and_then(|arg| arg.as_usize())
839 // Helper methods used for padding and processing formatting arguments that
840 // all formatting traits can use.
842 /// Performs the correct padding for an integer which has already been
843 /// emitted into a str. The str should *not* contain the sign for the
844 /// integer, that will be added by this method.
848 /// * is_positive - whether the original integer was positive or not.
849 /// * prefix - if the '#' character (Alternate) is provided, this
850 /// is the prefix to put in front of the number.
851 /// * buf - the byte array that the number has been formatted into
853 /// This function will correctly account for the flags provided as well as
854 /// the minimum width. It will not take precision into account.
855 #[stable(feature = "rust1", since = "1.0.0")]
856 pub fn pad_integral(&mut self,
863 let mut width = buf.len();
867 sign = Some('-'); width += 1;
868 } else if self.sign_plus() {
869 sign = Some('+'); width += 1;
872 let mut prefixed = false;
873 if self.alternate() {
874 prefixed = true; width += prefix.char_len();
877 // Writes the sign if it exists, and then the prefix if it was requested
878 let write_prefix = |f: &mut Formatter| {
879 if let Some(c) = sign {
881 let n = c.encode_utf8(&mut b).unwrap_or(0);
882 let b = unsafe { str::from_utf8_unchecked(&b[..n]) };
883 try!(f.buf.write_str(b));
885 if prefixed { f.buf.write_str(prefix) }
889 // The `width` field is more of a `min-width` parameter at this point.
891 // If there's no minimum length requirements then we can just
894 try!(write_prefix(self)); self.buf.write_str(buf)
896 // Check if we're over the minimum width, if so then we can also
897 // just write the bytes.
898 Some(min) if width >= min => {
899 try!(write_prefix(self)); self.buf.write_str(buf)
901 // The sign and prefix goes before the padding if the fill character
903 Some(min) if self.sign_aware_zero_pad() => {
905 try!(write_prefix(self));
906 self.with_padding(min - width, Alignment::Right, |f| {
910 // Otherwise, the sign and prefix goes after the padding
912 self.with_padding(min - width, Alignment::Right, |f| {
913 try!(write_prefix(f)); f.buf.write_str(buf)
919 /// This function takes a string slice and emits it to the internal buffer
920 /// after applying the relevant formatting flags specified. The flags
921 /// recognized for generic strings are:
923 /// * width - the minimum width of what to emit
924 /// * fill/align - what to emit and where to emit it if the string
925 /// provided needs to be padded
926 /// * precision - the maximum length to emit, the string is truncated if it
927 /// is longer than this length
929 /// Notably this function ignored the `flag` parameters
930 #[stable(feature = "rust1", since = "1.0.0")]
931 pub fn pad(&mut self, s: &str) -> Result {
932 // Make sure there's a fast path up front
933 if self.width.is_none() && self.precision.is_none() {
934 return self.buf.write_str(s);
936 // The `precision` field can be interpreted as a `max-width` for the
937 // string being formatted
938 match self.precision {
940 // If there's a maximum width and our string is longer than
941 // that, then we must always have truncation. This is the only
942 // case where the maximum length will matter.
943 let char_len = s.char_len();
945 let nchars = ::cmp::min(max, char_len);
946 return self.buf.write_str(s.slice_chars(0, nchars));
951 // The `width` field is more of a `min-width` parameter at this point.
953 // If we're under the maximum length, and there's no minimum length
954 // requirements, then we can just emit the string
955 None => self.buf.write_str(s),
956 // If we're under the maximum width, check if we're over the minimum
957 // width, if so it's as easy as just emitting the string.
958 Some(width) if s.char_len() >= width => {
959 self.buf.write_str(s)
961 // If we're under both the maximum and the minimum width, then fill
962 // up the minimum width with the specified string + some alignment.
964 self.with_padding(width - s.char_len(), Alignment::Left, |me| {
971 /// Runs a callback, emitting the correct padding either before or
972 /// afterwards depending on whether right or left alignment is requested.
973 fn with_padding<F>(&mut self, padding: usize, default: Alignment,
975 where F: FnOnce(&mut Formatter) -> Result,
978 let align = match self.align {
979 Alignment::Unknown => default,
983 let (pre_pad, post_pad) = match align {
984 Alignment::Left => (0, padding),
985 Alignment::Right | Alignment::Unknown => (padding, 0),
986 Alignment::Center => (padding / 2, (padding + 1) / 2),
989 let mut fill = [0; 4];
990 let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
991 let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) };
993 for _ in 0..pre_pad {
994 try!(self.buf.write_str(fill));
999 for _ in 0..post_pad {
1000 try!(self.buf.write_str(fill));
1006 /// Takes the formatted parts and applies the padding.
1007 /// Assumes that the caller already has rendered the parts with required precision,
1008 /// so that `self.precision` can be ignored.
1009 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1010 if let Some(mut width) = self.width {
1011 // for the sign-aware zero padding, we render the sign first and
1012 // behave as if we had no sign from the beginning.
1013 let mut formatted = formatted.clone();
1014 let mut align = self.align;
1015 let old_fill = self.fill;
1016 if self.sign_aware_zero_pad() {
1017 // a sign always goes first
1018 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
1019 try!(self.buf.write_str(sign));
1021 // remove the sign from the formatted parts
1022 formatted.sign = b"";
1023 width = if width < sign.len() { 0 } else { width - sign.len() };
1024 align = Alignment::Right;
1028 // remaining parts go through the ordinary padding process.
1029 let len = formatted.len();
1030 let ret = if width <= len { // no padding
1031 self.write_formatted_parts(&formatted)
1033 self.with_padding(width - len, align, |f| {
1034 f.write_formatted_parts(&formatted)
1037 self.fill = old_fill;
1040 // this is the common case and we take a shortcut
1041 self.write_formatted_parts(formatted)
1045 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1046 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1047 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1050 if !formatted.sign.is_empty() {
1051 try!(write_bytes(self.buf, formatted.sign));
1053 for part in formatted.parts {
1055 flt2dec::Part::Zero(mut nzeroes) => {
1056 const ZEROES: &'static str = // 64 zeroes
1057 "0000000000000000000000000000000000000000000000000000000000000000";
1058 while nzeroes > ZEROES.len() {
1059 try!(self.buf.write_str(ZEROES));
1060 nzeroes -= ZEROES.len();
1063 try!(self.buf.write_str(&ZEROES[..nzeroes]));
1066 flt2dec::Part::Num(mut v) => {
1068 let len = part.len();
1069 for c in s[..len].iter_mut().rev() {
1070 *c = b'0' + (v % 10) as u8;
1073 try!(write_bytes(self.buf, &s[..len]));
1075 flt2dec::Part::Copy(buf) => {
1076 try!(write_bytes(self.buf, buf));
1083 /// Writes some data to the underlying buffer contained within this
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 pub fn write_str(&mut self, data: &str) -> Result {
1087 self.buf.write_str(data)
1090 /// Writes some formatted information into this instance
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1093 write(self.buf, fmt)
1096 /// Flags for formatting (packed version of rt::Flag)
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 pub fn flags(&self) -> u32 { self.flags }
1100 /// Character used as 'fill' whenever there is alignment
1101 #[stable(feature = "fmt_flags", since = "1.5.0")]
1102 pub fn fill(&self) -> char { self.fill }
1104 /// Flag indicating what form of alignment was requested
1105 #[unstable(feature = "fmt_flags_align", reason = "method was just created",
1107 pub fn align(&self) -> Alignment { self.align }
1109 /// Optionally specified integer width that the output should be
1110 #[stable(feature = "fmt_flags", since = "1.5.0")]
1111 pub fn width(&self) -> Option<usize> { self.width }
1113 /// Optionally specified precision for numeric types
1114 #[stable(feature = "fmt_flags", since = "1.5.0")]
1115 pub fn precision(&self) -> Option<usize> { self.precision }
1117 /// Determines if the `+` flag was specified.
1118 #[stable(feature = "fmt_flags", since = "1.5.0")]
1119 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1121 /// Determines if the `-` flag was specified.
1122 #[stable(feature = "fmt_flags", since = "1.5.0")]
1123 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1125 /// Determines if the `#` flag was specified.
1126 #[stable(feature = "fmt_flags", since = "1.5.0")]
1127 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1129 /// Determines if the `0` flag was specified.
1130 #[stable(feature = "fmt_flags", since = "1.5.0")]
1131 pub fn sign_aware_zero_pad(&self) -> bool {
1132 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1135 /// Creates a `DebugStruct` builder designed to assist with creation of
1136 /// `fmt::Debug` implementations for structs.
1148 /// impl fmt::Debug for Foo {
1149 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1150 /// fmt.debug_struct("Foo")
1151 /// .field("bar", &self.bar)
1152 /// .field("baz", &self.baz)
1157 /// // prints "Foo { bar: 10, baz: "Hello World" }"
1158 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1160 #[stable(feature = "debug_builders", since = "1.2.0")]
1162 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1163 builders::debug_struct_new(self, name)
1166 /// Creates a `DebugTuple` builder designed to assist with creation of
1167 /// `fmt::Debug` implementations for tuple structs.
1174 /// struct Foo(i32, String);
1176 /// impl fmt::Debug for Foo {
1177 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1178 /// fmt.debug_tuple("Foo")
1185 /// // prints "Foo(10, "Hello World")"
1186 /// println!("{:?}", Foo(10, "Hello World".to_string()));
1188 #[stable(feature = "debug_builders", since = "1.2.0")]
1190 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1191 builders::debug_tuple_new(self, name)
1194 /// Creates a `DebugList` builder designed to assist with creation of
1195 /// `fmt::Debug` implementations for list-like structures.
1202 /// struct Foo(Vec<i32>);
1204 /// impl fmt::Debug for Foo {
1205 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1206 /// fmt.debug_list().entries(self.0.iter()).finish()
1210 /// // prints "[10, 11]"
1211 /// println!("{:?}", Foo(vec![10, 11]));
1213 #[stable(feature = "debug_builders", since = "1.2.0")]
1215 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1216 builders::debug_list_new(self)
1219 /// Creates a `DebugSet` builder designed to assist with creation of
1220 /// `fmt::Debug` implementations for set-like structures.
1227 /// struct Foo(Vec<i32>);
1229 /// impl fmt::Debug for Foo {
1230 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1231 /// fmt.debug_set().entries(self.0.iter()).finish()
1235 /// // prints "{10, 11}"
1236 /// println!("{:?}", Foo(vec![10, 11]));
1238 #[stable(feature = "debug_builders", since = "1.2.0")]
1240 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1241 builders::debug_set_new(self)
1244 /// Creates a `DebugMap` builder designed to assist with creation of
1245 /// `fmt::Debug` implementations for map-like structures.
1252 /// struct Foo(Vec<(String, i32)>);
1254 /// impl fmt::Debug for Foo {
1255 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1256 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1260 /// // prints "{"A": 10, "B": 11}"
1261 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1263 #[stable(feature = "debug_builders", since = "1.2.0")]
1265 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1266 builders::debug_map_new(self)
1270 #[stable(since = "1.2.0", feature = "formatter_write")]
1271 impl<'a> Write for Formatter<'a> {
1272 fn write_str(&mut self, s: &str) -> Result {
1273 self.buf.write_str(s)
1276 fn write_char(&mut self, c: char) -> Result {
1277 self.buf.write_char(c)
1280 fn write_fmt(&mut self, args: Arguments) -> Result {
1281 write(self.buf, args)
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl Display for Error {
1287 fn fmt(&self, f: &mut Formatter) -> Result {
1288 Display::fmt("an error occurred when formatting an argument", f)
1292 // Implementations of the core formatting traits
1294 macro_rules! fmt_refs {
1295 ($($tr:ident),*) => {
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 impl<'a, T: ?Sized + $tr> $tr for &'a T {
1299 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1303 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1309 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl Debug for bool {
1313 fn fmt(&self, f: &mut Formatter) -> Result {
1314 Display::fmt(self, f)
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl Display for bool {
1320 fn fmt(&self, f: &mut Formatter) -> Result {
1321 Display::fmt(if *self { "true" } else { "false" }, f)
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 impl Debug for str {
1327 fn fmt(&self, f: &mut Formatter) -> Result {
1328 try!(f.write_char('"'));
1330 for (i, c) in self.char_indices() {
1331 let esc = c.escape_default();
1332 // If char needs escaping, flush backlog so far and write, else skip
1333 if esc.size_hint() != (1, Some(1)) {
1334 try!(f.write_str(&self[from..i]));
1336 try!(f.write_char(c));
1338 from = i + c.len_utf8();
1341 try!(f.write_str(&self[from..]));
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 impl Display for str {
1348 fn fmt(&self, f: &mut Formatter) -> Result {
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 impl Debug for char {
1355 fn fmt(&self, f: &mut Formatter) -> Result {
1356 try!(f.write_char('\''));
1357 for c in self.escape_default() {
1358 try!(f.write_char(c))
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 impl Display for char {
1366 fn fmt(&self, f: &mut Formatter) -> Result {
1367 if f.width.is_none() && f.precision.is_none() {
1370 let mut utf8 = [0; 4];
1371 let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
1372 let s: &str = unsafe { str::from_utf8_unchecked(&utf8[..amt]) };
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 impl<T> Pointer for *const T {
1380 fn fmt(&self, f: &mut Formatter) -> Result {
1381 let old_width = f.width;
1382 let old_flags = f.flags;
1384 // The alternate flag is already treated by LowerHex as being special-
1385 // it denotes whether to prefix with 0x. We use it to work out whether
1386 // or not to zero extend, and then unconditionally set it to get the
1389 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1391 if let None = f.width {
1392 f.width = Some((::usize::BITS/4) + 2);
1395 f.flags |= 1 << (FlagV1::Alternate as u32);
1397 let ret = LowerHex::fmt(&(*self as usize), f);
1399 f.width = old_width;
1400 f.flags = old_flags;
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 impl<T> Pointer for *mut T {
1408 fn fmt(&self, f: &mut Formatter) -> Result {
1409 // FIXME(#23542) Replace with type ascription.
1410 #![allow(trivial_casts)]
1411 Pointer::fmt(&(*self as *const T), f)
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 impl<'a, T> Pointer for &'a T {
1417 fn fmt(&self, f: &mut Formatter) -> Result {
1418 // FIXME(#23542) Replace with type ascription.
1419 #![allow(trivial_casts)]
1420 Pointer::fmt(&(*self as *const T), f)
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 impl<'a, T> Pointer for &'a mut T {
1426 fn fmt(&self, f: &mut Formatter) -> Result {
1427 // FIXME(#23542) Replace with type ascription.
1428 #![allow(trivial_casts)]
1429 Pointer::fmt(&(&**self as *const T), f)
1433 // Common code of floating point Debug and Display.
1434 fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
1435 where T: flt2dec::DecodableFloat
1437 let force_sign = fmt.sign_plus();
1438 let sign = match (force_sign, negative_zero) {
1439 (false, false) => flt2dec::Sign::Minus,
1440 (false, true) => flt2dec::Sign::MinusRaw,
1441 (true, false) => flt2dec::Sign::MinusPlus,
1442 (true, true) => flt2dec::Sign::MinusPlusRaw,
1445 let mut buf = [0; 1024]; // enough for f32 and f64
1446 let mut parts = [flt2dec::Part::Zero(0); 16];
1447 let formatted = if let Some(precision) = fmt.precision {
1448 flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1449 precision, false, &mut buf, &mut parts)
1451 flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1452 0, false, &mut buf, &mut parts)
1454 fmt.pad_formatted_parts(&formatted)
1457 // Common code of floating point LowerExp and UpperExp.
1458 fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
1459 where T: flt2dec::DecodableFloat
1461 let force_sign = fmt.sign_plus();
1462 let sign = match force_sign {
1463 false => flt2dec::Sign::Minus,
1464 true => flt2dec::Sign::MinusPlus,
1467 let mut buf = [0; 1024]; // enough for f32 and f64
1468 let mut parts = [flt2dec::Part::Zero(0); 16];
1469 let formatted = if let Some(precision) = fmt.precision {
1470 // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1471 flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1472 precision + 1, upper, &mut buf, &mut parts)
1474 flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1475 (0, 0), upper, &mut buf, &mut parts)
1477 fmt.pad_formatted_parts(&formatted)
1480 macro_rules! floating { ($ty:ident) => {
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 impl Debug for $ty {
1484 fn fmt(&self, fmt: &mut Formatter) -> Result {
1485 float_to_decimal_common(fmt, self, true)
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 impl Display for $ty {
1491 fn fmt(&self, fmt: &mut Formatter) -> Result {
1492 float_to_decimal_common(fmt, self, false)
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 impl LowerExp for $ty {
1498 fn fmt(&self, fmt: &mut Formatter) -> Result {
1499 float_to_exponential_common(fmt, self, false)
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl UpperExp for $ty {
1505 fn fmt(&self, fmt: &mut Formatter) -> Result {
1506 float_to_exponential_common(fmt, self, true)
1513 // Implementation of Display/Debug for various core types
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 impl<T> Debug for *const T {
1517 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<T> Debug for *mut T {
1521 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1525 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1528 macro_rules! tuple {
1530 ( $($name:ident,)+ ) => (
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 impl<$($name:Debug),*> Debug for ($($name,)*) {
1533 #[allow(non_snake_case, unused_assignments)]
1534 fn fmt(&self, f: &mut Formatter) -> Result {
1535 let mut builder = f.debug_tuple("");
1536 let ($(ref $name,)*) = *self;
1539 builder.field($name);
1544 try!(write!(builder.formatter(), ","));
1550 peel! { $($name,)* }
1554 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 impl<T: Debug> Debug for [T] {
1558 fn fmt(&self, f: &mut Formatter) -> Result {
1559 f.debug_list().entries(self.iter()).finish()
1563 #[stable(feature = "rust1", since = "1.0.0")]
1565 fn fmt(&self, f: &mut Formatter) -> Result {
1569 impl<T> Debug for PhantomData<T> {
1570 fn fmt(&self, f: &mut Formatter) -> Result {
1571 f.pad("PhantomData")
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl<T: Copy + Debug> Debug for Cell<T> {
1577 fn fmt(&self, f: &mut Formatter) -> Result {
1578 write!(f, "Cell {{ value: {:?} }}", self.get())
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1584 fn fmt(&self, f: &mut Formatter) -> Result {
1585 match self.borrow_state() {
1586 BorrowState::Unused | BorrowState::Reading => {
1587 write!(f, "RefCell {{ value: {:?} }}", self.borrow())
1589 BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
1594 #[stable(feature = "rust1", since = "1.0.0")]
1595 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1596 fn fmt(&self, f: &mut Formatter) -> Result {
1597 Debug::fmt(&**self, f)
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1603 fn fmt(&self, f: &mut Formatter) -> Result {
1604 Debug::fmt(&*(self.deref()), f)
1608 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1609 // it's a lot easier than creating all of the rt::Piece structures here.