diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 1efb5956101..be8828b3ec8 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -12,8 +12,6 @@ #![allow(unused_variables)] -pub use self::FormatError::*; - use any; use cell::{Cell, Ref, RefMut}; use iter::{Iterator, range}; @@ -23,10 +21,9 @@ use option::{Option, Some, None}; use ops::Deref; use result::{Ok, Err}; use result; -use slice::{AsSlice, SlicePrelude}; +use slice::SlicePrelude; use slice; use str::StrPrelude; -use str; pub use self::num::radix; pub use self::num::Radix; @@ -36,18 +33,16 @@ mod num; mod float; pub mod rt; -pub type Result = result::Result<(), FormatError>; +#[experimental = "core and I/O reconciliation may alter this definition"] +pub type Result = result::Result<(), Error>; /// The error type which is returned from formatting a message into a stream. /// /// This type does not support transmission of an error other than that an error /// occurred. Any extra information must be arranged to be transmitted through /// some other means. -pub enum FormatError { - /// A generic write error occurred during formatting, no other information - /// is transmitted via this variant. - WriteError, -} +#[experimental = "core and I/O reconciliation may alter this definition"] +pub struct Error; /// A collection of methods that are required to format a message into a stream. /// @@ -58,6 +53,7 @@ pub enum FormatError { /// This trait should generally not be implemented by consumers of the standard /// library. The `write!` macro accepts an instance of `io::Writer`, and the /// `io::Writer` trait is favored over implementing this trait. +#[experimental = "waiting for core and I/O reconciliation"] pub trait FormatWriter { /// Writes a slice of bytes into this writer, returning whether the write /// succeeded. @@ -81,17 +77,13 @@ pub trait FormatWriter { /// A struct to represent both where to emit formatting strings to and how they /// should be formatted. A mutable version of this is passed to all formatting /// traits. +#[unstable = "name may change and implemented traits are also unstable"] pub struct Formatter<'a> { - /// Flags for formatting (packed version of rt::Flag) - pub flags: uint, - /// Character used as 'fill' whenever there is alignment - pub fill: char, - /// Boolean indication of whether the output should be left-aligned - pub align: rt::Alignment, - /// Optionally specified integer width that the output should be - pub width: Option, - /// Optionally specified precision for numeric types - pub precision: Option, + flags: uint, + fill: char, + align: rt::Alignment, + width: Option, + precision: Option, buf: &'a mut FormatWriter+'a, curarg: slice::Items<'a, Argument<'a>>, @@ -104,6 +96,7 @@ enum Void {} /// family of functions. It contains a function to format the given value. At /// compile time it is ensured that the function and the value have the correct /// types, and then this struct is used to canonicalize arguments to one type. +#[experimental = "implementation detail of the `format_args!` macro"] pub struct Argument<'a> { formatter: extern "Rust" fn(&Void, &mut Formatter) -> Result, value: &'a Void, @@ -115,6 +108,7 @@ impl<'a> Arguments<'a> { /// which is valid because the compiler performs all necessary validation to /// ensure that the resulting call to format/write would be safe. #[doc(hidden)] #[inline] + #[experimental = "implementation detail of the `format_args!` macro"] pub unsafe fn new<'a>(pieces: &'static [&'static str], args: &'a [Argument<'a>]) -> Arguments<'a> { Arguments { @@ -128,6 +122,7 @@ impl<'a> Arguments<'a> { /// The `pieces` array must be at least as long as `fmt` to construct /// a valid Arguments structure. #[doc(hidden)] #[inline] + #[experimental = "implementation detail of the `format_args!` macro"] pub unsafe fn with_placeholders<'a>(pieces: &'static [&'static str], fmt: &'static [rt::Argument<'static>], args: &'a [Argument<'a>]) -> Arguments<'a> { @@ -148,6 +143,7 @@ impl<'a> Arguments<'a> { /// and pass it to a function or closure, passed as the first argument. The /// macro validates the format string at compile-time so usage of the `write` /// and `format` functions can be safely performed. +#[stable] pub struct Arguments<'a> { // Format string pieces to print. pieces: &'a [&'a str], @@ -169,84 +165,57 @@ impl<'a> Show for Arguments<'a> { /// When a format is not otherwise specified, types are formatted by ascribing /// to this trait. There is not an explicit way of selecting this trait to be /// used for formatting, it is only if no other format is specified. +#[unstable = "I/O and core have yet to be reconciled"] pub trait Show for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } -/// Format trait for the `b` character -pub trait Bool for Sized? { - /// Formats the value using the given formatter. - fn fmt(&self, &mut Formatter) -> Result; -} - -/// Format trait for the `c` character -pub trait Char for Sized? { - /// Formats the value using the given formatter. - fn fmt(&self, &mut Formatter) -> Result; -} - -/// Format trait for the `i` and `d` characters -pub trait Signed for Sized? { - /// Formats the value using the given formatter. - fn fmt(&self, &mut Formatter) -> Result; -} - -/// Format trait for the `u` character -pub trait Unsigned for Sized? { - /// Formats the value using the given formatter. - fn fmt(&self, &mut Formatter) -> Result; -} /// Format trait for the `o` character +#[unstable = "I/O and core have yet to be reconciled"] pub trait Octal for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `t` character +#[unstable = "I/O and core have yet to be reconciled"] pub trait Binary for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `x` character +#[unstable = "I/O and core have yet to be reconciled"] pub trait LowerHex for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `X` character +#[unstable = "I/O and core have yet to be reconciled"] pub trait UpperHex for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } -/// Format trait for the `s` character -pub trait String for Sized? { - /// Formats the value using the given formatter. - fn fmt(&self, &mut Formatter) -> Result; -} - /// Format trait for the `p` character +#[unstable = "I/O and core have yet to be reconciled"] pub trait Pointer for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } -/// Format trait for the `f` character -pub trait Float for Sized? { - /// Formats the value using the given formatter. - fn fmt(&self, &mut Formatter) -> Result; -} - /// Format trait for the `e` character +#[unstable = "I/O and core have yet to be reconciled"] pub trait LowerExp for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } /// Format trait for the `E` character +#[unstable = "I/O and core have yet to be reconciled"] pub trait UpperExp for Sized? { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; @@ -271,6 +240,8 @@ static DEFAULT_ARGUMENT: rt::Argument<'static> = rt::Argument { /// /// * output - the buffer to write output to /// * args - the precompiled arguments generated by `format_args!` +#[experimental = "libcore and I/O have yet to be reconciled, and this is an \ + implementation detail which should not otherwise be exported"] pub fn write(output: &mut FormatWriter, args: &Arguments) -> Result { let mut formatter = Formatter { flags: 0, @@ -368,6 +339,7 @@ impl<'a> Formatter<'a> { /// /// This function will correctly account for the flags provided as well as /// the minimum width. It will not take precision into account. + #[unstable = "definition may change slightly over time"] pub fn pad_integral(&mut self, is_positive: bool, prefix: &str, @@ -440,6 +412,7 @@ impl<'a> Formatter<'a> { /// is longer than this length /// /// Notably this function ignored the `flag` parameters + #[unstable = "definition may change slightly over time"] pub fn pad(&mut self, s: &str) -> Result { // Make sure there's a fast path up front if self.width.is_none() && self.precision.is_none() { @@ -516,19 +489,48 @@ impl<'a> Formatter<'a> { /// Writes some data to the underlying buffer contained within this /// formatter. + #[unstable = "reconciling core and I/O may alter this definition"] pub fn write(&mut self, data: &[u8]) -> Result { self.buf.write(data) } /// Writes some formatted information into this instance + #[unstable = "reconciling core and I/O may alter this definition"] pub fn write_fmt(&mut self, fmt: &Arguments) -> Result { write(self.buf, fmt) } + + /// Flags for formatting (packed version of rt::Flag) + #[experimental = "return type may change and method was just created"] + pub fn flags(&self) -> uint { self.flags } + + /// Character used as 'fill' whenever there is alignment + #[unstable = "method was just created"] + pub fn fill(&self) -> char { self.fill } + + /// Flag indicating what form of alignment was requested + #[unstable = "method was just created"] + pub fn align(&self) -> rt::Alignment { self.align } + + /// Optionally specified integer width that the output should be + #[unstable = "method was just created"] + pub fn width(&self) -> Option { self.width } + + /// Optionally specified precision for numeric types + #[unstable = "method was just created"] + pub fn precision(&self) -> Option { self.precision } +} + +impl Show for Error { + fn fmt(&self, f: &mut Formatter) -> Result { + "an error occurred when formatting an argument".fmt(f) + } } /// This is a function which calls are emitted to by the compiler itself to /// create the Argument structures that are passed into the `format` function. #[doc(hidden)] #[inline] +#[experimental = "implementation detail of the `format_args!` macro"] pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result, t: &'a T) -> Argument<'a> { unsafe { @@ -542,15 +544,17 @@ pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result, /// When the compiler determines that the type of an argument *must* be a string /// (such as for select), then it invokes this method. #[doc(hidden)] #[inline] +#[experimental = "implementation detail of the `format_args!` macro"] pub fn argumentstr<'a>(s: &'a &str) -> Argument<'a> { - argument(String::fmt, s) + argument(Show::fmt, s) } /// When the compiler determines that the type of an argument *must* be a uint /// (such as for plural), then it invokes this method. #[doc(hidden)] #[inline] +#[experimental = "implementation detail of the `format_args!` macro"] pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> { - argument(Unsigned::fmt, s) + argument(Show::fmt, s) } // Implementations of the core formatting traits @@ -565,32 +569,26 @@ impl<'a> Show for &'a Show+'a { fn fmt(&self, f: &mut Formatter) -> Result { (*self).fmt(f) } } -impl Bool for bool { +impl Show for bool { fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt(if *self { "true" } else { "false" }, f) + Show::fmt(if *self { "true" } else { "false" }, f) } } -impl String for T { - fn fmt(&self, f: &mut Formatter) -> Result { - f.pad(self.as_slice()) - } -} - -impl String for str { +impl Show for str { fn fmt(&self, f: &mut Formatter) -> Result { f.pad(self) } } -impl Char for char { +impl Show for char { fn fmt(&self, f: &mut Formatter) -> Result { use char::Char; let mut utf8 = [0u8, ..4]; let amt = self.encode_utf8(&mut utf8).unwrap_or(0); let s: &str = unsafe { mem::transmute(utf8[..amt]) }; - String::fmt(s, f) + Show::fmt(s, f) } } @@ -620,7 +618,7 @@ impl<'a, T> Pointer for &'a mut T { } macro_rules! floating(($ty:ident) => { - impl Float for $ty { + impl Show for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -688,19 +686,6 @@ floating!(f64) // Implementation of Show for various core types -macro_rules! delegate(($ty:ty to $other:ident) => { - impl Show for $ty { - fn fmt(&self, f: &mut Formatter) -> Result { - $other::fmt(self, f) - } - } -}) -delegate!(str to String) -delegate!(bool to Bool) -delegate!(char to Char) -delegate!(f32 to Float) -delegate!(f64 to Float) - impl Show for *const T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index 0a5af56217c..1c856a6e208 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -109,6 +109,7 @@ radix!(UpperHex, 16, "0x", x @ 0 ... 9 => b'0' + x, /// A radix with in the range of `2..36`. #[deriving(Clone, PartialEq)] +#[unstable = "may be renamed or move to a different module"] pub struct Radix { base: u8, } @@ -132,6 +133,7 @@ impl GenericRadix for Radix { } /// A helper type for formatting radixes. +#[unstable = "may be renamed or move to a different module"] pub struct RadixFmt(T, R); /// Constructs a radix formatter in the range of `2..36`. @@ -142,6 +144,7 @@ pub struct RadixFmt(T, R); /// use std::fmt::radix; /// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string()); /// ``` +#[unstable = "may be renamed or move to a different module"] pub fn radix(x: T, base: u8) -> RadixFmt { RadixFmt(x, Radix::new(base)) } @@ -167,7 +170,6 @@ macro_rules! int_base { macro_rules! integer { ($Int:ident, $Uint:ident) => { int_base!(Show for $Int as $Int -> Decimal) - int_base!(Signed for $Int as $Int -> Decimal) int_base!(Binary for $Int as $Uint -> Binary) int_base!(Octal for $Int as $Uint -> Octal) int_base!(LowerHex for $Int as $Uint -> LowerHex) @@ -175,7 +177,6 @@ macro_rules! integer { radix_fmt!($Int as $Int, fmt_int) int_base!(Show for $Uint as $Uint -> Decimal) - int_base!(Unsigned for $Uint as $Uint -> Decimal) int_base!(Binary for $Uint as $Uint -> Binary) int_base!(Octal for $Uint as $Uint -> Octal) int_base!(LowerHex for $Uint as $Uint -> LowerHex) diff --git a/src/libcore/fmt/rt.rs b/src/libcore/fmt/rt.rs index 0e8504e7ee5..145e78dc668 100644 --- a/src/libcore/fmt/rt.rs +++ b/src/libcore/fmt/rt.rs @@ -14,6 +14,8 @@ //! These definitions are similar to their `ct` equivalents, but differ in that //! these can be statically allocated and are slightly optimized for the runtime +#![experimental = "implementation detail of the `format_args!` macro"] + pub use self::Alignment::*; pub use self::Count::*; pub use self::Position::*; diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index 9ba67bb2e47..9016f40b1b8 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -108,7 +108,10 @@ macro_rules! try( /// Writing a formatted string into a writer #[macro_export] macro_rules! write( - ($dst:expr, $($arg:tt)*) => (format_args_method!($dst, write_fmt, $($arg)*)) + ($dst:expr, $($arg:tt)*) => ({ + let dst = &mut *$dst; + format_args!(|args| { dst.write_fmt(args) }, $($arg)*) + }) ) /// Writing a formatted string plus a newline into a writer @@ -119,15 +122,5 @@ macro_rules! writeln( ) ) -/// Write some formatted data into a stream. -/// -/// Identical to the macro in `std::macros` -#[macro_export] -macro_rules! write( - ($dst:expr, $($arg:tt)*) => ({ - format_args_method!($dst, write_fmt, $($arg)*) - }) -) - #[macro_export] macro_rules! unreachable( () => (panic!("unreachable code")) ) diff --git a/src/libcoretest/fmt/num.rs b/src/libcoretest/fmt/num.rs index 868e14b928a..3b43d6ad33b 100644 --- a/src/libcoretest/fmt/num.rs +++ b/src/libcoretest/fmt/num.rs @@ -21,16 +21,16 @@ fn test_format_int() { assert!(format!("{}", 1i16).as_slice() == "1"); assert!(format!("{}", 1i32).as_slice() == "1"); assert!(format!("{}", 1i64).as_slice() == "1"); - assert!(format!("{:d}", -1i).as_slice() == "-1"); - assert!(format!("{:d}", -1i8).as_slice() == "-1"); - assert!(format!("{:d}", -1i16).as_slice() == "-1"); - assert!(format!("{:d}", -1i32).as_slice() == "-1"); - assert!(format!("{:d}", -1i64).as_slice() == "-1"); - assert!(format!("{:t}", 1i).as_slice() == "1"); - assert!(format!("{:t}", 1i8).as_slice() == "1"); - assert!(format!("{:t}", 1i16).as_slice() == "1"); - assert!(format!("{:t}", 1i32).as_slice() == "1"); - assert!(format!("{:t}", 1i64).as_slice() == "1"); + assert!(format!("{}", -1i).as_slice() == "-1"); + assert!(format!("{}", -1i8).as_slice() == "-1"); + assert!(format!("{}", -1i16).as_slice() == "-1"); + assert!(format!("{}", -1i32).as_slice() == "-1"); + assert!(format!("{}", -1i64).as_slice() == "-1"); + assert!(format!("{:b}", 1i).as_slice() == "1"); + assert!(format!("{:b}", 1i8).as_slice() == "1"); + assert!(format!("{:b}", 1i16).as_slice() == "1"); + assert!(format!("{:b}", 1i32).as_slice() == "1"); + assert!(format!("{:b}", 1i64).as_slice() == "1"); assert!(format!("{:x}", 1i).as_slice() == "1"); assert!(format!("{:x}", 1i8).as_slice() == "1"); assert!(format!("{:x}", 1i16).as_slice() == "1"); @@ -52,16 +52,11 @@ fn test_format_int() { assert!(format!("{}", 1u16).as_slice() == "1"); assert!(format!("{}", 1u32).as_slice() == "1"); assert!(format!("{}", 1u64).as_slice() == "1"); - assert!(format!("{:u}", 1u).as_slice() == "1"); - assert!(format!("{:u}", 1u8).as_slice() == "1"); - assert!(format!("{:u}", 1u16).as_slice() == "1"); - assert!(format!("{:u}", 1u32).as_slice() == "1"); - assert!(format!("{:u}", 1u64).as_slice() == "1"); - assert!(format!("{:t}", 1u).as_slice() == "1"); - assert!(format!("{:t}", 1u8).as_slice() == "1"); - assert!(format!("{:t}", 1u16).as_slice() == "1"); - assert!(format!("{:t}", 1u32).as_slice() == "1"); - assert!(format!("{:t}", 1u64).as_slice() == "1"); + assert!(format!("{:b}", 1u).as_slice() == "1"); + assert!(format!("{:b}", 1u8).as_slice() == "1"); + assert!(format!("{:b}", 1u16).as_slice() == "1"); + assert!(format!("{:b}", 1u32).as_slice() == "1"); + assert!(format!("{:b}", 1u64).as_slice() == "1"); assert!(format!("{:x}", 1u).as_slice() == "1"); assert!(format!("{:x}", 1u8).as_slice() == "1"); assert!(format!("{:x}", 1u16).as_slice() == "1"); @@ -79,9 +74,9 @@ fn test_format_int() { assert!(format!("{:o}", 1u64).as_slice() == "1"); // Test a larger number - assert!(format!("{:t}", 55i).as_slice() == "110111"); + assert!(format!("{:b}", 55i).as_slice() == "110111"); assert!(format!("{:o}", 55i).as_slice() == "67"); - assert!(format!("{:d}", 55i).as_slice() == "55"); + assert!(format!("{}", 55i).as_slice() == "55"); assert!(format!("{:x}", 55i).as_slice() == "37"); assert!(format!("{:X}", 55i).as_slice() == "37"); } @@ -89,15 +84,13 @@ fn test_format_int() { #[test] fn test_format_int_zero() { assert!(format!("{}", 0i).as_slice() == "0"); - assert!(format!("{:d}", 0i).as_slice() == "0"); - assert!(format!("{:t}", 0i).as_slice() == "0"); + assert!(format!("{:b}", 0i).as_slice() == "0"); assert!(format!("{:o}", 0i).as_slice() == "0"); assert!(format!("{:x}", 0i).as_slice() == "0"); assert!(format!("{:X}", 0i).as_slice() == "0"); assert!(format!("{}", 0u).as_slice() == "0"); - assert!(format!("{:u}", 0u).as_slice() == "0"); - assert!(format!("{:t}", 0u).as_slice() == "0"); + assert!(format!("{:b}", 0u).as_slice() == "0"); assert!(format!("{:o}", 0u).as_slice() == "0"); assert!(format!("{:x}", 0u).as_slice() == "0"); assert!(format!("{:X}", 0u).as_slice() == "0"); @@ -105,11 +98,11 @@ fn test_format_int_zero() { #[test] fn test_format_int_flags() { - assert!(format!("{:3d}", 1i).as_slice() == " 1"); - assert!(format!("{:>3d}", 1i).as_slice() == " 1"); - assert!(format!("{:>+3d}", 1i).as_slice() == " +1"); - assert!(format!("{:<3d}", 1i).as_slice() == "1 "); - assert!(format!("{:#d}", 1i).as_slice() == "1"); + assert!(format!("{:3}", 1i).as_slice() == " 1"); + assert!(format!("{:>3}", 1i).as_slice() == " 1"); + assert!(format!("{:>+3}", 1i).as_slice() == " +1"); + assert!(format!("{:<3}", 1i).as_slice() == "1 "); + assert!(format!("{:#}", 1i).as_slice() == "1"); assert!(format!("{:#x}", 10i).as_slice() == "0xa"); assert!(format!("{:#X}", 10i).as_slice() == "0xA"); assert!(format!("{:#5x}", 10i).as_slice() == " 0xa"); @@ -119,25 +112,25 @@ fn test_format_int_flags() { assert!(format!("{:<8x}", 10i).as_slice() == "a "); assert!(format!("{:>8x}", 10i).as_slice() == " a"); assert!(format!("{:#08x}", 10i).as_slice() == "0x00000a"); - assert!(format!("{:08d}", -10i).as_slice() == "-0000010"); + assert!(format!("{:08}", -10i).as_slice() == "-0000010"); assert!(format!("{:x}", -1u8).as_slice() == "ff"); assert!(format!("{:X}", -1u8).as_slice() == "FF"); - assert!(format!("{:t}", -1u8).as_slice() == "11111111"); + assert!(format!("{:b}", -1u8).as_slice() == "11111111"); assert!(format!("{:o}", -1u8).as_slice() == "377"); assert!(format!("{:#x}", -1u8).as_slice() == "0xff"); assert!(format!("{:#X}", -1u8).as_slice() == "0xFF"); - assert!(format!("{:#t}", -1u8).as_slice() == "0b11111111"); + assert!(format!("{:#b}", -1u8).as_slice() == "0b11111111"); assert!(format!("{:#o}", -1u8).as_slice() == "0o377"); } #[test] fn test_format_int_sign_padding() { - assert!(format!("{:+5d}", 1i).as_slice() == " +1"); - assert!(format!("{:+5d}", -1i).as_slice() == " -1"); - assert!(format!("{:05d}", 1i).as_slice() == "00001"); - assert!(format!("{:05d}", -1i).as_slice() == "-0001"); - assert!(format!("{:+05d}", 1i).as_slice() == "+0001"); - assert!(format!("{:+05d}", -1i).as_slice() == "-0001"); + assert!(format!("{:+5}", 1i).as_slice() == " +1"); + assert!(format!("{:+5}", -1i).as_slice() == " -1"); + assert!(format!("{:05}", 1i).as_slice() == "00001"); + assert!(format!("{:05}", -1i).as_slice() == "-0001"); + assert!(format!("{:+05}", 1i).as_slice() == "+0001"); + assert!(format!("{:+05}", -1i).as_slice() == "-0001"); } #[test] @@ -169,7 +162,7 @@ mod uint { #[bench] fn format_bin(b: &mut Bencher) { let mut rng = weak_rng(); - b.iter(|| { format!("{:t}", rng.gen::()); }) + b.iter(|| { format!("{:b}", rng.gen::()); }) } #[bench] @@ -181,7 +174,7 @@ mod uint { #[bench] fn format_dec(b: &mut Bencher) { let mut rng = weak_rng(); - b.iter(|| { format!("{:u}", rng.gen::()); }) + b.iter(|| { format!("{}", rng.gen::()); }) } #[bench] @@ -205,7 +198,7 @@ mod int { #[bench] fn format_bin(b: &mut Bencher) { let mut rng = weak_rng(); - b.iter(|| { format!("{:t}", rng.gen::()); }) + b.iter(|| { format!("{:b}", rng.gen::()); }) } #[bench] @@ -217,7 +210,7 @@ mod int { #[bench] fn format_dec(b: &mut Bencher) { let mut rng = weak_rng(); - b.iter(|| { format!("{:d}", rng.gen::()); }) + b.iter(|| { format!("{}", rng.gen::()); }) } #[bench] diff --git a/src/libflate/lib.rs b/src/libflate/lib.rs index e5bd81cb816..568210118a8 100644 --- a/src/libflate/lib.rs +++ b/src/libflate/lib.rs @@ -130,7 +130,7 @@ mod tests { input.len()); let cmp = deflate_bytes(input.as_slice()).expect("deflation failed"); let out = inflate_bytes(cmp.as_slice()).expect("inflation failed"); - debug!("{} bytes deflated to {} ({:.1f}% size)", + debug!("{} bytes deflated to {} ({:.1}% size)", input.len(), cmp.len(), 100.0 * ((cmp.len() as f64) / (input.len() as f64))); assert_eq!(input.as_slice(), out.as_slice()); diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index cd9ef215720..df8cdabbcaa 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -221,7 +221,7 @@ pub fn render_to(output: &mut W) { impl<'a> dot::Labeller<'a, Nd<'a>, Ed<'a>> for Graph { fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new("example3").unwrap() } fn node_id(&'a self, n: &Nd<'a>) -> dot::Id<'a> { - dot::Id::new(format!("N{:u}", n.val0())).unwrap() + dot::Id::new(format!("N{}", n.val0())).unwrap() } fn node_label<'a>(&'a self, n: &Nd<'a>) -> dot::LabelText<'a> { let &(i, _) = n; @@ -635,7 +635,7 @@ mod tests { } fn id_name<'a>(n: &Node) -> Id<'a> { - Id::new(format!("N{:u}", *n)).unwrap() + Id::new(format!("N{}", *n)).unwrap() } impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraph { diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index 2e60ce31d5e..fd2d97d4deb 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -241,13 +241,6 @@ impl fmt::Show for LogLevel { } } -impl fmt::Signed for LogLevel { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - let LogLevel(level) = *self; - write!(fmt, "{}", level) - } -} - impl Logger for DefaultLogger { fn log(&mut self, record: &LogRecord) { match writeln!(&mut self.handle, diff --git a/src/librand/lib.rs b/src/librand/lib.rs index 117cca1b8b5..d6a68dd07d7 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -237,7 +237,7 @@ pub trait Rng { /// use std::rand::{task_rng, Rng}; /// /// let mut rng = task_rng(); - /// println!("{:b}", rng.gen_weighted_bool(3)); + /// println!("{}", rng.gen_weighted_bool(3)); /// ``` fn gen_weighted_bool(&mut self, n: uint) -> bool { n == 0 || self.gen_range(0, n) == 0 diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index d7925177c29..62032beaacd 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -102,7 +102,7 @@ pub fn check_crate(tcx: &ty::ctxt) { fn make_stat(bccx: &BorrowckCtxt, stat: uint) -> String { let total = bccx.stats.guaranteed_paths as f64; let perc = if total == 0.0 { 0.0 } else { stat as f64 * 100.0 / total }; - format!("{} ({:.0f}%)", stat, perc) + format!("{} ({:.0}%)", stat, perc) } } diff --git a/src/librustc/middle/cfg/graphviz.rs b/src/librustc/middle/cfg/graphviz.rs index 78b3a1179ca..ba6dd2a5107 100644 --- a/src/librustc/middle/cfg/graphviz.rs +++ b/src/librustc/middle/cfg/graphviz.rs @@ -53,7 +53,7 @@ impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> { fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(self.name.as_slice()).unwrap() } fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> { - dot::Id::new(format!("N{:u}", i.node_id())).unwrap() + dot::Id::new(format!("N{}", i.node_id())).unwrap() } fn node_label(&'a self, &(i, n): &Node<'a>) -> dot::LabelText<'a> { diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index c733084e981..6881f75ac18 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -81,8 +81,7 @@ impl<'a> fmt::Show for Matrix<'a> { try!(write!(f, "+")); for (column, pat_str) in row.into_iter().enumerate() { try!(write!(f, " ")); - f.width = Some(column_widths[column]); - try!(f.pad(pat_str.as_slice())); + try!(write!(f, "{:1$}", pat_str, column_widths[column])); try!(write!(f, " +")); } try!(write!(f, "\n")); diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 366f4bd0249..141504cb6f7 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -194,7 +194,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let words_per_id = (bits_per_id + uint::BITS - 1) / uint::BITS; let num_nodes = cfg.graph.all_nodes().len(); - debug!("DataFlowContext::new(analysis_name: {:s}, id_range={}, \ + debug!("DataFlowContext::new(analysis_name: {}, id_range={}, \ bits_per_id={}, words_per_id={}) \ num_nodes: {}", analysis_name, id_range, bits_per_id, words_per_id, @@ -223,7 +223,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { pub fn add_gen(&mut self, id: ast::NodeId, bit: uint) { //! Indicates that `id` generates `bit` - debug!("{:s} add_gen(id={}, bit={})", + debug!("{} add_gen(id={}, bit={})", self.analysis_name, id, bit); assert!(self.nodeid_to_index.contains_key(&id)); assert!(self.bits_per_id > 0); @@ -236,7 +236,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { pub fn add_kill(&mut self, id: ast::NodeId, bit: uint) { //! Indicates that `id` kills `bit` - debug!("{:s} add_kill(id={}, bit={})", + debug!("{} add_kill(id={}, bit={})", self.analysis_name, id, bit); assert!(self.nodeid_to_index.contains_key(&id)); assert!(self.bits_per_id > 0); @@ -249,7 +249,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { fn apply_gen_kill(&self, cfgidx: CFGIndex, bits: &mut [uint]) { //! Applies the gen and kill sets for `cfgidx` to `bits` - debug!("{:s} apply_gen_kill(cfgidx={}, bits={}) [before]", + debug!("{} apply_gen_kill(cfgidx={}, bits={}) [before]", self.analysis_name, cfgidx, mut_bits_to_string(bits)); assert!(self.bits_per_id > 0); @@ -259,7 +259,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let kills = self.kills.slice(start, end); bitwise(bits, kills, &Subtract); - debug!("{:s} apply_gen_kill(cfgidx={}, bits={}) [after]", + debug!("{} apply_gen_kill(cfgidx={}, bits={}) [after]", self.analysis_name, cfgidx, mut_bits_to_string(bits)); } @@ -316,7 +316,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { temp_bits.as_slice() } }; - debug!("{:s} each_bit_for_node({}, cfgidx={}) bits={}", + debug!("{} each_bit_for_node({}, cfgidx={}) bits={}", self.analysis_name, e, cfgidx, bits_to_string(slice)); self.each_bit(slice, f) } @@ -337,7 +337,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let cfgidx = to_cfgidx_or_die(id, &self.nodeid_to_index); let (start, end) = self.compute_id_range(cfgidx); let gens = self.gens.slice(start, end); - debug!("{:s} each_gen_bit(id={}, gens={})", + debug!("{} each_gen_bit(id={}, gens={})", self.analysis_name, id, bits_to_string(gens)); self.each_bit(gens, f) } @@ -385,7 +385,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { //! This is usually called (if it is called at all), after //! all add_gen and add_kill calls, but before propagate. - debug!("{:s} add_kills_from_flow_exits", self.analysis_name); + debug!("{} add_kills_from_flow_exits", self.analysis_name); if self.bits_per_id == 0 { // Skip the surprisingly common degenerate case. (Note // compute_id_range requires self.words_per_id > 0.) @@ -408,7 +408,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { } } None => { - debug!("{:s} add_kills_from_flow_exits flow_exit={} \ + debug!("{} add_kills_from_flow_exits flow_exit={} \ no cfg_idx for exiting_scope={}", self.analysis_name, flow_exit, node_id); } @@ -417,10 +417,10 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { if changed { let bits = self.kills.slice_mut(start, end); - debug!("{:s} add_kills_from_flow_exits flow_exit={} bits={} [before]", + debug!("{} add_kills_from_flow_exits flow_exit={} bits={} [before]", self.analysis_name, flow_exit, mut_bits_to_string(bits)); bits.clone_from_slice(orig_kills.as_slice()); - debug!("{:s} add_kills_from_flow_exits flow_exit={} bits={} [after]", + debug!("{} add_kills_from_flow_exits flow_exit={} bits={} [after]", self.analysis_name, flow_exit, mut_bits_to_string(bits)); } true @@ -453,7 +453,7 @@ impl<'a, 'tcx, O:DataFlowOperator+Clone+'static> DataFlowContext<'a, 'tcx, O> { } } - debug!("Dataflow result for {:s}:", self.analysis_name); + debug!("Dataflow result for {}:", self.analysis_name); debug!("{}", { self.pretty_print_to(box io::stderr(), blk).unwrap(); "" @@ -474,7 +474,7 @@ impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> { fn walk_cfg(&mut self, cfg: &cfg::CFG, in_out: &mut [uint]) { - debug!("DataFlowContext::walk_cfg(in_out={}) {:s}", + debug!("DataFlowContext::walk_cfg(in_out={}) {}", bits_to_string(in_out), self.dfcx.analysis_name); assert!(self.dfcx.bits_per_id > 0); @@ -519,7 +519,7 @@ impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> { edge: &cfg::CFGEdge) { let source = edge.source(); let cfgidx = edge.target(); - debug!("{:s} propagate_bits_into_entry_set_for(pred_bits={}, {} to {})", + debug!("{} propagate_bits_into_entry_set_for(pred_bits={}, {} to {})", self.dfcx.analysis_name, bits_to_string(pred_bits), source, cfgidx); assert!(self.dfcx.bits_per_id > 0); @@ -530,7 +530,7 @@ impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> { bitwise(on_entry, pred_bits, &self.dfcx.oper) }; if changed { - debug!("{:s} changed entry set for {} to {}", + debug!("{} changed entry set for {} to {}", self.dfcx.analysis_name, cfgidx, bits_to_string(self.dfcx.on_entry.slice(start, end))); self.changed = true; diff --git a/src/librustc/middle/graph.rs b/src/librustc/middle/graph.rs index d2a7ec1e186..ac132477b87 100644 --- a/src/librustc/middle/graph.rs +++ b/src/librustc/middle/graph.rs @@ -36,7 +36,7 @@ be indexed by the direction (see the type `Direction`). #![allow(dead_code)] // still WIP -use std::fmt::{Formatter, FormatError, Show}; +use std::fmt::{Formatter, Error, Show}; use std::uint; pub struct Graph { @@ -57,7 +57,7 @@ pub struct Edge { } impl Show for Edge { - fn fmt(&self, f: &mut Formatter) -> Result<(), FormatError> { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { write!(f, "Edge {{ next_edge: [{}, {}], source: {}, target: {}, data: {} }}", self.next_edge[0], self.next_edge[1], self.source, self.target, self.data) diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 9f90afa3749..70567f52c06 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -2678,9 +2678,14 @@ impl ops::Sub for TypeContents { } impl fmt::Show for TypeContents { + #[cfg(stage0)] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TypeContents({:t})", self.bits) } + #[cfg(not(stage0))] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TypeContents({:b})", self.bits) + } } pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool { diff --git a/src/librustc/middle/typeck/variance.rs b/src/librustc/middle/typeck/variance.rs index 76250d44baf..dfc9f392452 100644 --- a/src/librustc/middle/typeck/variance.rs +++ b/src/librustc/middle/typeck/variance.rs @@ -603,7 +603,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { let is_inferred; macro_rules! cannot_happen { () => { { - panic!("invalid parent: {:s} for {:s}", + panic!("invalid parent: {} for {}", tcx.map.node_to_string(parent_id), tcx.map.node_to_string(param_id)); } } } diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index abf29fe3a4c..47bba3e4327 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -368,7 +368,7 @@ unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_vo if enabled { let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc); - cgcx.handler.note(format!("optimization {:s} for {:s} at {:s}: {:s}", + cgcx.handler.note(format!("optimization {} for {} at {}: {}", opt.kind.describe(), pass_name, if loc.is_empty() { "[unknown]" } else { loc.as_slice() }, diff --git a/src/librustc_trans/driver/mod.rs b/src/librustc_trans/driver/mod.rs index 8985d05b6ca..a73afdf68e3 100644 --- a/src/librustc_trans/driver/mod.rs +++ b/src/librustc_trans/driver/mod.rs @@ -224,13 +224,13 @@ Available lint options: }; println!("Lint checks provided by rustc:\n"); - println!(" {} {:7.7s} {}", padded("name"), "default", "meaning"); - println!(" {} {:7.7s} {}", padded("----"), "-------", "-------"); + println!(" {} {:7.7} {}", padded("name"), "default", "meaning"); + println!(" {} {:7.7} {}", padded("----"), "-------", "-------"); let print_lints = |lints: Vec<&Lint>| { for lint in lints.into_iter() { let name = lint.name_lower().replace("_", "-"); - println!(" {} {:7.7s} {}", + println!(" {} {:7.7} {}", padded(name.as_slice()), lint.default_level.as_str(), lint.desc); } println!("\n"); @@ -293,7 +293,7 @@ fn describe_debug_flags() { for tuple in r.iter() { match *tuple { (ref name, ref desc, _) => { - println!(" -Z {:>20s} -- {}", *name, *desc); + println!(" -Z {:>20} -- {}", *name, *desc); } } } @@ -306,7 +306,7 @@ fn describe_codegen_flags() { Some(..) => (21, "=val"), None => (25, "") }; - println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"), + println!(" -C {:>width$}{} -- {}", name.replace("_", "-"), extra, desc, width=width); } } diff --git a/src/librustc_trans/driver/pretty.rs b/src/librustc_trans/driver/pretty.rs index c20f2e097f3..420a0ed5e8a 100644 --- a/src/librustc_trans/driver/pretty.rs +++ b/src/librustc_trans/driver/pretty.rs @@ -355,8 +355,8 @@ impl UserIdentifiedItem { fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId { let fail_because = |is_wrong_because| -> ast::NodeId { let message = - format!("{:s} needs NodeId (int) or unique \ - path suffix (b::c::d); got {:s}, which {:s}", + format!("{} needs NodeId (int) or unique \ + path suffix (b::c::d); got {}, which {}", user_option, self.reconstructed_input(), is_wrong_because); diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index 9c4a532790d..98cdea73a99 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -3135,7 +3135,7 @@ pub fn trans_crate<'tcx>(analysis: CrateAnalysis<'tcx>) } if shared_ccx.sess().count_llvm_insns() { for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() { - println!("{:7u} {}", *v, *k); + println!("{:7} {}", *v, *k); } } diff --git a/src/librustc_trans/trans/cleanup.rs b/src/librustc_trans/trans/cleanup.rs index 02909b0e3a9..58c67c8c091 100644 --- a/src/librustc_trans/trans/cleanup.rs +++ b/src/librustc_trans/trans/cleanup.rs @@ -67,7 +67,7 @@ pub enum CleanupScopeKind<'blk, 'tcx: 'blk> { } impl<'blk, 'tcx: 'blk> fmt::Show for CleanupScopeKind<'blk, 'tcx> { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::FormatError> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { CustomScopeKind => write!(f, "CustomScopeKind"), AstScopeKind(nid) => write!(f, "AstScopeKind({})", nid), diff --git a/src/librustdoc/html/item_type.rs b/src/librustdoc/html/item_type.rs index 901761ba806..daa5f155d51 100644 --- a/src/librustdoc/html/item_type.rs +++ b/src/librustdoc/html/item_type.rs @@ -75,12 +75,6 @@ impl fmt::Show for ItemType { } } -impl fmt::Unsigned for ItemType { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - (*self as uint).fmt(f) - } -} - pub fn shortty(item: &clean::Item) -> ItemType { match item.inner { clean::ModuleItem(..) => Module, diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 0ecb86d8bdd..5e4ac259e71 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -437,8 +437,8 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult if i > 0 { try!(write!(&mut w, ",")); } - try!(write!(&mut w, r#"[{:u},"{}","{}",{}"#, - item.ty, item.name, path, + try!(write!(&mut w, r#"[{},"{}","{}",{}"#, + item.ty as uint, item.name, path, item.desc.to_json().to_string())); match item.parent { Some(nodeid) => { @@ -457,8 +457,8 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult if i > 0 { try!(write!(&mut w, ",")); } - try!(write!(&mut w, r#"[{:u},"{}"]"#, - short, *fqp.last().unwrap())); + try!(write!(&mut w, r#"[{},"{}"]"#, + short as uint, *fqp.last().unwrap())); } try!(write!(&mut w, "]}};")); @@ -2192,7 +2192,7 @@ impl<'a> fmt::Show for Source<'a> { } try!(write!(fmt, "
"));
         for i in range(1, lines + 1) {
-            try!(write!(fmt, "{0:1$u}\n", i, cols));
+            try!(write!(fmt, "{0:1$}\n", i, cols));
         }
         try!(write!(fmt, "
")); try!(write!(fmt, "{}", highlight::highlight(s.as_slice(), None, None))); diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 0350fe72e11..4a512ca33fc 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -168,11 +168,11 @@ pub fn main_args(args: &[String]) -> int { if matches.opt_strs("passes").as_slice() == &["list".to_string()] { println!("Available passes for running rustdoc:"); for &(name, _, description) in PASSES.iter() { - println!("{:>20s} - {}", name, description); + println!("{:>20} - {}", name, description); } println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970 for &name in DEFAULT_PASSES.iter() { - println!("{:>20s}", name); + println!("{:>20}", name); } return 0; } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 2968c53de9a..030ee1d4352 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -2403,7 +2403,7 @@ impl ToJson for Option { impl fmt::Show for Json { /// Encodes a json value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.to_writer(f).map_err(|_| fmt::WriteError) + self.to_writer(f).map_err(|_| fmt::Error) } } diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs index e140ddba723..2482fe63028 100644 --- a/src/libstd/fmt.rs +++ b/src/libstd/fmt.rs @@ -38,11 +38,11 @@ Some examples of the `format!` extension are: ```rust # fn main() { format!("Hello"); // => "Hello" -format!("Hello, {:s}!", "world"); // => "Hello, world!" -format!("The number is {:d}", 1i); // => "The number is 1" +format!("Hello, {}!", "world"); // => "Hello, world!" +format!("The number is {}", 1i); // => "The number is 1" format!("{}", (3i, 4i)); // => "(3, 4)" format!("{value}", value=4i); // => "4" -format!("{} {}", 1i, 2i); // => "1 2" +format!("{} {}", 1i, 2u); // => "1 2" # } ``` @@ -94,9 +94,9 @@ For example, the following `format!` expressions all use named argument: ```rust # fn main() { -format!("{argument}", argument = "test"); // => "test" -format!("{name} {}", 1i, name = 2i); // => "2 1" -format!("{a:s} {c:d} {b}", a="a", b=(), c=3i); // => "a 3 ()" +format!("{argument}", argument = "test"); // => "test" +format!("{name} {}", 1i, name = 2i); // => "2 1" +format!("{a} {c} {b}", a="a", b=(), c=3i); // => "a 3 ()" # } ``` @@ -138,23 +138,16 @@ multiple actual types to be formatted via `{:d}` (like `i8` as well as `int`). The current mapping of types to traits is: * *nothing* ⇒ `Show` -* `d` ⇒ `Signed` -* `i` ⇒ `Signed` -* `u` ⇒ `Unsigned` -* `b` ⇒ `Bool` -* `c` ⇒ `Char` * `o` ⇒ `Octal` * `x` ⇒ `LowerHex` * `X` ⇒ `UpperHex` -* `s` ⇒ `String` * `p` ⇒ `Pointer` -* `t` ⇒ `Binary` -* `f` ⇒ `Float` +* `b` ⇒ `Binary` * `e` ⇒ `LowerExp` * `E` ⇒ `UpperExp` What this means is that any type of argument which implements the -`std::fmt::Binary` trait can then be formatted with `{:t}`. Implementations are +`std::fmt::Binary` trait can then be formatted with `{:b}`. Implementations are provided for these traits for a number of primitive types by the standard library as well. If no format is specified (as in `{}` or `{:6}`), then the format trait used is the `Show` trait. This is one of the more commonly @@ -216,7 +209,7 @@ impl fmt::Binary for Vector2D { // Respect the formatting flags by using the helper method // `pad_integral` on the Formatter object. See the method documentation // for details, and the function `pad` can be used to pad strings. - let decimals = f.precision.unwrap_or(3); + let decimals = f.precision().unwrap_or(3); let string = f64::to_str_exact(magnitude, decimals); f.pad_integral(true, "", string.as_bytes()) } @@ -226,7 +219,7 @@ fn main() { let myvector = Vector2D { x: 3, y: 4 }; println!("{}", myvector); // => "(3, 4)" - println!("{:10.3t}", myvector); // => " 5.000" + println!("{:10.3b}", myvector); // => " 5.000" } ``` @@ -418,10 +411,10 @@ use string; use vec::Vec; pub use core::fmt::{Formatter, Result, FormatWriter, rt}; -pub use core::fmt::{Show, Bool, Char, Signed, Unsigned, Octal, Binary}; -pub use core::fmt::{LowerHex, UpperHex, String, Pointer}; -pub use core::fmt::{Float, LowerExp, UpperExp}; -pub use core::fmt::{FormatError, WriteError}; +pub use core::fmt::{Show, Octal, Binary}; +pub use core::fmt::{LowerHex, UpperHex, Pointer}; +pub use core::fmt::{LowerExp, UpperExp}; +pub use core::fmt::Error; pub use core::fmt::{Argument, Arguments, write, radix, Radix, RadixFmt}; #[doc(hidden)] @@ -444,6 +437,8 @@ pub use core::fmt::{argument, argumentstr, argumentuint}; /// let s = format_args!(fmt::format, "Hello, {}!", "world"); /// assert_eq!(s, "Hello, world!".to_string()); /// ``` +#[experimental = "this is an implementation detail of format! and should not \ + be called directly"] pub fn format(args: &Arguments) -> string::String { let mut output = Vec::new(); let _ = write!(&mut output as &mut Writer, "{}", args); @@ -454,7 +449,7 @@ impl<'a> Writer for Formatter<'a> { fn write(&mut self, b: &[u8]) -> io::IoResult<()> { match (*self).write(b) { Ok(()) => Ok(()), - Err(WriteError) => Err(io::standard_error(io::OtherIoError)) + Err(Error) => Err(io::standard_error(io::OtherIoError)) } } } diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 82bfa3c4e80..681400e9db5 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -1034,7 +1034,7 @@ pub trait Writer { Ok(()) => Ok(()), Err(e) => { self.error = Err(e); - Err(fmt::WriteError) + Err(fmt::Error) } } } @@ -1081,13 +1081,13 @@ pub trait Writer { /// Write the result of passing n through `int::to_str_bytes`. #[inline] fn write_int(&mut self, n: int) -> IoResult<()> { - write!(self, "{:d}", n) + write!(self, "{}", n) } /// Write the result of passing n through `uint::to_str_bytes`. #[inline] fn write_uint(&mut self, n: uint) -> IoResult<()> { - write!(self, "{:u}", n) + write!(self, "{}", n) } /// Write a little-endian uint (number of bytes depends on system). @@ -1896,10 +1896,8 @@ impl Default for FilePermission { } impl fmt::Show for FilePermission { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.fill = '0'; - formatter.width = Some(4); - (&self.bits as &fmt::Octal).fmt(formatter) + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:04o}", self.bits) } } diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index 26e9e70dff3..4e5dd5d8818 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -240,6 +240,7 @@ macro_rules! unimplemented( /// format!("x = {}, y = {y}", 10i, y = 30i); /// ``` #[macro_export] +#[stable] macro_rules! format( ($($arg:tt)*) => ( format_args!(::std::fmt::format, $($arg)*) @@ -259,15 +260,18 @@ macro_rules! format( /// write!(&mut w, "formatted {}", "arguments"); /// ``` #[macro_export] +#[stable] macro_rules! write( ($dst:expr, $($arg:tt)*) => ({ - format_args_method!($dst, write_fmt, $($arg)*) + let dst = &mut *$dst; + format_args!(|args| { dst.write_fmt(args) }, $($arg)*) }) ) /// Equivalent to the `write!` macro, except that a newline is appended after /// the message is written. #[macro_export] +#[stable] macro_rules! writeln( ($dst:expr, $fmt:expr $($arg:tt)*) => ( write!($dst, concat!($fmt, "\n") $($arg)*) @@ -277,6 +281,7 @@ macro_rules! writeln( /// Equivalent to the `println!` macro except that a newline is not printed at /// the end of the message. #[macro_export] +#[stable] macro_rules! print( ($($arg:tt)*) => (format_args!(::std::io::stdio::print_args, $($arg)*)) ) @@ -294,6 +299,7 @@ macro_rules! print( /// println!("format {} arguments", "some"); /// ``` #[macro_export] +#[stable] macro_rules! println( ($($arg:tt)*) => (format_args!(::std::io::stdio::println_args, $($arg)*)) ) diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 15e14902727..497a2d49faf 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -95,7 +95,7 @@ impl Ident { } pub fn encode_with_hygiene(&self) -> String { - format!("\x00name_{:u},ctxt_{:u}\x00", + format!("\x00name_{},ctxt_{}\x00", self.name.uint(), self.ctxt) } diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 9292825ffe8..8c70a95443b 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -361,9 +361,6 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { syntax_expanders.insert(intern("format_args"), builtin_normal_expander( ext::format::expand_format_args)); - syntax_expanders.insert(intern("format_args_method"), - builtin_normal_expander( - ext::format::expand_format_args_method)); syntax_expanders.insert(intern("env"), builtin_normal_expander( ext::env::expand_env)); diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index dccc12e406b..8fccb0755f4 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -887,7 +887,7 @@ impl<'a> MethodDef<'a> { // a series of let statements mapping each self_arg to a uint // corresponding to its variant index. let vi_idents: Vec = self_arg_names.iter() - .map(|name| { let vi_suffix = format!("{:s}_vi", name.as_slice()); + .map(|name| { let vi_suffix = format!("{}_vi", name.as_slice()); cx.ident_of(vi_suffix.as_slice()) }) .collect::>(); diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index f1b92b4d6bc..b04a800a32d 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -237,7 +237,7 @@ impl<'a, 'b> Context<'a, 'b> { match arg { Exact(arg) => { if self.args.len() <= arg { - let msg = format!("invalid reference to argument `{}` ({:s})", + let msg = format!("invalid reference to argument `{}` ({})", arg, self.describe_num_args()); self.ecx.span_err(self.fmtsp, msg.as_slice()); @@ -670,17 +670,11 @@ impl<'a, 'b> Context<'a, 'b> { Known(ref tyname) => { match tyname.as_slice() { "" => "Show", - "b" => "Bool", - "c" => "Char", - "d" | "i" => "Signed", "e" => "LowerExp", "E" => "UpperExp", - "f" => "Float", "o" => "Octal", "p" => "Pointer", - "s" => "String", - "t" => "Binary", - "u" => "Unsigned", + "b" => "Binary", "x" => "LowerHex", "X" => "UpperHex", _ => { @@ -724,18 +718,6 @@ pub fn expand_format_args<'cx>(ecx: &'cx mut ExtCtxt, sp: Span, } } -pub fn expand_format_args_method<'cx>(ecx: &'cx mut ExtCtxt, sp: Span, - tts: &[ast::TokenTree]) -> Box { - - match parse_args(ecx, sp, true, tts) { - (invocation, Some((efmt, args, order, names))) => { - MacExpr::new(expand_preparsed_format_args(ecx, sp, invocation, efmt, - args, order, names)) - } - (_, None) => MacExpr::new(ecx.expr_uint(sp, 2)) - } -} - /// Take the various parts of `format_args!(extra, efmt, args..., /// name=names...)` and construct the appropriate formatting /// expression. diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index b50a4690e42..2ddcab10cda 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -131,7 +131,7 @@ fn new_sctable_internal() -> SCTable { pub fn display_sctable(table: &SCTable) { error!("SC table:"); for (idx,val) in table.table.borrow().iter().enumerate() { - error!("{:4u} : {}",idx,val); + error!("{:4} : {}",idx,val); } } diff --git a/src/libterm/terminfo/parm.rs b/src/libterm/terminfo/parm.rs index ec6e286b9b9..f910bfc5bd4 100644 --- a/src/libterm/terminfo/parm.rs +++ b/src/libterm/terminfo/parm.rs @@ -497,8 +497,8 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result ,String> { let mut s = match val { Number(d) => { let s = match (op, flags.sign) { - (FormatDigit, true) => format!("{:+d}", d).into_bytes(), - (FormatDigit, false) => format!("{:d}", d).into_bytes(), + (FormatDigit, true) => format!("{:+}", d).into_bytes(), + (FormatDigit, false) => format!("{}", d).into_bytes(), (FormatOctal, _) => format!("{:o}", d).into_bytes(), (FormatHex, _) => format!("{:x}", d).into_bytes(), (FormatHEX, _) => format!("{:X}", d).into_bytes(), diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index d5d0e7aeb17..0ea8ca84ef8 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -687,14 +687,14 @@ impl ConsoleTestState { improved += 1; try!(self.write_plain(format!(": {}", *k).as_slice())); try!(self.write_improved()); - try!(self.write_plain(format!(" by {:.2f}%\n", + try!(self.write_plain(format!(" by {:.2}%\n", pct as f64).as_slice())); } Regression(pct) => { regressed += 1; try!(self.write_plain(format!(": {}", *k).as_slice())); try!(self.write_regressed()); - try!(self.write_plain(format!(" by {:.2f}%\n", + try!(self.write_plain(format!(" by {:.2}%\n", pct as f64).as_slice())); } } diff --git a/src/libtime/lib.rs b/src/libtime/lib.rs index 4fb387db3a2..062035c23f9 100644 --- a/src/libtime/lib.rs +++ b/src/libtime/lib.rs @@ -602,8 +602,8 @@ impl<'a> fmt::Show for TmFmt<'a> { match ch { 'G' => write!(fmt, "{}", year), - 'g' => write!(fmt, "{:02d}", (year % 100 + 100) % 100), - 'V' => write!(fmt, "{:02d}", days / 7 + 1), + 'g' => write!(fmt, "{:02}", (year % 100 + 100) % 100), + 'V' => write!(fmt, "{:02}", days / 7 + 1), _ => Ok(()) } } @@ -663,7 +663,7 @@ impl<'a> fmt::Show for TmFmt<'a> { 11 => "Dec", _ => return die() }, - 'C' => return write!(fmt, "{:02d}", (tm.tm_year as int + 1900) / 100), + 'C' => return write!(fmt, "{:02}", (tm.tm_year as int + 1900) / 100), 'c' => { try!(parse_type(fmt, 'a', tm)); try!(' '.fmt(fmt)); @@ -682,9 +682,9 @@ impl<'a> fmt::Show for TmFmt<'a> { try!('/'.fmt(fmt)); return parse_type(fmt, 'y', tm); } - 'd' => return write!(fmt, "{:02d}", tm.tm_mday), - 'e' => return write!(fmt, "{:2d}", tm.tm_mday), - 'f' => return write!(fmt, "{:09d}", tm.tm_nsec), + 'd' => return write!(fmt, "{:02}", tm.tm_mday), + 'e' => return write!(fmt, "{:2}", tm.tm_mday), + 'f' => return write!(fmt, "{:09}", tm.tm_nsec), 'F' => { try!(parse_type(fmt, 'Y', tm)); try!('-'.fmt(fmt)); @@ -694,23 +694,23 @@ impl<'a> fmt::Show for TmFmt<'a> { } 'G' => return iso_week(fmt, 'G', tm), 'g' => return iso_week(fmt, 'g', tm), - 'H' => return write!(fmt, "{:02d}", tm.tm_hour), + 'H' => return write!(fmt, "{:02}", tm.tm_hour), 'I' => { let mut h = tm.tm_hour; if h == 0 { h = 12 } if h > 12 { h -= 12 } - return write!(fmt, "{:02d}", h) + return write!(fmt, "{:02}", h) } - 'j' => return write!(fmt, "{:03d}", tm.tm_yday + 1), - 'k' => return write!(fmt, "{:2d}", tm.tm_hour), + 'j' => return write!(fmt, "{:03}", tm.tm_yday + 1), + 'k' => return write!(fmt, "{:2}", tm.tm_hour), 'l' => { let mut h = tm.tm_hour; if h == 0 { h = 12 } if h > 12 { h -= 12 } - return write!(fmt, "{:2d}", h) + return write!(fmt, "{:2}", h) } - 'M' => return write!(fmt, "{:02d}", tm.tm_min), - 'm' => return write!(fmt, "{:02d}", tm.tm_mon + 1), + 'M' => return write!(fmt, "{:02}", tm.tm_min), + 'm' => return write!(fmt, "{:02}", tm.tm_mon + 1), 'n' => "\n", 'P' => if (tm.tm_hour as int) < 12 { "am" } else { "pm" }, 'p' => if (tm.tm_hour as int) < 12 { "AM" } else { "PM" }, @@ -728,7 +728,7 @@ impl<'a> fmt::Show for TmFmt<'a> { try!(' '.fmt(fmt)); return parse_type(fmt, 'p', tm); } - 'S' => return write!(fmt, "{:02d}", tm.tm_sec), + 'S' => return write!(fmt, "{:02}", tm.tm_sec), 's' => return write!(fmt, "{}", tm.to_timespec().sec), 'T' | 'X' => { try!(parse_type(fmt, 'H', tm)); @@ -738,7 +738,7 @@ impl<'a> fmt::Show for TmFmt<'a> { return parse_type(fmt, 'S', tm); } 't' => "\t", - 'U' => return write!(fmt, "{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7), + 'U' => return write!(fmt, "{:02}", (tm.tm_yday - tm.tm_wday + 7) / 7), 'u' => { let i = tm.tm_wday as int; return (if i == 0 { 7 } else { i }).fmt(fmt); @@ -752,19 +752,19 @@ impl<'a> fmt::Show for TmFmt<'a> { return parse_type(fmt, 'Y', tm); } 'W' => { - return write!(fmt, "{:02d}", + return write!(fmt, "{:02}", (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7) } 'w' => return (tm.tm_wday as int).fmt(fmt), 'Y' => return (tm.tm_year as int + 1900).fmt(fmt), - 'y' => return write!(fmt, "{:02d}", (tm.tm_year as int + 1900) % 100), + 'y' => return write!(fmt, "{:02}", (tm.tm_year as int + 1900) % 100), 'Z' => if tm.tm_gmtoff == 0_i32 { "GMT"} else { "" }, // FIXME (#2350): support locale 'z' => { let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' }; let mut m = tm.tm_gmtoff.abs() / 60_i32; let h = m / 60_i32; m -= h * 60_i32; - return write!(fmt, "{}{:02d}{:02d}", sign, h, m); + return write!(fmt, "{}{:02}{:02}", sign, h, m); } '+' => return tm.rfc3339().fmt(fmt), '%' => "%", @@ -806,7 +806,7 @@ impl<'a> fmt::Show for TmFmt<'a> { let mut m = self.tm.tm_gmtoff.abs() / 60_i32; let h = m / 60_i32; m -= h * 60_i32; - write!(fmt, "{}{}{:02d}:{:02d}", s, sign, h as int, m as int) + write!(fmt, "{}{}{:02}:{:02}", s, sign, h as int, m as int) } } } diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index 15d89bebf75..07300b73c85 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -148,7 +148,7 @@ fn write_header(header: &str) { } fn write_row(label: &str, value: Duration) { - println!("{:30s} {} s\n", label, value); + println!("{:30} {} s\n", label, value); } fn write_results(label: &str, results: &Results) { diff --git a/src/test/bench/noise.rs b/src/test/bench/noise.rs index 1c530e3851e..419e39b53cf 100644 --- a/src/test/bench/noise.rs +++ b/src/test/bench/noise.rs @@ -115,7 +115,7 @@ fn main() { for y in range(0u, 256) { for x in range(0u, 256) { let idx = (pixels[y*256+x] / 0.2) as uint; - print!("{:c}", symbols[idx]); + print!("{}", symbols[idx]); } print!("\n"); } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index e39cd743ad5..4005c11e6b6 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -63,7 +63,7 @@ fn sort_and_fmt(mm: &HashMap , uint>, total: uint) -> String { let mut buffer = String::new(); for &(ref k, v) in pairs_sorted.iter() { - buffer.push_str(format!("{} {:0.3f}\n", + buffer.push_str(format!("{} {:0.3}\n", k.as_slice() .to_ascii() .to_uppercase() diff --git a/src/test/bench/shootout-k-nucleotide.rs b/src/test/bench/shootout-k-nucleotide.rs index 6ada34a5a58..b030e7bb93e 100644 --- a/src/test/bench/shootout-k-nucleotide.rs +++ b/src/test/bench/shootout-k-nucleotide.rs @@ -266,7 +266,7 @@ fn print_frequencies(frequencies: &Table, frame: uint) { } for &(count, key) in vector.iter().rev() { - println!("{} {:.3f}", + println!("{} {:.3}", key.unpack(frame).as_slice(), (count as f32 * 100.0) / (total_count as f32)); } diff --git a/src/test/bench/shootout-nbody.rs b/src/test/bench/shootout-nbody.rs index 3bcc0c25df8..b62504d7ba8 100644 --- a/src/test/bench/shootout-nbody.rs +++ b/src/test/bench/shootout-nbody.rs @@ -179,11 +179,11 @@ fn main() { let mut bodies = BODIES; offset_momentum(&mut bodies); - println!("{:.9f}", energy(&bodies)); + println!("{:.9}", energy(&bodies)); advance(&mut bodies, 0.01, n); - println!("{:.9f}", energy(&bodies)); + println!("{:.9}", energy(&bodies)); } /// Pop a mutable reference off the head of a slice, mutating the slice to no diff --git a/src/test/bench/shootout-spectralnorm.rs b/src/test/bench/shootout-spectralnorm.rs index acb289aa3ad..f76391b596b 100644 --- a/src/test/bench/shootout-spectralnorm.rs +++ b/src/test/bench/shootout-spectralnorm.rs @@ -59,7 +59,7 @@ fn main() { } else { from_str(args[1].as_slice()).unwrap() }); - println!("{:.9f}", answer); + println!("{:.9}", answer); } fn spectralnorm(n: uint) -> f64 { diff --git a/src/test/compile-fail/ifmt-bad-arg.rs b/src/test/compile-fail/ifmt-bad-arg.rs index 6829b1e2721..db7f49272aa 100644 --- a/src/test/compile-fail/ifmt-bad-arg.rs +++ b/src/test/compile-fail/ifmt-bad-arg.rs @@ -23,8 +23,8 @@ fn main() { format!("{foo}", 1, foo=2); //~ ERROR: argument never used format!("", foo=2); //~ ERROR: named argument never used - format!("{0:d} {0:s}", 1); //~ ERROR: redeclared with type `s` - format!("{foo:d} {foo:s}", foo=1); //~ ERROR: redeclared with type `s` + format!("{0:x} {0:X}", 1); //~ ERROR: redeclared with type `X` + format!("{foo:x} {foo:X}", foo=1); //~ ERROR: redeclared with type `X` format!("{foo}", foo=1, foo=2); //~ ERROR: duplicate argument format!("", foo=1, 2); //~ ERROR: positional arguments cannot follow diff --git a/src/test/compile-fail/ifmt-unimpl.rs b/src/test/compile-fail/ifmt-unimpl.rs index 194047ce848..948040496bd 100644 --- a/src/test/compile-fail/ifmt-unimpl.rs +++ b/src/test/compile-fail/ifmt-unimpl.rs @@ -9,6 +9,6 @@ // except according to those terms. fn main() { - format!("{:d}", "3"); - //~^ ERROR: the trait `core::fmt::Signed` is not implemented + format!("{:X}", "3"); + //~^ ERROR: the trait `core::fmt::UpperHex` is not implemented } diff --git a/src/test/compile-fail/issue-1448-2.rs b/src/test/compile-fail/issue-1448-2.rs index 3daced7a5ac..234fa85c89a 100644 --- a/src/test/compile-fail/issue-1448-2.rs +++ b/src/test/compile-fail/issue-1448-2.rs @@ -13,5 +13,5 @@ fn foo(a: uint) -> uint { a } fn main() { - println!("{:u}", foo(10i)); //~ ERROR mismatched types + println!("{}", foo(10i)); //~ ERROR mismatched types } diff --git a/src/test/compile-fail/issue-14853.rs b/src/test/compile-fail/issue-14853.rs index 4243b98e0dd..6515b34d964 100644 --- a/src/test/compile-fail/issue-14853.rs +++ b/src/test/compile-fail/issue-14853.rs @@ -10,17 +10,18 @@ use std::fmt::Show; +trait Str {} + trait Something { - fn yay(_: Option, thing: &[T]) -> String { - } + fn yay(_: Option, thing: &[T]); } struct X { data: u32 } impl Something for X { - fn yay(_:Option, thing: &[T]) -> String { -//~^ ERROR in method `yay`, type parameter 0 requires bound `core::str::Str`, which is not required - format!("{:s}", thing[0]) + fn yay(_:Option, thing: &[T]) { +//~^ ERROR in method `yay`, type parameter 0 requires bound `Str`, which is not required + } } diff --git a/src/test/run-pass/ifmt.rs b/src/test/run-pass/ifmt.rs index 59f7eda4161..b78371c51e4 100644 --- a/src/test/run-pass/ifmt.rs +++ b/src/test/run-pass/ifmt.rs @@ -22,12 +22,12 @@ struct A; struct B; struct C; -impl fmt::Signed for A { +impl fmt::LowerHex for A { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write("aloha".as_bytes()) } } -impl fmt::Signed for B { +impl fmt::UpperHex for B { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write("adios".as_bytes()) } @@ -55,71 +55,71 @@ pub fn main() { t!(format!("{}", 'a'), "a"); // At least exercise all the formats - t!(format!("{:b}", true), "true"); - t!(format!("{:c}", '☃'), "☃"); - t!(format!("{:d}", 10i), "10"); - t!(format!("{:i}", 10i), "10"); - t!(format!("{:u}", 10u), "10"); + t!(format!("{}", true), "true"); + t!(format!("{}", '☃'), "☃"); + t!(format!("{}", 10i), "10"); + t!(format!("{}", 10i), "10"); + t!(format!("{}", 10u), "10"); t!(format!("{:o}", 10u), "12"); t!(format!("{:x}", 10u), "a"); t!(format!("{:X}", 10u), "A"); - t!(format!("{:s}", "foo"), "foo"); - t!(format!("{:s}", "foo".to_string()), "foo"); + t!(format!("{}", "foo"), "foo"); + t!(format!("{}", "foo".to_string()), "foo"); t!(format!("{:p}", 0x1234 as *const int), "0x1234"); t!(format!("{:p}", 0x1234 as *mut int), "0x1234"); - t!(format!("{:d}", A), "aloha"); - t!(format!("{:d}", B), "adios"); - t!(format!("foo {:s} ☃☃☃☃☃☃", "bar"), "foo bar ☃☃☃☃☃☃"); + t!(format!("{:x}", A), "aloha"); + t!(format!("{:X}", B), "adios"); + t!(format!("foo {} ☃☃☃☃☃☃", "bar"), "foo bar ☃☃☃☃☃☃"); t!(format!("{1} {0}", 0i, 1i), "1 0"); t!(format!("{foo} {bar}", foo=0i, bar=1i), "0 1"); t!(format!("{foo} {1} {bar} {0}", 0i, 1i, foo=2i, bar=3i), "2 1 3 0"); t!(format!("{} {0}", "a"), "a a"); t!(format!("{foo_bar}", foo_bar=1i), "1"); - t!(format!("{:d}", 5i + 5i), "10"); + t!(format!("{}", 5i + 5i), "10"); t!(format!("{:#4}", C), "☃123"); let a: &fmt::Show = &1i; t!(format!("{}", a), "1"); // Formatting strings and their arguments - t!(format!("{:s}", "a"), "a"); - t!(format!("{:4s}", "a"), "a "); - t!(format!("{:4s}", "☃"), "☃ "); - t!(format!("{:>4s}", "a"), " a"); - t!(format!("{:<4s}", "a"), "a "); - t!(format!("{:^5s}", "a"), " a "); - t!(format!("{:^5s}", "aa"), " aa "); - t!(format!("{:^4s}", "a"), " a "); - t!(format!("{:^4s}", "aa"), " aa "); - t!(format!("{:.4s}", "a"), "a"); - t!(format!("{:4.4s}", "a"), "a "); - t!(format!("{:4.4s}", "aaaaaaaaaaaaaaaaaa"), "aaaa"); - t!(format!("{:<4.4s}", "aaaaaaaaaaaaaaaaaa"), "aaaa"); - t!(format!("{:>4.4s}", "aaaaaaaaaaaaaaaaaa"), "aaaa"); - t!(format!("{:^4.4s}", "aaaaaaaaaaaaaaaaaa"), "aaaa"); - t!(format!("{:>10.4s}", "aaaaaaaaaaaaaaaaaa"), "aaaa"); - t!(format!("{:2.4s}", "aaaaa"), "aaaa"); - t!(format!("{:2.4s}", "aaaa"), "aaaa"); - t!(format!("{:2.4s}", "aaa"), "aaa"); - t!(format!("{:2.4s}", "aa"), "aa"); - t!(format!("{:2.4s}", "a"), "a "); - t!(format!("{:0>2s}", "a"), "0a"); - t!(format!("{:.*s}", 4, "aaaaaaaaaaaaaaaaaa"), "aaaa"); - t!(format!("{:.1$s}", "aaaaaaaaaaaaaaaaaa", 4), "aaaa"); - t!(format!("{:.a$s}", "aaaaaaaaaaaaaaaaaa", a=4), "aaaa"); - t!(format!("{:1$s}", "a", 4), "a "); - t!(format!("{1:0$s}", 4, "a"), "a "); - t!(format!("{:a$s}", "a", a=4), "a "); - t!(format!("{:-#s}", "a"), "a"); - t!(format!("{:+#s}", "a"), "a"); + t!(format!("{}", "a"), "a"); + t!(format!("{:4}", "a"), "a "); + t!(format!("{:4}", "☃"), "☃ "); + t!(format!("{:>4}", "a"), " a"); + t!(format!("{:<4}", "a"), "a "); + t!(format!("{:^5}", "a"), " a "); + t!(format!("{:^5}", "aa"), " aa "); + t!(format!("{:^4}", "a"), " a "); + t!(format!("{:^4}", "aa"), " aa "); + t!(format!("{:.4}", "a"), "a"); + t!(format!("{:4.4}", "a"), "a "); + t!(format!("{:4.4}", "aaaaaaaaaaaaaaaaaa"), "aaaa"); + t!(format!("{:<4.4}", "aaaaaaaaaaaaaaaaaa"), "aaaa"); + t!(format!("{:>4.4}", "aaaaaaaaaaaaaaaaaa"), "aaaa"); + t!(format!("{:^4.4}", "aaaaaaaaaaaaaaaaaa"), "aaaa"); + t!(format!("{:>10.4}", "aaaaaaaaaaaaaaaaaa"), "aaaa"); + t!(format!("{:2.4}", "aaaaa"), "aaaa"); + t!(format!("{:2.4}", "aaaa"), "aaaa"); + t!(format!("{:2.4}", "aaa"), "aaa"); + t!(format!("{:2.4}", "aa"), "aa"); + t!(format!("{:2.4}", "a"), "a "); + t!(format!("{:0>2}", "a"), "0a"); + t!(format!("{:.*}", 4, "aaaaaaaaaaaaaaaaaa"), "aaaa"); + t!(format!("{:.1$}", "aaaaaaaaaaaaaaaaaa", 4), "aaaa"); + t!(format!("{:.a$}", "aaaaaaaaaaaaaaaaaa", a=4), "aaaa"); + t!(format!("{:1$}", "a", 4), "a "); + t!(format!("{1:0$}", 4, "a"), "a "); + t!(format!("{:a$}", "a", a=4), "a "); + t!(format!("{:-#}", "a"), "a"); + t!(format!("{:+#}", "a"), "a"); // Some float stuff - t!(format!("{:f}", 1.0f32), "1"); - t!(format!("{:f}", 1.0f64), "1"); - t!(format!("{:.3f}", 1.0f64), "1.000"); - t!(format!("{:10.3f}", 1.0f64), " 1.000"); - t!(format!("{:+10.3f}", 1.0f64), " +1.000"); - t!(format!("{:+10.3f}", -1.0f64), " -1.000"); + t!(format!("{:}", 1.0f32), "1"); + t!(format!("{:}", 1.0f64), "1"); + t!(format!("{:.3}", 1.0f64), "1.000"); + t!(format!("{:10.3}", 1.0f64), " 1.000"); + t!(format!("{:+10.3}", 1.0f64), " +1.000"); + t!(format!("{:+10.3}", -1.0f64), " -1.000"); t!(format!("{:e}", 1.2345e6f32), "1.2345e6"); t!(format!("{:e}", 1.2345e6f64), "1.2345e6"); @@ -164,7 +164,7 @@ fn test_write() { { let w = &mut buf as &mut io::Writer; write!(w, "{foo}", foo=4i); - write!(w, "{:s}", "hello"); + write!(w, "{}", "hello"); writeln!(w, "{}", "line"); writeln!(w, "{foo}", foo="bar"); } diff --git a/src/test/run-pass/realloc-16687.rs b/src/test/run-pass/realloc-16687.rs index bd581dd657f..a29ed712d40 100644 --- a/src/test/run-pass/realloc-16687.rs +++ b/src/test/run-pass/realloc-16687.rs @@ -46,19 +46,19 @@ unsafe fn test_triangle() -> bool { static PRINT : bool = false; unsafe fn allocate(size: uint, align: uint) -> *mut u8 { - if PRINT { println!("allocate(size={:u} align={:u})", size, align); } + if PRINT { println!("allocate(size={} align={})", size, align); } let ret = heap::allocate(size, align); if ret.is_null() { alloc::oom() } - if PRINT { println!("allocate(size={:u} align={:u}) ret: 0x{:010x}", + if PRINT { println!("allocate(size={} align={}) ret: 0x{:010x}", size, align, ret as uint); } ret } unsafe fn deallocate(ptr: *mut u8, size: uint, align: uint) { - if PRINT { println!("deallocate(ptr=0x{:010x} size={:u} align={:u})", + if PRINT { println!("deallocate(ptr=0x{:010x} size={} align={})", ptr as uint, size, align); } @@ -66,7 +66,7 @@ unsafe fn test_triangle() -> bool { } unsafe fn reallocate(ptr: *mut u8, old_size: uint, size: uint, align: uint) -> *mut u8 { if PRINT { - println!("reallocate(ptr=0x{:010x} old_size={:u} size={:u} align={:u})", + println!("reallocate(ptr=0x{:010x} old_size={} size={} align={})", ptr as uint, old_size, size, align); } @@ -74,7 +74,7 @@ unsafe fn test_triangle() -> bool { if ret.is_null() { alloc::oom() } if PRINT { - println!("reallocate(ptr=0x{:010x} old_size={:u} size={:u} align={:u}) \ + println!("reallocate(ptr=0x{:010x} old_size={} size={} align={}) \ ret: 0x{:010x}", ptr as uint, old_size, size, align, ret as uint); }