1 // Copyright 2013-2014 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 #![allow(unused_variables)]
16 use cell::{Cell, Ref, RefMut};
17 use iter::{Iterator, IteratorExt, range};
18 use kinds::{Copy, Sized};
21 use option::Option::{Some, None};
22 use ops::{Deref, FnOnce};
23 use result::Result::{Ok, Err};
27 use str::{mod, StrExt, Utf8Error};
29 pub use self::num::radix;
30 pub use self::num::Radix;
31 pub use self::num::RadixFmt;
37 #[experimental = "core and I/O reconciliation may alter this definition"]
38 /// The type returned by formatter methods.
39 pub type Result = result::Result<(), Error>;
41 /// The error type which is returned from formatting a message into a stream.
43 /// This type does not support transmission of an error other than that an error
44 /// occurred. Any extra information must be arranged to be transmitted through
46 #[experimental = "core and I/O reconciliation may alter this definition"]
50 /// A collection of methods that are required to format a message into a stream.
52 /// This trait is the type which this modules requires when formatting
53 /// information. This is similar to the standard library's `io::Writer` trait,
54 /// but it is only intended for use in libcore.
56 /// This trait should generally not be implemented by consumers of the standard
57 /// library. The `write!` macro accepts an instance of `io::Writer`, and the
58 /// `io::Writer` trait is favored over implementing this trait.
59 #[experimental = "waiting for core and I/O reconciliation"]
61 /// Writes a slice of bytes into this writer, returning whether the write
64 /// This method can only succeed if the entire byte slice was successfully
65 /// written, and this method will not return until all data has been
66 /// written or an error occurs.
70 /// This function will return an instance of `FormatError` on error.
71 fn write_str(&mut self, s: &str) -> Result;
73 /// Glue for usage of the `write!` macro with implementers of this trait.
75 /// This method should generally not be invoked manually, but rather through
76 /// the `write!` macro itself.
77 fn write_fmt(&mut self, args: Arguments) -> Result { write(self, args) }
80 /// A struct to represent both where to emit formatting strings to and how they
81 /// should be formatted. A mutable version of this is passed to all formatting
83 #[unstable = "name may change and implemented traits are also unstable"]
84 pub struct Formatter<'a> {
89 precision: Option<uint>,
91 buf: &'a mut (Writer+'a),
92 curarg: slice::Iter<'a, Argument<'a>>,
93 args: &'a [Argument<'a>],
96 // NB. Argument is essentially an optimized partially applied formatting function,
97 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
101 /// This struct represents the generic "argument" which is taken by the Xprintf
102 /// family of functions. It contains a function to format the given value. At
103 /// compile time it is ensured that the function and the value have the correct
104 /// types, and then this struct is used to canonicalize arguments to one type.
105 #[experimental = "implementation detail of the `format_args!` macro"]
107 pub struct Argument<'a> {
109 formatter: fn(&Void, &mut Formatter) -> Result,
112 impl<'a> Argument<'a> {
114 fn show_uint(x: &uint, f: &mut Formatter) -> Result {
118 fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter) -> Result) -> Argument<'b> {
121 formatter: mem::transmute(f),
122 value: mem::transmute(x)
127 fn from_uint(x: &uint) -> Argument {
128 Argument::new(x, Argument::show_uint)
131 fn as_uint(&self) -> Option<uint> {
132 if self.formatter as uint == Argument::show_uint as uint {
133 Some(unsafe { *(self.value as *const _ as *const uint) })
140 impl<'a> Arguments<'a> {
141 /// When using the format_args!() macro, this function is used to generate the
142 /// Arguments structure.
143 #[doc(hidden)] #[inline]
144 #[experimental = "implementation detail of the `format_args!` macro"]
145 pub fn new(pieces: &'a [&'a str],
146 args: &'a [Argument<'a>]) -> Arguments<'a> {
154 /// This function is used to specify nonstandard formatting parameters.
155 /// The `pieces` array must be at least as long as `fmt` to construct
156 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
157 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
158 /// created with `argumentuint`. However, failing to do so doesn't cause
159 /// unsafety, but will ignore invalid .
160 #[doc(hidden)] #[inline]
161 #[experimental = "implementation detail of the `format_args!` macro"]
162 pub fn with_placeholders(pieces: &'a [&'a str],
163 fmt: &'a [rt::Argument<'a>],
164 args: &'a [Argument<'a>]) -> Arguments<'a> {
173 /// This structure represents a safely precompiled version of a format string
174 /// and its arguments. This cannot be generated at runtime because it cannot
175 /// safely be done so, so no constructors are given and the fields are private
176 /// to prevent modification.
178 /// The `format_args!` macro will safely create an instance of this structure
179 /// and pass it to a function or closure, passed as the first argument. The
180 /// macro validates the format string at compile-time so usage of the `write`
181 /// and `format` functions can be safely performed.
184 pub struct Arguments<'a> {
185 // Format string pieces to print.
186 pieces: &'a [&'a str],
188 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
189 fmt: Option<&'a [rt::Argument<'a>]>,
191 // Dynamic arguments for interpolation, to be interleaved with string
192 // pieces. (Every argument is preceded by a string piece.)
193 args: &'a [Argument<'a>],
196 impl<'a> Show for Arguments<'a> {
197 fn fmt(&self, fmt: &mut Formatter) -> Result {
198 write(fmt.buf, *self)
202 /// When a format is not otherwise specified, types are formatted by ascribing
203 /// to this trait. There is not an explicit way of selecting this trait to be
204 /// used for formatting, it is only if no other format is specified.
205 #[unstable = "I/O and core have yet to be reconciled"]
206 pub trait Show for Sized? {
207 /// Formats the value using the given formatter.
208 fn fmt(&self, &mut Formatter) -> Result;
212 /// Format trait for the `o` character
213 #[unstable = "I/O and core have yet to be reconciled"]
214 pub trait Octal for Sized? {
215 /// Formats the value using the given formatter.
216 fn fmt(&self, &mut Formatter) -> Result;
219 /// Format trait for the `b` character
220 #[unstable = "I/O and core have yet to be reconciled"]
221 pub trait Binary for Sized? {
222 /// Formats the value using the given formatter.
223 fn fmt(&self, &mut Formatter) -> Result;
226 /// Format trait for the `x` character
227 #[unstable = "I/O and core have yet to be reconciled"]
228 pub trait LowerHex for Sized? {
229 /// Formats the value using the given formatter.
230 fn fmt(&self, &mut Formatter) -> Result;
233 /// Format trait for the `X` character
234 #[unstable = "I/O and core have yet to be reconciled"]
235 pub trait UpperHex for Sized? {
236 /// Formats the value using the given formatter.
237 fn fmt(&self, &mut Formatter) -> Result;
240 /// Format trait for the `p` character
241 #[unstable = "I/O and core have yet to be reconciled"]
242 pub trait Pointer for Sized? {
243 /// Formats the value using the given formatter.
244 fn fmt(&self, &mut Formatter) -> Result;
247 /// Format trait for the `e` character
248 #[unstable = "I/O and core have yet to be reconciled"]
249 pub trait LowerExp for Sized? {
250 /// Formats the value using the given formatter.
251 fn fmt(&self, &mut Formatter) -> Result;
254 /// Format trait for the `E` character
255 #[unstable = "I/O and core have yet to be reconciled"]
256 pub trait UpperExp for Sized? {
257 /// Formats the value using the given formatter.
258 fn fmt(&self, &mut Formatter) -> Result;
261 /// The `write` function takes an output stream, a precompiled format string,
262 /// and a list of arguments. The arguments will be formatted according to the
263 /// specified format string into the output stream provided.
267 /// * output - the buffer to write output to
268 /// * args - the precompiled arguments generated by `format_args!`
269 #[experimental = "libcore and I/O have yet to be reconciled, and this is an \
270 implementation detail which should not otherwise be exported"]
271 pub fn write(output: &mut Writer, args: Arguments) -> Result {
272 let mut formatter = Formatter {
277 align: rt::AlignUnknown,
280 curarg: args.args.iter(),
283 let mut pieces = args.pieces.iter();
287 // We can use default formatting parameters for all arguments.
288 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
289 try!(formatter.buf.write_str(*piece));
290 try!((arg.formatter)(arg.value, &mut formatter));
294 // Every spec has a corresponding argument that is preceded by
296 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
297 try!(formatter.buf.write_str(*piece));
298 try!(formatter.run(arg));
303 // There can be only one trailing string piece left.
304 match pieces.next() {
306 try!(formatter.buf.write_str(*piece));
314 impl<'a> Formatter<'a> {
316 // First up is the collection of functions used to execute a format string
317 // at runtime. This consumes all of the compile-time statics generated by
318 // the format! syntax extension.
319 fn run(&mut self, arg: &rt::Argument) -> Result {
320 // Fill in the format parameters into the formatter
321 self.fill = arg.format.fill;
322 self.align = arg.format.align;
323 self.flags = arg.format.flags;
324 self.width = self.getcount(&arg.format.width);
325 self.precision = self.getcount(&arg.format.precision);
327 // Extract the correct argument
328 let value = match arg.position {
329 rt::ArgumentNext => { *self.curarg.next().unwrap() }
330 rt::ArgumentIs(i) => self.args[i],
333 // Then actually do some printing
334 (value.formatter)(value.value, self)
337 fn getcount(&mut self, cnt: &rt::Count) -> Option<uint> {
339 rt::CountIs(n) => Some(n),
340 rt::CountImplied => None,
341 rt::CountIsParam(i) => {
342 self.args[i].as_uint()
344 rt::CountIsNextParam => {
345 self.curarg.next().and_then(|arg| arg.as_uint())
350 // Helper methods used for padding and processing formatting arguments that
351 // all formatting traits can use.
353 /// Performs the correct padding for an integer which has already been
354 /// emitted into a byte-array. The byte-array should *not* contain the sign
355 /// for the integer, that will be added by this method.
359 /// * is_positive - whether the original integer was positive or not.
360 /// * prefix - if the '#' character (FlagAlternate) is provided, this
361 /// is the prefix to put in front of the number.
362 /// * buf - the byte array that the number has been formatted into
364 /// This function will correctly account for the flags provided as well as
365 /// the minimum width. It will not take precision into account.
366 #[unstable = "definition may change slightly over time"]
367 pub fn pad_integral(&mut self,
373 use fmt::rt::{FlagAlternate, FlagSignPlus, FlagSignAwareZeroPad};
375 let mut width = buf.len();
379 sign = Some('-'); width += 1;
380 } else if self.flags & (1 << (FlagSignPlus as uint)) != 0 {
381 sign = Some('+'); width += 1;
384 let mut prefixed = false;
385 if self.flags & (1 << (FlagAlternate as uint)) != 0 {
386 prefixed = true; width += prefix.char_len();
389 // Writes the sign if it exists, and then the prefix if it was requested
390 let write_prefix = |&: f: &mut Formatter| {
391 for c in sign.into_iter() {
393 let n = c.encode_utf8(&mut b).unwrap_or(0);
394 let b = unsafe { str::from_utf8_unchecked(b[0..n]) };
395 try!(f.buf.write_str(b));
397 if prefixed { f.buf.write_str(prefix) }
401 // The `width` field is more of a `min-width` parameter at this point.
403 // If there's no minimum length requirements then we can just
406 try!(write_prefix(self)); self.buf.write_str(buf)
408 // Check if we're over the minimum width, if so then we can also
409 // just write the bytes.
410 Some(min) if width >= min => {
411 try!(write_prefix(self)); self.buf.write_str(buf)
413 // The sign and prefix goes before the padding if the fill character
415 Some(min) if self.flags & (1 << (FlagSignAwareZeroPad as uint)) != 0 => {
417 try!(write_prefix(self));
418 self.with_padding(min - width, rt::AlignRight, |f| {
422 // Otherwise, the sign and prefix goes after the padding
424 self.with_padding(min - width, rt::AlignRight, |f| {
425 try!(write_prefix(f)); f.buf.write_str(buf)
431 /// This function takes a string slice and emits it to the internal buffer
432 /// after applying the relevant formatting flags specified. The flags
433 /// recognized for generic strings are:
435 /// * width - the minimum width of what to emit
436 /// * fill/align - what to emit and where to emit it if the string
437 /// provided needs to be padded
438 /// * precision - the maximum length to emit, the string is truncated if it
439 /// is longer than this length
441 /// Notably this function ignored the `flag` parameters
442 #[unstable = "definition may change slightly over time"]
443 pub fn pad(&mut self, s: &str) -> Result {
444 // Make sure there's a fast path up front
445 if self.width.is_none() && self.precision.is_none() {
446 return self.buf.write_str(s);
448 // The `precision` field can be interpreted as a `max-width` for the
449 // string being formatted
450 match self.precision {
452 // If there's a maximum width and our string is longer than
453 // that, then we must always have truncation. This is the only
454 // case where the maximum length will matter.
455 let char_len = s.char_len();
457 let nchars = ::cmp::min(max, char_len);
458 return self.buf.write_str(s.slice_chars(0, nchars));
463 // The `width` field is more of a `min-width` parameter at this point.
465 // If we're under the maximum length, and there's no minimum length
466 // requirements, then we can just emit the string
467 None => self.buf.write_str(s),
468 // If we're under the maximum width, check if we're over the minimum
469 // width, if so it's as easy as just emitting the string.
470 Some(width) if s.char_len() >= width => {
471 self.buf.write_str(s)
473 // If we're under both the maximum and the minimum width, then fill
474 // up the minimum width with the specified string + some alignment.
476 self.with_padding(width - s.char_len(), rt::AlignLeft, |me| {
483 /// Runs a callback, emitting the correct padding either before or
484 /// afterwards depending on whether right or left alignment is requested.
485 fn with_padding<F>(&mut self, padding: uint, default: rt::Alignment, f: F) -> Result where
486 F: FnOnce(&mut Formatter) -> Result,
489 let align = match self.align {
490 rt::AlignUnknown => default,
494 let (pre_pad, post_pad) = match align {
495 rt::AlignLeft => (0u, padding),
496 rt::AlignRight | rt::AlignUnknown => (padding, 0u),
497 rt::AlignCenter => (padding / 2, (padding + 1) / 2),
500 let mut fill = [0u8; 4];
501 let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
502 let fill = unsafe { str::from_utf8_unchecked(fill[..len]) };
504 for _ in range(0, pre_pad) {
505 try!(self.buf.write_str(fill));
510 for _ in range(0, post_pad) {
511 try!(self.buf.write_str(fill));
517 /// Writes some data to the underlying buffer contained within this
519 #[unstable = "reconciling core and I/O may alter this definition"]
520 pub fn write_str(&mut self, data: &str) -> Result {
521 self.buf.write_str(data)
524 /// Writes some formatted information into this instance
525 #[unstable = "reconciling core and I/O may alter this definition"]
526 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
530 /// Flags for formatting (packed version of rt::Flag)
531 #[experimental = "return type may change and method was just created"]
532 pub fn flags(&self) -> uint { self.flags }
534 /// Character used as 'fill' whenever there is alignment
535 #[unstable = "method was just created"]
536 pub fn fill(&self) -> char { self.fill }
538 /// Flag indicating what form of alignment was requested
539 #[unstable = "method was just created"]
540 pub fn align(&self) -> rt::Alignment { self.align }
542 /// Optionally specified integer width that the output should be
543 #[unstable = "method was just created"]
544 pub fn width(&self) -> Option<uint> { self.width }
546 /// Optionally specified precision for numeric types
547 #[unstable = "method was just created"]
548 pub fn precision(&self) -> Option<uint> { self.precision }
551 impl Show for Error {
552 fn fmt(&self, f: &mut Formatter) -> Result {
553 "an error occurred when formatting an argument".fmt(f)
557 /// This is a function which calls are emitted to by the compiler itself to
558 /// create the Argument structures that are passed into the `format` function.
559 #[doc(hidden)] #[inline]
560 #[experimental = "implementation detail of the `format_args!` macro"]
561 pub fn argument<'a, T>(f: fn(&T, &mut Formatter) -> Result,
562 t: &'a T) -> Argument<'a> {
566 /// When the compiler determines that the type of an argument *must* be a uint
567 /// (such as for width and precision), then it invokes this method.
568 #[doc(hidden)] #[inline]
569 #[experimental = "implementation detail of the `format_args!` macro"]
570 pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
571 Argument::from_uint(s)
574 // Implementations of the core formatting traits
576 impl<'a, Sized? T: Show> Show for &'a T {
577 fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
579 impl<'a, Sized? T: Show> Show for &'a mut T {
580 fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
582 impl<'a> Show for &'a (Show+'a) {
583 fn fmt(&self, f: &mut Formatter) -> Result { (*self).fmt(f) }
587 fn fmt(&self, f: &mut Formatter) -> Result {
588 Show::fmt(if *self { "true" } else { "false" }, f)
593 fn fmt(&self, f: &mut Formatter) -> Result {
599 fn fmt(&self, f: &mut Formatter) -> Result {
602 let mut utf8 = [0u8; 4];
603 let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
604 let s: &str = unsafe { mem::transmute(utf8[..amt]) };
609 impl<T> Pointer for *const T {
610 fn fmt(&self, f: &mut Formatter) -> Result {
611 f.flags |= 1 << (rt::FlagAlternate as uint);
612 let ret = LowerHex::fmt(&(*self as uint), f);
613 f.flags &= !(1 << (rt::FlagAlternate as uint));
618 impl<T> Pointer for *mut T {
619 fn fmt(&self, f: &mut Formatter) -> Result {
620 Pointer::fmt(&(*self as *const T), f)
624 impl<'a, T> Pointer for &'a T {
625 fn fmt(&self, f: &mut Formatter) -> Result {
626 Pointer::fmt(&(*self as *const T), f)
630 impl<'a, T> Pointer for &'a mut T {
631 fn fmt(&self, f: &mut Formatter) -> Result {
632 Pointer::fmt(&(&**self as *const T), f)
636 macro_rules! floating { ($ty:ident) => {
638 fn fmt(&self, fmt: &mut Formatter) -> Result {
641 let digits = match fmt.precision {
642 Some(i) => float::DigExact(i),
643 None => float::DigMax(6),
645 float::float_to_str_bytes_common(self.abs(),
653 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
658 impl LowerExp for $ty {
659 fn fmt(&self, fmt: &mut Formatter) -> Result {
662 let digits = match fmt.precision {
663 Some(i) => float::DigExact(i),
664 None => float::DigMax(6),
666 float::float_to_str_bytes_common(self.abs(),
674 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
679 impl UpperExp for $ty {
680 fn fmt(&self, fmt: &mut Formatter) -> Result {
683 let digits = match fmt.precision {
684 Some(i) => float::DigExact(i),
685 None => float::DigMax(6),
687 float::float_to_str_bytes_common(self.abs(),
695 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
703 // Implementation of Show for various core types
705 impl<T> Show for *const T {
706 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
709 impl<T> Show for *mut T {
710 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
714 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
719 ( $($name:ident,)+ ) => (
720 impl<$($name:Show),*> Show for ($($name,)*) {
721 #[allow(non_snake_case, unused_assignments)]
722 fn fmt(&self, f: &mut Formatter) -> Result {
723 try!(write!(f, "("));
724 let ($(ref $name,)*) = *self;
728 try!(write!(f, ", "));
730 try!(write!(f, "{}", *$name));
734 try!(write!(f, ","));
743 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
745 impl<'a> Show for &'a (any::Any+'a) {
746 fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") }
749 impl<T: Show> Show for [T] {
750 fn fmt(&self, f: &mut Formatter) -> Result {
751 if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
752 try!(write!(f, "["));
754 let mut is_first = true;
755 for x in self.iter() {
759 try!(write!(f, ", "));
761 try!(write!(f, "{}", *x))
763 if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
764 try!(write!(f, "]"));
771 fn fmt(&self, f: &mut Formatter) -> Result {
776 impl<T: Copy + Show> Show for Cell<T> {
777 fn fmt(&self, f: &mut Formatter) -> Result {
778 write!(f, "Cell {{ value: {} }}", self.get())
782 impl<'b, T: Show> Show for Ref<'b, T> {
783 fn fmt(&self, f: &mut Formatter) -> Result {
788 impl<'b, T: Show> Show for RefMut<'b, T> {
789 fn fmt(&self, f: &mut Formatter) -> Result {
790 (*(self.deref())).fmt(f)
794 impl Show for Utf8Error {
795 fn fmt(&self, f: &mut Formatter) -> Result {
797 Utf8Error::InvalidByte(n) => {
798 write!(f, "invalid utf-8: invalid byte at index {}", n)
800 Utf8Error::TooShort => {
801 write!(f, "invalid utf-8: byte slice too short")
807 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
808 // it's a lot easier than creating all of the rt::Piece structures here.