about summary refs log tree commit diff
path: root/src/libcore/fmt
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2015-01-07 05:31:23 +0000
committerbors <bors@rust-lang.org>2015-01-07 05:31:23 +0000
commit9e4e524e0eb17c8f463e731f23b544003e8709c6 (patch)
tree916024d35e08f0826c20654f629ec596b5cb1f14 /src/libcore/fmt
parentea6f65c5f1a3f84e010d2cef02a0160804e9567a (diff)
parenta64000820f0fc32be4d7535a9a92418a434fa4ba (diff)
downloadrust-9e4e524e0eb17c8f463e731f23b544003e8709c6.tar.gz
rust-9e4e524e0eb17c8f463e731f23b544003e8709c6.zip
auto merge of #20677 : alexcrichton/rust/rollup, r=alexcrichton
Diffstat (limited to 'src/libcore/fmt')
-rw-r--r--src/libcore/fmt/float.rs4
-rw-r--r--src/libcore/fmt/mod.rs188
-rw-r--r--src/libcore/fmt/num.rs53
3 files changed, 210 insertions, 35 deletions
diff --git a/src/libcore/fmt/float.rs b/src/libcore/fmt/float.rs
index f63242b4f85..d833b8fed77 100644
--- a/src/libcore/fmt/float.rs
+++ b/src/libcore/fmt/float.rs
@@ -20,7 +20,7 @@ use fmt;
 use iter::{IteratorExt, range};
 use num::{cast, Float, ToPrimitive};
 use num::FpCategory as Fp;
-use ops::FnOnce;
+use ops::{FnOnce, Index};
 use result::Result::Ok;
 use slice::{self, SliceExt};
 use str::{self, StrExt};
@@ -332,5 +332,5 @@ pub fn float_to_str_bytes_common<T: Float, U, F>(
         }
     }
 
-    f(unsafe { str::from_utf8_unchecked(buf[..end]) })
+    f(unsafe { str::from_utf8_unchecked(buf.index(&(0..end))) })
 }
diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs
index 951f5c29f00..f9027f19068 100644
--- a/src/libcore/fmt/mod.rs
+++ b/src/libcore/fmt/mod.rs
@@ -13,22 +13,20 @@
 #![allow(unused_variables)]
 
 use any;
-use cell::{Cell, Ref, RefMut};
+use cell::{Cell, RefCell, Ref, RefMut};
+use char::CharExt;
 use iter::{Iterator, IteratorExt, range};
-use kinds::{Copy, Sized};
+use marker::{Copy, Sized};
 use mem;
 use option::Option;
 use option::Option::{Some, None};
-use ops::{Deref, FnOnce};
 use result::Result::Ok;
+use ops::{Deref, FnOnce, Index};
 use result;
 use slice::SliceExt;
 use slice;
 use str::{self, StrExt, Utf8Error};
 
-// NOTE: for old macros; remove after the next snapshot
-#[cfg(stage0)] use result::Result::Err;
-
 pub use self::num::radix;
 pub use self::num::Radix;
 pub use self::num::RadixFmt;
@@ -217,19 +215,32 @@ pub struct Arguments<'a> {
 
 impl<'a> Show for Arguments<'a> {
     fn fmt(&self, fmt: &mut Formatter) -> Result {
+        String::fmt(self, fmt)
+    }
+}
+
+impl<'a> String for Arguments<'a> {
+    fn fmt(&self, fmt: &mut Formatter) -> Result {
         write(fmt.buf, *self)
     }
 }
 
-/// 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.
+/// Format trait for the `:?` format. Useful for debugging, most all types
+/// should implement this.
 #[unstable = "I/O and core have yet to be reconciled"]
 pub trait Show {
     /// Formats the value using the given formatter.
     fn fmt(&self, &mut Formatter) -> Result;
 }
 
+/// When a value can be semantically expressed as a String, this trait may be
+/// used. It corresponds to the default format, `{}`.
+#[unstable = "I/O and core have yet to be reconciled"]
+pub trait String {
+    /// 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"]
@@ -413,7 +424,7 @@ impl<'a> Formatter<'a> {
             for c in sign.into_iter() {
                 let mut b = [0; 4];
                 let n = c.encode_utf8(&mut b).unwrap_or(0);
-                let b = unsafe { str::from_utf8_unchecked(b[0..n]) };
+                let b = unsafe { str::from_utf8_unchecked(b.index(&(0..n))) };
                 try!(f.buf.write_str(b));
             }
             if prefixed { f.buf.write_str(prefix) }
@@ -521,7 +532,7 @@ impl<'a> Formatter<'a> {
 
         let mut fill = [0u8; 4];
         let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
-        let fill = unsafe { str::from_utf8_unchecked(fill[..len]) };
+        let fill = unsafe { str::from_utf8_unchecked(fill.index(&(..len))) };
 
         for _ in range(0, pre_pad) {
             try!(self.buf.write_str(fill));
@@ -572,7 +583,7 @@ impl<'a> Formatter<'a> {
 
 impl Show for Error {
     fn fmt(&self, f: &mut Formatter) -> Result {
-        "an error occurred when formatting an argument".fmt(f)
+        String::fmt("an error occurred when formatting an argument", f)
     }
 }
 
@@ -595,33 +606,86 @@ pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
 
 // Implementations of the core formatting traits
 
-impl<'a, T: ?Sized + Show> Show for &'a T {
-    fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
-}
-impl<'a, T: ?Sized + Show> Show for &'a mut T {
-    fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
+macro_rules! fmt_refs {
+    ($($tr:ident),*) => {
+        $(
+        impl<'a, T: ?Sized + $tr> $tr for &'a T {
+            fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
+        }
+        impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
+            fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
+        }
+        )*
+    }
 }
 
+fmt_refs! { Show, String, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
+
 impl Show for bool {
     fn fmt(&self, f: &mut Formatter) -> Result {
-        Show::fmt(if *self { "true" } else { "false" }, f)
+        String::fmt(self, f)
+    }
+}
+
+impl String for bool {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        String::fmt(if *self { "true" } else { "false" }, f)
+    }
+}
+
+#[cfg(stage0)]
+//NOTE(stage0): remove impl after snapshot
+impl Show for str {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        String::fmt(self, f)
     }
 }
 
+#[cfg(not(stage0))]
+//NOTE(stage0): remove cfg after snapshot
 impl Show for str {
     fn fmt(&self, f: &mut Formatter) -> Result {
+        try!(write!(f, "\""));
+        for c in self.chars().flat_map(|c| c.escape_default()) {
+            try!(write!(f, "{}", c));
+        }
+        write!(f, "\"")
+    }
+}
+
+impl String for str {
+    fn fmt(&self, f: &mut Formatter) -> Result {
         f.pad(self)
     }
 }
 
+#[cfg(stage0)]
+//NOTE(stage0): remove impl after snapshot
+impl Show for char {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        String::fmt(self, f)
+    }
+}
+
+#[cfg(not(stage0))]
+//NOTE(stage0): remove cfg after snapshot
 impl Show for char {
     fn fmt(&self, f: &mut Formatter) -> Result {
         use char::CharExt;
+        try!(write!(f, "'"));
+        for c in self.escape_default() {
+            try!(write!(f, "{}", c));
+        }
+        write!(f, "'")
+    }
+}
 
+impl String for char {
+    fn fmt(&self, f: &mut Formatter) -> Result {
         let mut utf8 = [0u8; 4];
         let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
-        let s: &str = unsafe { mem::transmute(utf8[..amt]) };
-        Show::fmt(s, f)
+        let s: &str = unsafe { mem::transmute(utf8.index(&(0..amt))) };
+        String::fmt(s, f)
     }
 }
 
@@ -653,8 +717,16 @@ impl<'a, T> Pointer for &'a mut T {
 }
 
 macro_rules! floating { ($ty:ident) => {
+
     impl Show for $ty {
         fn fmt(&self, fmt: &mut Formatter) -> Result {
+            try!(String::fmt(self, fmt));
+            fmt.write_str(stringify!($ty))
+        }
+    }
+
+    impl String for $ty {
+        fn fmt(&self, fmt: &mut Formatter) -> Result {
             use num::Float;
 
             let digits = match fmt.precision {
@@ -724,10 +796,15 @@ floating! { f64 }
 impl<T> Show for *const T {
     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
 }
-
+impl<T> String for *const T {
+    fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
+}
 impl<T> Show for *mut T {
     fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
 }
+impl<T> String for *mut T {
+    fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
+}
 
 macro_rules! peel {
     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
@@ -746,7 +823,7 @@ macro_rules! tuple {
                     if n > 0 {
                         try!(write!(f, ", "));
                     }
-                    try!(write!(f, "{}", *$name));
+                    try!(write!(f, "{:?}", *$name));
                     n += 1;
                 )*
                 if n == 1 {
@@ -777,6 +854,49 @@ impl<T: Show> Show for [T] {
             } else {
                 try!(write!(f, ", "));
             }
+            try!(write!(f, "{:?}", *x))
+        }
+        if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
+            try!(write!(f, "]"));
+        }
+        Ok(())
+    }
+}
+
+#[cfg(stage0)]
+impl<T: Show> String for [T] {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
+            try!(write!(f, "["));
+        }
+        let mut is_first = true;
+        for x in self.iter() {
+            if is_first {
+                is_first = false;
+            } else {
+                try!(write!(f, ", "));
+            }
+            try!(write!(f, "{}", *x))
+        }
+        if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
+            try!(write!(f, "]"));
+        }
+        Ok(())
+    }
+}
+#[cfg(not(stage0))]
+impl<T: String> String for [T] {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
+            try!(write!(f, "["));
+        }
+        let mut is_first = true;
+        for x in self.iter() {
+            if is_first {
+                is_first = false;
+            } else {
+                try!(write!(f, ", "));
+            }
             try!(write!(f, "{}", *x))
         }
         if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
@@ -792,25 +912,41 @@ impl Show for () {
     }
 }
 
+impl String for () {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        f.pad("()")
+    }
+}
+
 impl<T: Copy + Show> Show for Cell<T> {
     fn fmt(&self, f: &mut Formatter) -> Result {
-        write!(f, "Cell {{ value: {} }}", self.get())
+        write!(f, "Cell {{ value: {:?} }}", self.get())
+    }
+}
+
+#[unstable]
+impl<T: Show> Show for RefCell<T> {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        match self.try_borrow() {
+            Some(val) => write!(f, "RefCell {{ value: {:?} }}", val),
+            None => write!(f, "RefCell {{ <borrowed> }}")
+        }
     }
 }
 
 impl<'b, T: Show> Show for Ref<'b, T> {
     fn fmt(&self, f: &mut Formatter) -> Result {
-        (**self).fmt(f)
+        Show::fmt(&**self, f)
     }
 }
 
 impl<'b, T: Show> Show for RefMut<'b, T> {
     fn fmt(&self, f: &mut Formatter) -> Result {
-        (*(self.deref())).fmt(f)
+        Show::fmt(&*(self.deref()), f)
     }
 }
 
-impl Show for Utf8Error {
+impl String for Utf8Error {
     fn fmt(&self, f: &mut Formatter) -> Result {
         match *self {
             Utf8Error::InvalidByte(n) => {
diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs
index e0724fc2da5..17149aed3db 100644
--- a/src/libcore/fmt/num.rs
+++ b/src/libcore/fmt/num.rs
@@ -16,6 +16,7 @@
 
 use fmt;
 use iter::IteratorExt;
+use ops::Index;
 use num::{Int, cast};
 use slice::SliceExt;
 use str;
@@ -61,7 +62,7 @@ trait GenericRadix {
                 if x == zero { break };                   // No more digits left to accumulate.
             }
         }
-        let buf = unsafe { str::from_utf8_unchecked(buf[curr..]) };
+        let buf = unsafe { str::from_utf8_unchecked(buf.index(&(curr..))) };
         f.pad_integral(is_positive, self.prefix(), buf)
     }
 }
@@ -153,9 +154,23 @@ pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
 }
 
 macro_rules! radix_fmt {
-    ($T:ty as $U:ty, $fmt:ident) => {
+    ($T:ty as $U:ty, $fmt:ident, $S:expr) => {
+        #[cfg(stage0)]
         impl fmt::Show for RadixFmt<$T, Radix> {
             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+                fmt::String::fmt(self, f)
+            }
+        }
+
+        #[cfg(not(stage0))]
+        impl fmt::Show for RadixFmt<$T, Radix> {
+            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+                try!(fmt::String::fmt(self, f));
+                f.write_str($S)
+            }
+        }
+        impl fmt::String for RadixFmt<$T, Radix> {
+            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                 match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
             }
         }
@@ -170,24 +185,48 @@ macro_rules! int_base {
         }
     }
 }
+
+macro_rules! show {
+    ($T:ident with $S:expr) => {
+        #[cfg(stage0)]
+        impl fmt::Show for $T {
+            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+                fmt::String::fmt(self, f)
+            }
+        }
+
+        #[cfg(not(stage0))]
+        impl fmt::Show for $T {
+            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+                try!(fmt::String::fmt(self, f));
+                f.write_str($S)
+            }
+        }
+    }
+}
 macro_rules! integer {
     ($Int:ident, $Uint:ident) => {
-        int_base! { Show     for $Int as $Int   -> Decimal }
+        integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) }
+    };
+    ($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => {
+        int_base! { String   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 }
         int_base! { UpperHex for $Int as $Uint  -> UpperHex }
-        radix_fmt! { $Int as $Int, fmt_int }
+        radix_fmt! { $Int as $Int, fmt_int, $SI }
+        show! { $Int with $SI }
 
-        int_base! { Show     for $Uint as $Uint -> Decimal }
+        int_base! { String   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 }
         int_base! { UpperHex for $Uint as $Uint -> UpperHex }
-        radix_fmt! { $Uint as $Uint, fmt_int }
+        radix_fmt! { $Uint as $Uint, fmt_int, $SU }
+        show! { $Uint with $SU }
     }
 }
-integer! { int, uint }
+integer! { int, uint, "i", "u" }
 integer! { i8, u8 }
 integer! { i16, u16 }
 integer! { i32, u32 }