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;
27 use str::{self, StrExt, Utf8Error};
29 // NOTE: for old macros; remove after the next snapshot
30 #[cfg(stage0)] use result::Result::Err;
32 pub use self::num::radix;
33 pub use self::num::Radix;
34 pub use self::num::RadixFmt;
40 #[experimental = "core and I/O reconciliation may alter this definition"]
41 /// The type returned by formatter methods.
42 pub type Result = result::Result<(), Error>;
44 /// The error type which is returned from formatting a message into a stream.
46 /// This type does not support transmission of an error other than that an error
47 /// occurred. Any extra information must be arranged to be transmitted through
49 #[experimental = "core and I/O reconciliation may alter this definition"]
53 /// A collection of methods that are required to format a message into a stream.
55 /// This trait is the type which this modules requires when formatting
56 /// information. This is similar to the standard library's `io::Writer` trait,
57 /// but it is only intended for use in libcore.
59 /// This trait should generally not be implemented by consumers of the standard
60 /// library. The `write!` macro accepts an instance of `io::Writer`, and the
61 /// `io::Writer` trait is favored over implementing this trait.
62 #[experimental = "waiting for core and I/O reconciliation"]
64 /// Writes a slice of bytes into this writer, returning whether the write
67 /// This method can only succeed if the entire byte slice was successfully
68 /// written, and this method will not return until all data has been
69 /// written or an error occurs.
73 /// This function will return an instance of `FormatError` on error.
74 fn write_str(&mut self, s: &str) -> Result;
76 /// Glue for usage of the `write!` macro with implementers of this trait.
78 /// This method should generally not be invoked manually, but rather through
79 /// the `write!` macro itself.
80 fn write_fmt(&mut self, args: Arguments) -> Result {
81 // This Adapter is needed to allow `self` (of type `&mut
82 // Self`) to be cast to a FormatWriter (below) without
83 // requiring a `Sized` bound.
84 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
86 impl<'a, T: ?Sized> Writer for Adapter<'a, T>
89 fn write_str(&mut self, s: &str) -> Result {
93 fn write_fmt(&mut self, args: Arguments) -> Result {
94 self.0.write_fmt(args)
98 write(&mut Adapter(self), args)
102 /// A struct to represent both where to emit formatting strings to and how they
103 /// should be formatted. A mutable version of this is passed to all formatting
105 #[unstable = "name may change and implemented traits are also unstable"]
106 pub struct Formatter<'a> {
109 align: rt::Alignment,
111 precision: Option<uint>,
113 buf: &'a mut (Writer+'a),
114 curarg: slice::Iter<'a, Argument<'a>>,
115 args: &'a [Argument<'a>],
118 // NB. Argument is essentially an optimized partially applied formatting function,
119 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
123 /// This struct represents the generic "argument" which is taken by the Xprintf
124 /// family of functions. It contains a function to format the given value. At
125 /// compile time it is ensured that the function and the value have the correct
126 /// types, and then this struct is used to canonicalize arguments to one type.
127 #[experimental = "implementation detail of the `format_args!` macro"]
129 pub struct Argument<'a> {
131 formatter: fn(&Void, &mut Formatter) -> Result,
134 impl<'a> Argument<'a> {
136 fn show_uint(x: &uint, f: &mut Formatter) -> Result {
140 fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter) -> Result) -> Argument<'b> {
143 formatter: mem::transmute(f),
144 value: mem::transmute(x)
149 fn from_uint(x: &uint) -> Argument {
150 Argument::new(x, Argument::show_uint)
153 fn as_uint(&self) -> Option<uint> {
154 if self.formatter as uint == Argument::show_uint as uint {
155 Some(unsafe { *(self.value as *const _ as *const uint) })
162 impl<'a> Arguments<'a> {
163 /// When using the format_args!() macro, this function is used to generate the
164 /// Arguments structure.
165 #[doc(hidden)] #[inline]
166 #[experimental = "implementation detail of the `format_args!` macro"]
167 pub fn new(pieces: &'a [&'a str],
168 args: &'a [Argument<'a>]) -> Arguments<'a> {
176 /// This function is used to specify nonstandard formatting parameters.
177 /// The `pieces` array must be at least as long as `fmt` to construct
178 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
179 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
180 /// created with `argumentuint`. However, failing to do so doesn't cause
181 /// unsafety, but will ignore invalid .
182 #[doc(hidden)] #[inline]
183 #[experimental = "implementation detail of the `format_args!` macro"]
184 pub fn with_placeholders(pieces: &'a [&'a str],
185 fmt: &'a [rt::Argument<'a>],
186 args: &'a [Argument<'a>]) -> Arguments<'a> {
195 /// This structure represents a safely precompiled version of a format string
196 /// and its arguments. This cannot be generated at runtime because it cannot
197 /// safely be done so, so no constructors are given and the fields are private
198 /// to prevent modification.
200 /// The `format_args!` macro will safely create an instance of this structure
201 /// and pass it to a function or closure, passed as the first argument. The
202 /// macro validates the format string at compile-time so usage of the `write`
203 /// and `format` functions can be safely performed.
206 pub struct Arguments<'a> {
207 // Format string pieces to print.
208 pieces: &'a [&'a str],
210 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
211 fmt: Option<&'a [rt::Argument<'a>]>,
213 // Dynamic arguments for interpolation, to be interleaved with string
214 // pieces. (Every argument is preceded by a string piece.)
215 args: &'a [Argument<'a>],
218 impl<'a> Show for Arguments<'a> {
219 fn fmt(&self, fmt: &mut Formatter) -> Result {
220 write(fmt.buf, *self)
224 /// When a format is not otherwise specified, types are formatted by ascribing
225 /// to this trait. There is not an explicit way of selecting this trait to be
226 /// used for formatting, it is only if no other format is specified.
227 #[unstable = "I/O and core have yet to be reconciled"]
229 /// Formats the value using the given formatter.
230 fn fmt(&self, &mut Formatter) -> Result;
234 /// Format trait for the `o` character
235 #[unstable = "I/O and core have yet to be reconciled"]
237 /// Formats the value using the given formatter.
238 fn fmt(&self, &mut Formatter) -> Result;
241 /// Format trait for the `b` character
242 #[unstable = "I/O and core have yet to be reconciled"]
244 /// Formats the value using the given formatter.
245 fn fmt(&self, &mut Formatter) -> Result;
248 /// Format trait for the `x` character
249 #[unstable = "I/O and core have yet to be reconciled"]
251 /// Formats the value using the given formatter.
252 fn fmt(&self, &mut Formatter) -> Result;
255 /// Format trait for the `X` character
256 #[unstable = "I/O and core have yet to be reconciled"]
258 /// Formats the value using the given formatter.
259 fn fmt(&self, &mut Formatter) -> Result;
262 /// Format trait for the `p` character
263 #[unstable = "I/O and core have yet to be reconciled"]
265 /// Formats the value using the given formatter.
266 fn fmt(&self, &mut Formatter) -> Result;
269 /// Format trait for the `e` character
270 #[unstable = "I/O and core have yet to be reconciled"]
272 /// Formats the value using the given formatter.
273 fn fmt(&self, &mut Formatter) -> Result;
276 /// Format trait for the `E` character
277 #[unstable = "I/O and core have yet to be reconciled"]
279 /// Formats the value using the given formatter.
280 fn fmt(&self, &mut Formatter) -> Result;
283 /// The `write` function takes an output stream, a precompiled format string,
284 /// and a list of arguments. The arguments will be formatted according to the
285 /// specified format string into the output stream provided.
289 /// * output - the buffer to write output to
290 /// * args - the precompiled arguments generated by `format_args!`
291 #[experimental = "libcore and I/O have yet to be reconciled, and this is an \
292 implementation detail which should not otherwise be exported"]
293 pub fn write(output: &mut Writer, args: Arguments) -> Result {
294 let mut formatter = Formatter {
299 align: rt::AlignUnknown,
302 curarg: args.args.iter(),
305 let mut pieces = args.pieces.iter();
309 // We can use default formatting parameters for all arguments.
310 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
311 try!(formatter.buf.write_str(*piece));
312 try!((arg.formatter)(arg.value, &mut formatter));
316 // Every spec has a corresponding argument that is preceded by
318 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
319 try!(formatter.buf.write_str(*piece));
320 try!(formatter.run(arg));
325 // There can be only one trailing string piece left.
326 match pieces.next() {
328 try!(formatter.buf.write_str(*piece));
336 impl<'a> Formatter<'a> {
338 // First up is the collection of functions used to execute a format string
339 // at runtime. This consumes all of the compile-time statics generated by
340 // the format! syntax extension.
341 fn run(&mut self, arg: &rt::Argument) -> Result {
342 // Fill in the format parameters into the formatter
343 self.fill = arg.format.fill;
344 self.align = arg.format.align;
345 self.flags = arg.format.flags;
346 self.width = self.getcount(&arg.format.width);
347 self.precision = self.getcount(&arg.format.precision);
349 // Extract the correct argument
350 let value = match arg.position {
351 rt::ArgumentNext => { *self.curarg.next().unwrap() }
352 rt::ArgumentIs(i) => self.args[i],
355 // Then actually do some printing
356 (value.formatter)(value.value, self)
359 fn getcount(&mut self, cnt: &rt::Count) -> Option<uint> {
361 rt::CountIs(n) => Some(n),
362 rt::CountImplied => None,
363 rt::CountIsParam(i) => {
364 self.args[i].as_uint()
366 rt::CountIsNextParam => {
367 self.curarg.next().and_then(|arg| arg.as_uint())
372 // Helper methods used for padding and processing formatting arguments that
373 // all formatting traits can use.
375 /// Performs the correct padding for an integer which has already been
376 /// emitted into a byte-array. The byte-array should *not* contain the sign
377 /// for the integer, that will be added by this method.
381 /// * is_positive - whether the original integer was positive or not.
382 /// * prefix - if the '#' character (FlagAlternate) is provided, this
383 /// is the prefix to put in front of the number.
384 /// * buf - the byte array that the number has been formatted into
386 /// This function will correctly account for the flags provided as well as
387 /// the minimum width. It will not take precision into account.
388 #[unstable = "definition may change slightly over time"]
389 pub fn pad_integral(&mut self,
395 use fmt::rt::{FlagAlternate, FlagSignPlus, FlagSignAwareZeroPad};
397 let mut width = buf.len();
401 sign = Some('-'); width += 1;
402 } else if self.flags & (1 << (FlagSignPlus as uint)) != 0 {
403 sign = Some('+'); width += 1;
406 let mut prefixed = false;
407 if self.flags & (1 << (FlagAlternate as uint)) != 0 {
408 prefixed = true; width += prefix.char_len();
411 // Writes the sign if it exists, and then the prefix if it was requested
412 let write_prefix = |&: f: &mut Formatter| {
413 for c in sign.into_iter() {
415 let n = c.encode_utf8(&mut b).unwrap_or(0);
416 let b = unsafe { str::from_utf8_unchecked(b[0..n]) };
417 try!(f.buf.write_str(b));
419 if prefixed { f.buf.write_str(prefix) }
423 // The `width` field is more of a `min-width` parameter at this point.
425 // If there's no minimum length requirements then we can just
428 try!(write_prefix(self)); self.buf.write_str(buf)
430 // Check if we're over the minimum width, if so then we can also
431 // just write the bytes.
432 Some(min) if width >= min => {
433 try!(write_prefix(self)); self.buf.write_str(buf)
435 // The sign and prefix goes before the padding if the fill character
437 Some(min) if self.flags & (1 << (FlagSignAwareZeroPad as uint)) != 0 => {
439 try!(write_prefix(self));
440 self.with_padding(min - width, rt::AlignRight, |f| {
444 // Otherwise, the sign and prefix goes after the padding
446 self.with_padding(min - width, rt::AlignRight, |f| {
447 try!(write_prefix(f)); f.buf.write_str(buf)
453 /// This function takes a string slice and emits it to the internal buffer
454 /// after applying the relevant formatting flags specified. The flags
455 /// recognized for generic strings are:
457 /// * width - the minimum width of what to emit
458 /// * fill/align - what to emit and where to emit it if the string
459 /// provided needs to be padded
460 /// * precision - the maximum length to emit, the string is truncated if it
461 /// is longer than this length
463 /// Notably this function ignored the `flag` parameters
464 #[unstable = "definition may change slightly over time"]
465 pub fn pad(&mut self, s: &str) -> Result {
466 // Make sure there's a fast path up front
467 if self.width.is_none() && self.precision.is_none() {
468 return self.buf.write_str(s);
470 // The `precision` field can be interpreted as a `max-width` for the
471 // string being formatted
472 match self.precision {
474 // If there's a maximum width and our string is longer than
475 // that, then we must always have truncation. This is the only
476 // case where the maximum length will matter.
477 let char_len = s.char_len();
479 let nchars = ::cmp::min(max, char_len);
480 return self.buf.write_str(s.slice_chars(0, nchars));
485 // The `width` field is more of a `min-width` parameter at this point.
487 // If we're under the maximum length, and there's no minimum length
488 // requirements, then we can just emit the string
489 None => self.buf.write_str(s),
490 // If we're under the maximum width, check if we're over the minimum
491 // width, if so it's as easy as just emitting the string.
492 Some(width) if s.char_len() >= width => {
493 self.buf.write_str(s)
495 // If we're under both the maximum and the minimum width, then fill
496 // up the minimum width with the specified string + some alignment.
498 self.with_padding(width - s.char_len(), rt::AlignLeft, |me| {
505 /// Runs a callback, emitting the correct padding either before or
506 /// afterwards depending on whether right or left alignment is requested.
507 fn with_padding<F>(&mut self, padding: uint, default: rt::Alignment, f: F) -> Result where
508 F: FnOnce(&mut Formatter) -> Result,
511 let align = match self.align {
512 rt::AlignUnknown => default,
516 let (pre_pad, post_pad) = match align {
517 rt::AlignLeft => (0u, padding),
518 rt::AlignRight | rt::AlignUnknown => (padding, 0u),
519 rt::AlignCenter => (padding / 2, (padding + 1) / 2),
522 let mut fill = [0u8; 4];
523 let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
524 let fill = unsafe { str::from_utf8_unchecked(fill[..len]) };
526 for _ in range(0, pre_pad) {
527 try!(self.buf.write_str(fill));
532 for _ in range(0, post_pad) {
533 try!(self.buf.write_str(fill));
539 /// Writes some data to the underlying buffer contained within this
541 #[unstable = "reconciling core and I/O may alter this definition"]
542 pub fn write_str(&mut self, data: &str) -> Result {
543 self.buf.write_str(data)
546 /// Writes some formatted information into this instance
547 #[unstable = "reconciling core and I/O may alter this definition"]
548 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
552 /// Flags for formatting (packed version of rt::Flag)
553 #[experimental = "return type may change and method was just created"]
554 pub fn flags(&self) -> uint { self.flags }
556 /// Character used as 'fill' whenever there is alignment
557 #[unstable = "method was just created"]
558 pub fn fill(&self) -> char { self.fill }
560 /// Flag indicating what form of alignment was requested
561 #[unstable = "method was just created"]
562 pub fn align(&self) -> rt::Alignment { self.align }
564 /// Optionally specified integer width that the output should be
565 #[unstable = "method was just created"]
566 pub fn width(&self) -> Option<uint> { self.width }
568 /// Optionally specified precision for numeric types
569 #[unstable = "method was just created"]
570 pub fn precision(&self) -> Option<uint> { self.precision }
573 impl Show for Error {
574 fn fmt(&self, f: &mut Formatter) -> Result {
575 "an error occurred when formatting an argument".fmt(f)
579 /// This is a function which calls are emitted to by the compiler itself to
580 /// create the Argument structures that are passed into the `format` function.
581 #[doc(hidden)] #[inline]
582 #[experimental = "implementation detail of the `format_args!` macro"]
583 pub fn argument<'a, T>(f: fn(&T, &mut Formatter) -> Result,
584 t: &'a T) -> Argument<'a> {
588 /// When the compiler determines that the type of an argument *must* be a uint
589 /// (such as for width and precision), then it invokes this method.
590 #[doc(hidden)] #[inline]
591 #[experimental = "implementation detail of the `format_args!` macro"]
592 pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
593 Argument::from_uint(s)
596 // Implementations of the core formatting traits
598 impl<'a, T: ?Sized + Show> Show for &'a T {
599 fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
601 impl<'a, T: ?Sized + Show> Show for &'a mut T {
602 fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
606 fn fmt(&self, f: &mut Formatter) -> Result {
607 Show::fmt(if *self { "true" } else { "false" }, f)
612 fn fmt(&self, f: &mut Formatter) -> Result {
618 fn fmt(&self, f: &mut Formatter) -> Result {
621 let mut utf8 = [0u8; 4];
622 let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
623 let s: &str = unsafe { mem::transmute(utf8[..amt]) };
628 impl<T> Pointer for *const T {
629 fn fmt(&self, f: &mut Formatter) -> Result {
630 f.flags |= 1 << (rt::FlagAlternate as uint);
631 let ret = LowerHex::fmt(&(*self as uint), f);
632 f.flags &= !(1 << (rt::FlagAlternate as uint));
637 impl<T> Pointer for *mut T {
638 fn fmt(&self, f: &mut Formatter) -> Result {
639 Pointer::fmt(&(*self as *const T), f)
643 impl<'a, T> Pointer for &'a T {
644 fn fmt(&self, f: &mut Formatter) -> Result {
645 Pointer::fmt(&(*self as *const T), f)
649 impl<'a, T> Pointer for &'a mut T {
650 fn fmt(&self, f: &mut Formatter) -> Result {
651 Pointer::fmt(&(&**self as *const T), f)
655 macro_rules! floating { ($ty:ident) => {
657 fn fmt(&self, fmt: &mut Formatter) -> Result {
660 let digits = match fmt.precision {
661 Some(i) => float::DigExact(i),
662 None => float::DigMax(6),
664 float::float_to_str_bytes_common(self.abs(),
672 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
677 impl LowerExp for $ty {
678 fn fmt(&self, fmt: &mut Formatter) -> Result {
681 let digits = match fmt.precision {
682 Some(i) => float::DigExact(i),
683 None => float::DigMax(6),
685 float::float_to_str_bytes_common(self.abs(),
693 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
698 impl UpperExp for $ty {
699 fn fmt(&self, fmt: &mut Formatter) -> Result {
702 let digits = match fmt.precision {
703 Some(i) => float::DigExact(i),
704 None => float::DigMax(6),
706 float::float_to_str_bytes_common(self.abs(),
714 fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
722 // Implementation of Show for various core types
724 impl<T> Show for *const T {
725 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
728 impl<T> Show for *mut T {
729 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
733 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
738 ( $($name:ident,)+ ) => (
739 impl<$($name:Show),*> Show for ($($name,)*) {
740 #[allow(non_snake_case, unused_assignments)]
741 fn fmt(&self, f: &mut Formatter) -> Result {
742 try!(write!(f, "("));
743 let ($(ref $name,)*) = *self;
747 try!(write!(f, ", "));
749 try!(write!(f, "{}", *$name));
753 try!(write!(f, ","));
762 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
764 impl<'a> Show for &'a (any::Any+'a) {
765 fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") }
768 impl<T: Show> Show for [T] {
769 fn fmt(&self, f: &mut Formatter) -> Result {
770 if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
771 try!(write!(f, "["));
773 let mut is_first = true;
774 for x in self.iter() {
778 try!(write!(f, ", "));
780 try!(write!(f, "{}", *x))
782 if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
783 try!(write!(f, "]"));
790 fn fmt(&self, f: &mut Formatter) -> Result {
795 impl<T: Copy + Show> Show for Cell<T> {
796 fn fmt(&self, f: &mut Formatter) -> Result {
797 write!(f, "Cell {{ value: {} }}", self.get())
801 impl<'b, T: Show> Show for Ref<'b, T> {
802 fn fmt(&self, f: &mut Formatter) -> Result {
807 impl<'b, T: Show> Show for RefMut<'b, T> {
808 fn fmt(&self, f: &mut Formatter) -> Result {
809 (*(self.deref())).fmt(f)
813 impl Show for Utf8Error {
814 fn fmt(&self, f: &mut Formatter) -> Result {
816 Utf8Error::InvalidByte(n) => {
817 write!(f, "invalid utf-8: invalid byte at index {}", n)
819 Utf8Error::TooShort => {
820 write!(f, "invalid utf-8: byte slice too short")
826 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
827 // it's a lot easier than creating all of the rt::Piece structures here.