1
Fork 0

std: Tweak String implementations

This commit performs a pass over the implementations of the new `String` trait
in the formatting module. Some implementations were removed as a conservative
move pending an upcoming convention about `String` implementations, and some
were added in order to retain consistency across the libraries. Specifically:

* All "smart pointers" implement `String` now, adding missing implementations
  for `Arc` and `Rc`.
* The `Vec<T>` and `[T]` types no longer implement `String`.
* The `*const T` and `*mut T` type no longer implement `String`.
* The `()` type no longer implements `String`.
* The `Path` type's `Show` implementation does not surround itself with `Path
  {}` (a minor tweak).

All implementations of `String` in this PR were also marked `#[stable]` to
indicate that the types will continue to implement the `String` trait regardless
of what it looks like.
This commit is contained in:
Alex Crichton 2015-01-07 14:58:31 -08:00
parent 9f1ead8fad
commit 9851b4fbbf
22 changed files with 76 additions and 109 deletions

View file

@ -585,6 +585,13 @@ impl<T: fmt::Show> fmt::Show for Arc<T> {
} }
} }
#[stable]
impl<T: fmt::String> fmt::String for Arc<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::String::fmt(&**self, f)
}
}
#[stable] #[stable]
impl<T: Default + Sync + Send> Default for Arc<T> { impl<T: Default + Sync + Send> Default for Arc<T> {
#[stable] #[stable]

View file

@ -149,6 +149,7 @@ impl<T: ?Sized + fmt::Show> fmt::Show for Box<T> {
} }
} }
#[stable]
impl<T: ?Sized + fmt::String> fmt::String for Box<T> { impl<T: ?Sized + fmt::String> fmt::String for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::String::fmt(&**self, f) fmt::String::fmt(&**self, f)

View file

@ -611,6 +611,13 @@ impl<T: fmt::Show> fmt::Show for Rc<T> {
} }
} }
#[stable]
impl<T: fmt::String> fmt::String for Rc<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::String::fmt(&**self, f)
}
}
/// A weak version of `Rc<T>`. /// A weak version of `Rc<T>`.
/// ///
/// Weak references do not count when determining if the inner value should be dropped. /// Weak references do not count when determining if the inner value should be dropped.

View file

@ -681,6 +681,7 @@ impl fmt::Show for FromUtf8Error {
} }
} }
#[stable]
impl fmt::String for FromUtf8Error { impl fmt::String for FromUtf8Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::String::fmt(&self.error, f) fmt::String::fmt(&self.error, f)
@ -693,6 +694,7 @@ impl fmt::Show for FromUtf16Error {
} }
} }
#[stable]
impl fmt::String for FromUtf16Error { impl fmt::String for FromUtf16Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::String::fmt("invalid utf-16: lone surrogate found", f) fmt::String::fmt("invalid utf-16: lone surrogate found", f)
@ -805,7 +807,7 @@ impl Default for String {
} }
} }
#[experimental = "waiting on fmt stabilization"] #[stable]
impl fmt::String for String { impl fmt::String for String {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::String::fmt(&**self, f) fmt::String::fmt(&**self, f)
@ -1277,18 +1279,17 @@ mod tests {
assert_eq!(2u8.to_string(), "2"); assert_eq!(2u8.to_string(), "2");
assert_eq!(true.to_string(), "true"); assert_eq!(true.to_string(), "true");
assert_eq!(false.to_string(), "false"); assert_eq!(false.to_string(), "false");
assert_eq!(().to_string(), "()");
assert_eq!(("hi".to_string()).to_string(), "hi"); assert_eq!(("hi".to_string()).to_string(), "hi");
} }
#[test] #[test]
fn test_vectors() { fn test_vectors() {
let x: Vec<int> = vec![]; let x: Vec<int> = vec![];
assert_eq!(x.to_string(), "[]"); assert_eq!(format!("{:?}", x), "[]");
assert_eq!((vec![1i]).to_string(), "[1]"); assert_eq!(format!("{:?}", vec![1i]), "[1i]");
assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]"); assert_eq!(format!("{:?}", vec![1i, 2, 3]), "[1i, 2i, 3i]");
assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() == assert!(format!("{:?}", vec![vec![], vec![1i], vec![1i, 1]]) ==
"[[], [1], [1, 1]]"); "[[], [1i], [1i, 1i]]");
} }
#[test] #[test]

View file

@ -1454,22 +1454,6 @@ impl<T: fmt::Show> fmt::Show for Vec<T> {
} }
} }
#[cfg(stage0)]
#[experimental = "waiting on Show stability"]
impl<T: fmt::Show> fmt::String for Vec<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::String::fmt(self.as_slice(), f)
}
}
#[cfg(not(stage0))]
#[experimental = "waiting on Show stability"]
impl<T: fmt::String> fmt::String for Vec<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::String::fmt(self.as_slice(), f)
}
}
impl<'a> fmt::Writer for Vec<u8> { impl<'a> fmt::Writer for Vec<u8> {
fn write_str(&mut self, s: &str) -> fmt::Result { fn write_str(&mut self, s: &str) -> fmt::Result {
self.push_all(s.as_bytes()); self.push_all(s.as_bytes());

View file

@ -248,6 +248,7 @@ impl<'a, T, B: ?Sized> PartialOrd for Cow<'a, T, B> where B: PartialOrd + ToOwne
} }
} }
#[stable]
impl<'a, T, B: ?Sized> fmt::String for Cow<'a, T, B> where impl<'a, T, B: ?Sized> fmt::String for Cow<'a, T, B> where
B: fmt::String + ToOwned<T>, B: fmt::String + ToOwned<T>,
T: fmt::String, T: fmt::String,

View file

@ -219,6 +219,7 @@ impl<'a> Show for Arguments<'a> {
} }
} }
#[stable]
impl<'a> String for Arguments<'a> { impl<'a> String for Arguments<'a> {
fn fmt(&self, fmt: &mut Formatter) -> Result { fn fmt(&self, fmt: &mut Formatter) -> Result {
write(fmt.buf, *self) write(fmt.buf, *self)
@ -627,6 +628,7 @@ impl Show for bool {
} }
} }
#[stable]
impl String for bool { impl String for bool {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self, f: &mut Formatter) -> Result {
String::fmt(if *self { "true" } else { "false" }, f) String::fmt(if *self { "true" } else { "false" }, f)
@ -653,6 +655,7 @@ impl Show for str {
} }
} }
#[stable]
impl String for str { impl String for str {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self, f: &mut Formatter) -> Result {
f.pad(self) f.pad(self)
@ -680,6 +683,7 @@ impl Show for char {
} }
} }
#[stable]
impl String for char { impl String for char {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self, f: &mut Formatter) -> Result {
let mut utf8 = [0u8; 4]; let mut utf8 = [0u8; 4];
@ -725,6 +729,7 @@ macro_rules! floating { ($ty:ident) => {
} }
} }
#[stable]
impl String for $ty { impl String for $ty {
fn fmt(&self, fmt: &mut Formatter) -> Result { fn fmt(&self, fmt: &mut Formatter) -> Result {
use num::Float; use num::Float;
@ -796,15 +801,9 @@ floating! { f64 }
impl<T> Show for *const T { impl<T> Show for *const T {
fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } 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 { impl<T> Show for *mut T {
fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } 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 { macro_rules! peel {
($name:ident, $($other:ident,)*) => (tuple! { $($other,)* }) ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
@ -863,61 +862,12 @@ impl<T: Show> Show for [T] {
} }
} }
#[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 {
try!(write!(f, "]"));
}
Ok(())
}
}
impl Show for () { impl Show for () {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self, f: &mut Formatter) -> Result {
f.pad("()") f.pad("()")
} }
} }
impl String for () {
fn fmt(&self, f: &mut Formatter) -> Result {
f.pad("()")
}
}
impl<T: Copy + Show> Show for Cell<T> { impl<T: Copy + Show> Show for Cell<T> {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "Cell {{ value: {:?} }}", self.get()) write!(f, "Cell {{ value: {:?} }}", self.get())
@ -946,6 +896,7 @@ impl<'b, T: Show> Show for RefMut<'b, T> {
} }
} }
#[stable]
impl String for Utf8Error { impl String for Utf8Error {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self, f: &mut Formatter) -> Result {
match *self { match *self {

View file

@ -145,17 +145,18 @@
use self::Option::*; use self::Option::*;
use clone::Clone;
use cmp::{Eq, Ord}; use cmp::{Eq, Ord};
use default::Default; use default::Default;
use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator}; use fmt;
use iter::{ExactSizeIterator}; use iter::{ExactSizeIterator};
use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator};
use mem; use mem;
use result::Result;
use result::Result::{Ok, Err};
use slice;
use slice::AsSlice;
use clone::Clone;
use ops::{Deref, FnOnce}; use ops::{Deref, FnOnce};
use result::Result::{Ok, Err};
use result::Result;
use slice::AsSlice;
use slice;
// Note that this is not a lang item per se, but it has a hidden dependency on // Note that this is not a lang item per se, but it has a hidden dependency on
// `Iterator`, which is one. The compiler assumes that the `next` method of // `Iterator`, which is one. The compiler assumes that the `next` method of
@ -762,7 +763,6 @@ impl<T> AsSlice<T> for Option<T> {
#[stable] #[stable]
impl<T> Default for Option<T> { impl<T> Default for Option<T> {
#[stable]
#[inline] #[inline]
#[stable] #[stable]
fn default() -> Option<T> { None } fn default() -> Option<T> { None }

View file

@ -51,6 +51,8 @@ pub struct ConciseStability<'a>(pub &'a Option<clean::Stability>);
pub struct WhereClause<'a>(pub &'a clean::Generics); pub struct WhereClause<'a>(pub &'a clean::Generics);
/// Wrapper struct for emitting type parameter bounds. /// Wrapper struct for emitting type parameter bounds.
pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]); pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]);
/// Wrapper struct for emitting a comma-separated list of items
pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
impl VisSpace { impl VisSpace {
pub fn get(&self) -> Option<ast::Visibility> { pub fn get(&self) -> Option<ast::Visibility> {
@ -64,6 +66,16 @@ impl UnsafetySpace {
} }
} }
impl<'a, T: fmt::String> fmt::String for CommaSep<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, item) in self.0.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}", item));
}
Ok(())
}
}
//NOTE(stage0): remove impl after snapshot //NOTE(stage0): remove impl after snapshot
#[cfg(stage0)] #[cfg(stage0)]
impl<'a> fmt::Show for TyParamBounds<'a> { impl<'a> fmt::Show for TyParamBounds<'a> {
@ -530,7 +542,8 @@ impl fmt::String for clean::Type {
lifetimes = if decl.lifetimes.len() == 0 { lifetimes = if decl.lifetimes.len() == 0 {
"".to_string() "".to_string()
} else { } else {
format!("for &lt;{:#}&gt;", decl.lifetimes) format!("for &lt;{}&gt;",
CommaSep(decl.lifetimes.as_slice()))
}, },
args = decl.decl.inputs, args = decl.decl.inputs,
arrow = decl.decl.output, arrow = decl.decl.output,
@ -562,7 +575,8 @@ impl fmt::String for clean::Type {
lifetimes = if decl.lifetimes.len() == 0 { lifetimes = if decl.lifetimes.len() == 0 {
"".to_string() "".to_string()
} else { } else {
format!("for &lt;{:#}&gt;", decl.lifetimes) format!("for &lt;{}&gt;",
CommaSep(decl.lifetimes.as_slice()))
}, },
args = decl.decl.inputs, args = decl.decl.inputs,
bounds = if decl.bounds.len() == 0 { bounds = if decl.bounds.len() == 0 {
@ -592,7 +606,8 @@ impl fmt::String for clean::Type {
primitive_link(f, clean::PrimitiveTuple, primitive_link(f, clean::PrimitiveTuple,
match typs.as_slice() { match typs.as_slice() {
[ref one] => format!("({},)", one), [ref one] => format!("({},)", one),
many => format!("({:#})", many) many => format!("({})",
CommaSep(many.as_slice()))
}.as_slice()) }.as_slice())
} }
clean::Vector(ref t) => { clean::Vector(ref t) => {

View file

@ -60,7 +60,7 @@ pub fn is_sep(c: char) -> bool {
impl fmt::Show for Path { impl fmt::Show for Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Path {{ {} }}", self.display()) fmt::Show::fmt(&self.display(), f)
} }
} }

View file

@ -87,7 +87,7 @@ pub struct Path {
impl fmt::Show for Path { impl fmt::Show for Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Path {{ {} }}", self.display()) fmt::Show::fmt(&self.display(), f)
} }
} }

View file

@ -18,7 +18,7 @@ struct defer<'a> {
impl<'a> Drop for defer<'a> { impl<'a> Drop for defer<'a> {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
println!("{}", self.x); println!("{:?}", self.x);
} }
} }
} }

View file

@ -15,5 +15,5 @@ fn read_lines_borrowed<'a>() -> Vec<&'a str> {
} }
fn main() { fn main() {
println!("{}", read_lines_borrowed()); println!("{:?}", read_lines_borrowed());
} }

View file

@ -23,5 +23,5 @@ fn main() {
assert_eq!((*arc_v)[2], 3); assert_eq!((*arc_v)[2], 3);
println!("{}", *arc_v); println!("{:?}", *arc_v);
} }

View file

@ -21,5 +21,5 @@ fn main() {
assert_eq!((*arc_v)[2], 3); //~ ERROR use of moved value: `arc_v` assert_eq!((*arc_v)[2], 3); //~ ERROR use of moved value: `arc_v`
println!("{}", *arc_v); //~ ERROR use of moved value: `arc_v` println!("{:?}", *arc_v); //~ ERROR use of moved value: `arc_v`
} }

View file

@ -34,6 +34,6 @@ fn main() {
let foo = Foo { bar: [1u8, 2, 3, 4, 5], baz: 10i32 }; let foo = Foo { bar: [1u8, 2, 3, 4, 5], baz: 10i32 };
unsafe { unsafe {
let oof: Oof<[u8; 5], i32> = mem::transmute(foo); let oof: Oof<[u8; 5], i32> = mem::transmute(foo);
println!("{} {}", &oof.rab[], oof.zab); println!("{:?} {:?}", &oof.rab[], oof.zab);
} }
} }

View file

@ -22,7 +22,7 @@ pub fn main() {
let c : &[int] = &[2,2,2,2,3]; let c : &[int] = &[2,2,2,2,3];
let cc : &[int] = &[2,2,2,2,2,2]; let cc : &[int] = &[2,2,2,2,2,2];
println!("{}", a); println!("{:?}", a);
assert!(a < b); assert!(a < b);
assert!(a <= b); assert!(a <= b);
@ -30,7 +30,7 @@ pub fn main() {
assert!(b >= a); assert!(b >= a);
assert!(b > a); assert!(b > a);
println!("{}", b); println!("{:?}", b);
assert!(b < c); assert!(b < c);
assert!(b <= c); assert!(b <= c);
@ -44,7 +44,7 @@ pub fn main() {
assert!(c >= a); assert!(c >= a);
assert!(c > a); assert!(c > a);
println!("{}", c); println!("{:?}", c);
assert!(a < cc); assert!(a < cc);
assert!(a <= cc); assert!(a <= cc);
@ -52,5 +52,5 @@ pub fn main() {
assert!(cc >= a); assert!(cc >= a);
assert!(cc > a); assert!(cc > a);
println!("{}", cc); println!("{:?}", cc);
} }

View file

@ -183,7 +183,7 @@ fn test_write() {
// can do with them just yet (to test the output) // can do with them just yet (to test the output)
fn test_print() { fn test_print() {
print!("hi"); print!("hi");
print!("{}", vec!(0u8)); print!("{:?}", vec!(0u8));
println!("hello"); println!("hello");
println!("this is a {}", "test"); println!("this is a {}", "test");
println!("{foo}", foo="bar"); println!("{foo}", foo="bar");

View file

@ -15,7 +15,7 @@ fn main() {
let ss: &&[int] = &s; let ss: &&[int] = &s;
let sss: &&&[int] = &ss; let sss: &&&[int] = &ss;
println!("{}", &s[0..3]); println!("{:?}", &s[0..3]);
println!("{}", &ss[3..]); println!("{:?}", &ss[3..]);
println!("{}", &sss[2..4]); println!("{:?}", &sss[2..4]);
} }

View file

@ -25,6 +25,6 @@ static V: &'static [X] = &[X { vec: &[1, 2, 3] }];
pub fn main() { pub fn main() {
for &v in V.iter() { for &v in V.iter() {
println!("{}", v.vec); println!("{:?}", v.vec);
} }
} }

View file

@ -16,8 +16,8 @@ pub fn main() {
print!("["); print!("[");
for xi in x.iter() { for xi in x.iter() {
print!("{}, ", &xi[]); print!("{:?}, ", &xi[]);
} }
println!("]"); println!("]");
println!("{}", &y[]); println!("{:?}", &y[]);
} }

View file

@ -9,11 +9,11 @@
// except according to those terms. // except according to those terms.
pub fn main() { pub fn main() {
assert_eq!((vec!(0i, 1)).to_string(), "[0, 1]".to_string()); assert_eq!(format!("{:?}", vec!(0i, 1)), "[0i, 1i]".to_string());
let foo = vec!(3i, 4); let foo = vec!(3i, 4);
let bar: &[int] = &[4, 5]; let bar: &[int] = &[4, 5];
assert_eq!(foo.to_string(), "[3, 4]".to_string()); assert_eq!(format!("{:?}", foo), "[3i, 4i]");
assert_eq!(bar.to_string(), "[4, 5]".to_string()); assert_eq!(format!("{:?}", bar), "[4i, 5i]");
} }