From b78b749810f4ed53e8287adfb284f9f32f16b73c Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 19 Feb 2014 18:56:33 -0800 Subject: [PATCH] Remove all ToStr impls, add Show impls This commit changes the ToStr trait to: impl ToStr for T { fn to_str(&self) -> ~str { format!("{}", *self) } } The ToStr trait has been on the chopping block for quite awhile now, and this is the final nail in its coffin. The trait and the corresponding method are not being removed as part of this commit, but rather any implementations of the `ToStr` trait are being forbidden because of the generic impl. The new way to get the `to_str()` method to work is to implement `fmt::Show`. Formatting into a `&mut Writer` (as `format!` does) is much more efficient than `ToStr` when building up large strings. The `ToStr` trait forces many intermediate allocations to be made while the `fmt::Show` trait allows incremental buildup in the same heap allocated buffer. Additionally, the `fmt::Show` trait is much more extensible in terms of interoperation with other `Writer` instances and in more situations. By design the `ToStr` trait requires at least one allocation whereas the `fmt::Show` trait does not require any allocations. Closes #8242 Closes #9806 --- src/doc/tutorial.md | 2 +- src/libcollections/btree.rs | 60 +++---- src/libcollections/enum_set.rs | 2 +- src/libcollections/hashmap.rs | 8 - src/libcollections/lru_cache.rs | 27 ++-- src/libextra/json.rs | 16 +- src/libextra/url.rs | 147 +++++++++--------- src/libgetopts/lib.rs | 2 +- src/libnum/bigint.rs | 20 +-- src/libnum/complex.rs | 9 +- src/libnum/rational.rs | 7 +- src/librustc/middle/liveness.rs | 16 +- src/librustc/middle/mem_categorization.rs | 8 +- src/librustc/middle/ty.rs | 97 +++++++----- src/librustc/middle/typeck/variance.rs | 12 +- src/librustdoc/clean.rs | 2 +- src/librustdoc/doctree.rs | 2 +- src/librustuv/lib.rs | 9 +- src/libsemver/lib.rs | 15 -- src/libserialize/base64.rs | 9 +- src/libserialize/hex.rs | 9 +- src/libstd/any.rs | 9 -- src/libstd/ascii.rs | 10 +- src/libstd/bool.rs | 17 -- src/libstd/char.rs | 10 +- src/libstd/fmt/mod.rs | 10 ++ src/libstd/io/mod.rs | 42 +---- src/libstd/io/net/ip.rs | 27 ++-- src/libstd/num/f32.rs | 6 - src/libstd/num/f64.rs | 6 - src/libstd/num/int_macros.rs | 8 - src/libstd/num/uint_macros.rs | 8 - src/libstd/option.rs | 15 +- src/libstd/path/mod.rs | 11 -- src/libstd/result.rs | 19 +-- src/libstd/str.rs | 16 -- src/libstd/to_str.rs | 48 +----- src/libstd/tuple.rs | 7 - src/libsyntax/abi.rs | 21 ++- src/libsyntax/ast.rs | 55 +++---- src/libsyntax/ast_map.rs | 8 +- src/libsyntax/attr.rs | 2 +- src/libsyntax/crateid.rs | 11 +- src/libsyntax/diagnostic.rs | 15 +- src/libtest/lib.rs | 20 +-- src/libuuid/lib.rs | 43 +++-- src/test/auxiliary/cci_class_cast.rs | 8 +- ...use-after-move-implicity-coerced-object.rs | 8 +- src/test/run-pass/class-separate-impl.rs | 9 +- src/test/run-pass/deriving-global.rs | 6 +- src/test/run-pass/deriving-in-fn.rs | 4 +- ...{deriving-to-str.rs => deriving-show-2.rs} | 32 ++-- src/test/run-pass/issue-2904.rs | 10 +- src/test/run-pass/issue-3563-3.rs | 7 +- src/test/run-pass/new-impl-syntax.rs | 14 +- 55 files changed, 414 insertions(+), 607 deletions(-) rename src/test/run-pass/{deriving-to-str.rs => deriving-show-2.rs} (71%) diff --git a/src/doc/tutorial.md b/src/doc/tutorial.md index 2e6a0ef7e5b..c2469e0c171 100644 --- a/src/doc/tutorial.md +++ b/src/doc/tutorial.md @@ -2519,7 +2519,7 @@ of type `ABC` can be randomly generated and converted to a string: #[deriving(Eq)] struct Circle { radius: f64 } -#[deriving(Rand, ToStr)] +#[deriving(Rand, Show)] enum ABC { A, B, C } ~~~ diff --git a/src/libcollections/btree.rs b/src/libcollections/btree.rs index 13b39da0756..cc6a5eda759 100644 --- a/src/libcollections/btree.rs +++ b/src/libcollections/btree.rs @@ -18,7 +18,8 @@ ///a length (the height of the tree), and lower and upper bounds on the ///number of elements that a given node can contain. -use std::vec::OwnedVector; +use std::fmt; +use std::fmt::Show; #[allow(missing_doc)] pub struct BTree { @@ -106,11 +107,10 @@ impl TotalOrd for BTree { } } -impl ToStr for BTree { +impl fmt::Show for BTree { ///Returns a string representation of the BTree - fn to_str(&self) -> ~str { - let ret = self.root.to_str(); - ret + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.root.fmt(f) } } @@ -235,15 +235,15 @@ impl TotalOrd for Node { } } -impl ToStr for Node { +impl fmt::Show for Node { ///Returns a string representation of a Node. ///Will iterate over the Node and show "Key: x, value: y, child: () // " ///for all elements in the Node. "Child" only exists if the Node contains ///a branch. - fn to_str(&self) -> ~str { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - LeafNode(ref leaf) => leaf.to_str(), - BranchNode(ref branch) => branch.to_str() + LeafNode(ref leaf) => leaf.fmt(f), + BranchNode(ref branch) => branch.fmt(f), } } } @@ -401,10 +401,14 @@ impl TotalOrd for Leaf { } -impl ToStr for Leaf { +impl fmt::Show for Leaf { ///Returns a string representation of a Leaf. - fn to_str(&self) -> ~str { - self.elts.iter().map(|s| s.to_str()).to_owned_vec().connect(" // ") + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + for (i, s) in self.elts.iter().enumerate() { + if i != 0 { if_ok!(write!(f.buf, " // ")) } + if_ok!(write!(f.buf, "{}", *s)) + } + Ok(()) } } @@ -618,13 +622,14 @@ impl TotalOrd for Branch { } } -impl ToStr for Branch { +impl fmt::Show for Branch { ///Returns a string representation of a Branch. - fn to_str(&self) -> ~str { - let mut ret = self.elts.iter().map(|s| s.to_str()).to_owned_vec().connect(" // "); - ret.push_str(" // "); - ret.push_str("rightmost child: ("+ self.rightmost_child.to_str() +") "); - ret + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + for (i, s) in self.elts.iter().enumerate() { + if i != 0 { if_ok!(write!(f.buf, " // ")) } + if_ok!(write!(f.buf, "{}", *s)) + } + write!(f.buf, " // rightmost child: ({}) ", *self.rightmost_child) } } @@ -672,11 +677,10 @@ impl TotalOrd for LeafElt { } } -impl ToStr for LeafElt { +impl fmt::Show for LeafElt { ///Returns a string representation of a LeafElt. - fn to_str(&self) -> ~str { - format!("Key: {}, value: {};", - self.key.to_str(), self.value.to_str()) + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "Key: {}, value: {};", self.key, self.value) } } @@ -715,12 +719,12 @@ impl TotalOrd for BranchElt { } } -impl ToStr for BranchElt { - ///Returns string containing key, value, and child (which should recur to a leaf) - ///Consider changing in future to be more readable. - fn to_str(&self) -> ~str { - format!("Key: {}, value: {}, (child: {})", - self.key.to_str(), self.value.to_str(), self.left.to_str()) +impl fmt::Show for BranchElt { + /// Returns string containing key, value, and child (which should recur to a + /// leaf) Consider changing in future to be more readable. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "Key: {}, value: {}, (child: {})", + self.key, self.value, *self.left) } } diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index 0de6eaf53dd..2bd8cbf03e9 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -15,7 +15,7 @@ use std::num::Bitwise; -#[deriving(Clone, Eq, Hash, ToStr, Encodable, Decodable)] +#[deriving(Clone, Eq, Hash, Show, Encodable, Decodable)] /// A specialized Set implementation to use enum types. pub struct EnumSet { // We must maintain the invariant that no bits are set diff --git a/src/libcollections/hashmap.rs b/src/libcollections/hashmap.rs index fe56dbdd2f1..877f2b30009 100644 --- a/src/libcollections/hashmap.rs +++ b/src/libcollections/hashmap.rs @@ -606,10 +606,6 @@ impl fmt::Show for HashMap { } } -impl ToStr for HashMap { - fn to_str(&self) -> ~str { format!("{}", *self) } -} - /// HashMap iterator #[deriving(Clone)] pub struct Entries<'a, K, V> { @@ -888,10 +884,6 @@ impl fmt::Show for HashSet { } } -impl ToStr for HashSet { - fn to_str(&self) -> ~str { format!("{}", *self) } -} - impl FromIterator for HashSet { fn from_iterator>(iter: &mut T) -> HashSet { let (lower, _) = iter.size_hint(); diff --git a/src/libcollections/lru_cache.rs b/src/libcollections/lru_cache.rs index ec387df7215..b5e44cda665 100644 --- a/src/libcollections/lru_cache.rs +++ b/src/libcollections/lru_cache.rs @@ -37,10 +37,11 @@ //! assert!(cache.get(&2).is_none()); //! ``` +use std::cast; use std::container::Container; use std::hash::{Hash, sip}; +use std::fmt; use std::ptr; -use std::cast; use HashMap; @@ -217,36 +218,32 @@ impl LruCache { } } -impl ToStr for LruCache { +impl fmt::Show for LruCache { /// Return a string that lists the key-value pairs from most-recently /// used to least-recently used. - #[inline] - fn to_str(&self) -> ~str { - let mut acc = ~"{"; + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if_ok!(write!(f.buf, r"\{")); let mut cur = self.head; for i in range(0, self.len()) { - if i > 0 { - acc.push_str(", "); - } + if i > 0 { if_ok!(write!(f.buf, ", ")) } unsafe { cur = (*cur).next; match (*cur).key { // should never print nil - None => acc.push_str("nil"), - Some(ref k) => acc.push_str(k.to_str()) + None => if_ok!(write!(f.buf, "nil")), + Some(ref k) => if_ok!(write!(f.buf, "{}", *k)), } } - acc.push_str(": "); + if_ok!(write!(f.buf, ": ")); unsafe { match (*cur).value { // should never print nil - None => acc.push_str("nil"), - Some(ref value) => acc.push_str(value.to_str()) + None => if_ok!(write!(f.buf, "nil")), + Some(ref value) => if_ok!(write!(f.buf, "{}", *value)), } } } - acc.push_char('}'); - acc + write!(f.buf, r"\}") } } diff --git a/src/libextra/json.rs b/src/libextra/json.rs index 4cc210aaa6c..d438b00b992 100644 --- a/src/libextra/json.rs +++ b/src/libextra/json.rs @@ -240,7 +240,7 @@ use std::io; use std::io::MemWriter; use std::num; use std::str; -use std::to_str; +use std::fmt; use serialize::Encodable; use serialize; @@ -1576,18 +1576,16 @@ impl ToJson for Option { } } -impl to_str::ToStr for Json { +impl fmt::Show for Json { /// Encodes a json value into a string - fn to_str(&self) -> ~str { - let mut s = MemWriter::new(); - self.to_writer(&mut s as &mut io::Writer).unwrap(); - str::from_utf8_owned(s.unwrap()).unwrap() + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.to_writer(f.buf) } } -impl to_str::ToStr for Error { - fn to_str(&self) -> ~str { - format!("{}:{}: {}", self.line, self.col, self.msg) +impl fmt::Show for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}:{}: {}", self.line, self.col, self.msg) } } diff --git a/src/libextra/url.rs b/src/libextra/url.rs index 41d6d95c6bb..6e0cd72e3e7 100644 --- a/src/libextra/url.rs +++ b/src/libextra/url.rs @@ -12,12 +12,14 @@ #[allow(missing_doc)]; -use std::io::BufReader; use std::cmp::Eq; -use collections::HashMap; +use std::fmt; use std::hash::{Hash, sip}; +use std::io::BufReader; use std::uint; +use collections::HashMap; + /// A Uniform Resource Locator (URL). A URL is a form of URI (Uniform Resource /// Identifier) that includes network location information, such as hostname or /// port number. @@ -407,10 +409,12 @@ fn split_char_first(s: &str, c: char) -> (~str, ~str) { } } -fn userinfo_to_str(userinfo: &UserInfo) -> ~str { - match userinfo.pass { - Some(ref pass) => format!("{}:{}@", userinfo.user, *pass), - None => format!("{}@", userinfo.user), +impl fmt::Show for UserInfo { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.pass { + Some(ref pass) => write!(f.buf, "{}:{}@", self.user, *pass), + None => write!(f.buf, "{}@", self.user), + } } } @@ -437,19 +441,18 @@ fn query_from_str(rawquery: &str) -> Query { * println!("{}", url::query_to_str(&query)); // title=The%20Village&north=52.91&west=4.10 * ``` */ +#[allow(unused_must_use)] pub fn query_to_str(query: &Query) -> ~str { - let mut strvec = ~[]; - for kv in query.iter() { - match kv { - &(ref k, ref v) => { - strvec.push(format!("{}={}", - encode_component(*k), - encode_component(*v)) - ); - } - } + use std::io::MemWriter; + use std::str; + + let mut writer = MemWriter::new(); + for (i, &(ref k, ref v)) in query.iter().enumerate() { + if i != 0 { write!(&mut writer, "&"); } + write!(&mut writer, "{}={}", encode_component(*k), + encode_component(*v)); } - return strvec.connect("&"); + str::from_utf8_lossy(writer.unwrap()).into_owned() } /** @@ -784,74 +787,64 @@ impl FromStr for Path { } } -/** - * Converts a URL from `Url` to string representation. - * - * # Arguments - * - * `url` - a URL. - * - * # Returns - * - * A string that contains the formatted URL. Note that this will usually - * be an inverse of `from_str` but might strip out unneeded separators; - * for example, "http://somehost.com?", when parsed and formatted, will - * result in just "http://somehost.com". - */ -pub fn to_str(url: &Url) -> ~str { - let user = match url.user { - Some(ref user) => userinfo_to_str(user), - None => ~"", - }; +impl fmt::Show for Url { + /** + * Converts a URL from `Url` to string representation. + * + * # Arguments + * + * `url` - a URL. + * + * # Returns + * + * A string that contains the formatted URL. Note that this will usually + * be an inverse of `from_str` but might strip out unneeded separators; + * for example, "http://somehost.com?", when parsed and formatted, will + * result in just "http://somehost.com". + */ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if_ok!(write!(f.buf, "{}:", self.scheme)); - let authority = if url.host.is_empty() { - // If port is Some, we're in a nonsensical situation. Too bad. - ~"" - } else { - match url.port { - Some(ref port) => format!("//{}{}:{}", user, url.host, *port), - None => format!("//{}{}", user, url.host), + if !self.host.is_empty() { + if_ok!(write!(f.buf, "//")); + match self.user { + Some(ref user) => if_ok!(write!(f.buf, "{}", *user)), + None => {} + } + match self.port { + Some(ref port) => if_ok!(write!(f.buf, "{}:{}", self.host, + *port)), + None => if_ok!(write!(f.buf, "{}", self.host)), + } } - }; - let query = if url.query.is_empty() { - ~"" - } else { - format!("?{}", query_to_str(&url.query)) - }; + if_ok!(write!(f.buf, "{}", self.path)); - let fragment = match url.fragment { - Some(ref fragment) => format!("\\#{}", encode_component(*fragment)), - None => ~"", - }; + if !self.query.is_empty() { + if_ok!(write!(f.buf, "?{}", query_to_str(&self.query))); + } - format!("{}:{}{}{}{}", url.scheme, authority, url.path, query, fragment) -} - -pub fn path_to_str(path: &Path) -> ~str { - let query = if path.query.is_empty() { - ~"" - } else { - format!("?{}", query_to_str(&path.query)) - }; - - let fragment = match path.fragment { - Some(ref fragment) => format!("\\#{}", encode_component(*fragment)), - None => ~"", - }; - - format!("{}{}{}", path.path, query, fragment) -} - -impl ToStr for Url { - fn to_str(&self) -> ~str { - to_str(self) + match self.fragment { + Some(ref fragment) => write!(f.buf, "\\#{}", + encode_component(*fragment)), + None => Ok(()), + } } } -impl ToStr for Path { - fn to_str(&self) -> ~str { - path_to_str(self) +impl fmt::Show for Path { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if_ok!(write!(f.buf, "{}", self.path)); + if !self.query.is_empty() { + if_ok!(write!(f.buf, "?{}", self.query)) + } + + match self.fragment { + Some(ref fragment) => { + write!(f.buf, "\\#{}", encode_component(*fragment)) + } + None => Ok(()) + } } } diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index 537c2d40c66..20594105183 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -169,7 +169,7 @@ pub struct Matches { /// The type returned when the command line does not conform to the /// expected format. Call the `to_err_msg` method to retrieve the /// error as a string. -#[deriving(Clone, Eq, ToStr)] +#[deriving(Clone, Eq, Show)] #[allow(missing_doc)] pub enum Fail_ { ArgumentMissing(~str), diff --git a/src/libnum/bigint.rs b/src/libnum/bigint.rs index 0418c61d361..894b3794581 100644 --- a/src/libnum/bigint.rs +++ b/src/libnum/bigint.rs @@ -19,14 +19,14 @@ A `BigInt` is a combination of `BigUint` and `Sign`. use Integer; use std::cmp; -use std::cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater}; -use std::num::{Zero, One, ToStrRadix, FromStrRadix}; +use std::fmt; use std::num::{Bitwise, ToPrimitive, FromPrimitive}; +use std::num::{Zero, One, ToStrRadix, FromStrRadix}; use std::rand::Rng; use std::str; use std::uint; -use std::{i64, u64}; use std::vec; +use std::{i64, u64}; /** A `BigDigit` is a `BigUint`'s composing element. @@ -121,9 +121,10 @@ impl TotalOrd for BigUint { } } -impl ToStr for BigUint { - #[inline] - fn to_str(&self) -> ~str { self.to_str_radix(10) } +impl fmt::Show for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.to_str_radix(10)) + } } impl FromStr for BigUint { @@ -904,9 +905,10 @@ impl TotalOrd for BigInt { } } -impl ToStr for BigInt { - #[inline] - fn to_str(&self) -> ~str { self.to_str_radix(10) } +impl fmt::Show for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.to_str_radix(10)) + } } impl FromStr for BigInt { diff --git a/src/libnum/complex.rs b/src/libnum/complex.rs index 3755b2e43af..5ffd23aa346 100644 --- a/src/libnum/complex.rs +++ b/src/libnum/complex.rs @@ -11,6 +11,7 @@ //! Complex numbers. +use std::fmt; use std::num::{Zero,One,ToStrRadix}; // FIXME #1284: handle complex NaN & infinity etc. This @@ -167,12 +168,12 @@ impl One for Cmplx { } /* string conversions */ -impl ToStr for Cmplx { - fn to_str(&self) -> ~str { +impl fmt::Show for Cmplx { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < Zero::zero() { - format!("{}-{}i", self.re.to_str(), (-self.im).to_str()) + write!(f.buf, "{}-{}i", self.re, -self.im) } else { - format!("{}+{}i", self.re.to_str(), self.im.to_str()) + write!(f.buf, "{}+{}i", self.re, self.im) } } } diff --git a/src/libnum/rational.rs b/src/libnum/rational.rs index 5f1868b48c5..44a916c5d4e 100644 --- a/src/libnum/rational.rs +++ b/src/libnum/rational.rs @@ -13,6 +13,7 @@ use Integer; use std::cmp; +use std::fmt; use std::from_str::FromStr; use std::num::{Zero,One,ToStrRadix,FromStrRadix,Round}; use bigint::{BigInt, BigUint, Sign, Plus, Minus}; @@ -277,10 +278,10 @@ impl } /* String conversions */ -impl ToStr for Ratio { +impl fmt::Show for Ratio { /// Renders as `numer/denom`. - fn to_str(&self) -> ~str { - format!("{}/{}", self.numer.to_str(), self.denom.to_str()) + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}/{}", self.numer, self.denom) } } impl ToStrRadix for Ratio { diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 3b9f81adbac..7293c3a3cee 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -111,12 +111,12 @@ use middle::moves; use std::cast::transmute; use std::cell::{Cell, RefCell}; -use collections::HashMap; +use std::fmt; use std::io; use std::str; -use std::to_str; use std::uint; use std::vec; +use collections::HashMap; use syntax::ast::*; use syntax::codemap::Span; use syntax::parse::token::special_idents; @@ -184,12 +184,16 @@ pub fn check_crate(tcx: ty::ctxt, tcx.sess.abort_if_errors(); } -impl to_str::ToStr for LiveNode { - fn to_str(&self) -> ~str { format!("ln({})", self.get()) } +impl fmt::Show for LiveNode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "ln({})", self.get()) + } } -impl to_str::ToStr for Variable { - fn to_str(&self) -> ~str { format!("v({})", self.get()) } +impl fmt::Show for Variable { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "v({})", self.get()) + } } // ______________________________________________________________________ diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index c413439cb53..0882e8eb692 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -123,7 +123,7 @@ pub enum ElementKind { OtherElement, } -#[deriving(Eq, Hash)] +#[deriving(Eq, Hash, Show)] pub enum MutabilityCategory { McImmutable, // Immutable. McDeclared, // Directly declared as mutable. @@ -273,12 +273,6 @@ pub trait Typer { fn upvar_borrow(&mut self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow; } -impl ToStr for MutabilityCategory { - fn to_str(&self) -> ~str { - format!("{:?}", *self) - } -} - impl MutabilityCategory { pub fn from_mutbl(m: ast::Mutability) -> MutabilityCategory { match m { diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 8d88c084e99..b351b5c0cb8 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -33,10 +33,11 @@ use util::common::{indenter}; use std::cast; use std::cell::{Cell, RefCell}; use std::cmp; +use std::fmt::Show; +use std::fmt; use std::hash::{Hash, sip}; use std::ops; use std::rc::Rc; -use std::to_str::ToStr; use std::vec; use collections::{HashMap, HashSet}; use syntax::ast::*; @@ -128,14 +129,14 @@ pub struct mt { mutbl: ast::Mutability, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash, ToStr)] +#[deriving(Clone, Eq, Encodable, Decodable, Hash, Show)] pub enum vstore { vstore_fixed(uint), vstore_uniq, vstore_slice(Region) } -#[deriving(Clone, Eq, Hash, Encodable, Decodable, ToStr)] +#[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)] pub enum TraitStore { UniqTraitStore, // ~Trait RegionTraitStore(Region), // &Trait @@ -196,7 +197,7 @@ pub struct ItemVariances { region_params: OptVec } -#[deriving(Clone, Eq, Decodable, Encodable)] +#[deriving(Clone, Eq, Decodable, Encodable, Show)] pub enum Variance { Covariant, // T <: T iff A <: B -- e.g., function return type Invariant, // T <: T iff B == A -- e.g., type of mutable cell @@ -384,11 +385,13 @@ pub struct t_box_ { // ~15%.) This does mean that a t value relies on the ctxt to keep its box // alive, and using ty::get is unsafe when the ctxt is no longer alive. enum t_opaque {} -pub type t = *t_opaque; -impl ToStr for t { - fn to_str(&self) -> ~str { - ~"*t_opaque" +#[deriving(Clone, Eq, Hash)] +pub struct t { priv inner: *t_opaque } + +impl fmt::Show for t { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.buf.write_str("*t_opaque") } } @@ -458,7 +461,7 @@ pub struct param_ty { } /// Representation of regions: -#[deriving(Clone, Eq, Hash, Encodable, Decodable, ToStr, Show)] +#[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)] pub enum Region { // Region bound in a type or fn declaration which will be // substituted 'early' -- that is, at the same time when type @@ -618,13 +621,13 @@ impl Region { } } -#[deriving(Clone, Eq, TotalOrd, TotalEq, Hash, Encodable, Decodable, ToStr, Show)] +#[deriving(Clone, Eq, TotalOrd, TotalEq, Hash, Encodable, Decodable, Show)] pub struct FreeRegion { scope_id: NodeId, bound_region: BoundRegion } -#[deriving(Clone, Eq, TotalEq, TotalOrd, Hash, Encodable, Decodable, ToStr, Show)] +#[deriving(Clone, Eq, TotalEq, TotalOrd, Hash, Encodable, Decodable, Show)] pub enum BoundRegion { /// An anonymous region parameter for a given fn (&T) BrAnon(uint), @@ -768,7 +771,7 @@ pub enum IntVarValue { UintType(ast::UintTy), } -#[deriving(Clone, ToStr)] +#[deriving(Clone, Show)] pub enum terr_vstore_kind { terr_vec, terr_str, @@ -776,14 +779,14 @@ pub enum terr_vstore_kind { terr_trait } -#[deriving(Clone, ToStr)] +#[deriving(Clone, Show)] pub struct expected_found { expected: T, found: T } // Data structures used in type unification -#[deriving(Clone, ToStr)] +#[deriving(Clone, Show)] pub enum type_err { terr_mismatch, terr_purity_mismatch(expected_found), @@ -826,7 +829,7 @@ pub struct ParamBounds { pub type BuiltinBounds = EnumSet; -#[deriving(Clone, Encodable, Eq, Decodable, Hash, ToStr)] +#[deriving(Clone, Encodable, Eq, Decodable, Hash, Show)] #[repr(uint)] pub enum BuiltinBound { BoundStatic, @@ -867,7 +870,7 @@ pub struct IntVid(uint); #[deriving(Clone, Eq, Hash)] pub struct FloatVid(uint); -#[deriving(Clone, Eq, Encodable, Decodable, Hash, Show)] +#[deriving(Clone, Eq, Encodable, Decodable, Hash)] pub struct RegionVid { id: uint } @@ -879,7 +882,7 @@ pub enum InferTy { FloatVar(FloatVid) } -#[deriving(Clone, Encodable, Decodable, Hash, ToStr, Show)] +#[deriving(Clone, Encodable, Decodable, Hash, Show)] pub enum InferRegion { ReVar(RegionVid), ReSkolemized(uint, BoundRegion) @@ -910,56 +913,64 @@ impl Vid for TyVid { fn to_uint(&self) -> uint { let TyVid(v) = *self; v } } -impl ToStr for TyVid { - fn to_str(&self) -> ~str { format!("", self.to_uint()) } +impl fmt::Show for TyVid { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{ + write!(f.buf, "", self.to_uint()) + } } impl Vid for IntVid { fn to_uint(&self) -> uint { let IntVid(v) = *self; v } } -impl ToStr for IntVid { - fn to_str(&self) -> ~str { format!("", self.to_uint()) } +impl fmt::Show for IntVid { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "", self.to_uint()) + } } impl Vid for FloatVid { fn to_uint(&self) -> uint { let FloatVid(v) = *self; v } } -impl ToStr for FloatVid { - fn to_str(&self) -> ~str { format!("", self.to_uint()) } +impl fmt::Show for FloatVid { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "", self.to_uint()) + } } impl Vid for RegionVid { fn to_uint(&self) -> uint { self.id } } -impl ToStr for RegionVid { - fn to_str(&self) -> ~str { format!("{:?}", self.id) } -} - -impl ToStr for FnSig { - fn to_str(&self) -> ~str { - // grr, without tcx not much we can do. - return ~"(...)"; +impl fmt::Show for RegionVid { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.id.fmt(f) } } -impl ToStr for InferTy { - fn to_str(&self) -> ~str { +impl fmt::Show for FnSig { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // grr, without tcx not much we can do. + write!(f.buf, "(...)") + } +} + +impl fmt::Show for InferTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - TyVar(ref v) => v.to_str(), - IntVar(ref v) => v.to_str(), - FloatVar(ref v) => v.to_str() + TyVar(ref v) => v.fmt(f), + IntVar(ref v) => v.fmt(f), + FloatVar(ref v) => v.fmt(f), } } } -impl ToStr for IntVarValue { - fn to_str(&self) -> ~str { +impl fmt::Show for IntVarValue { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - IntType(ref v) => v.to_str(), - UintType(ref v) => v.to_str(), + IntType(ref v) => v.fmt(f), + UintType(ref v) => v.fmt(f), } } } @@ -2020,9 +2031,9 @@ impl ops::Sub for TypeContents { } } -impl ToStr for TypeContents { - fn to_str(&self) -> ~str { - format!("TypeContents({:t})", self.bits) +impl fmt::Show for TypeContents { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "TypeContents({:t})", self.bits) } } diff --git a/src/librustc/middle/typeck/variance.rs b/src/librustc/middle/typeck/variance.rs index 47c40514e6c..bd244b431c2 100644 --- a/src/librustc/middle/typeck/variance.rs +++ b/src/librustc/middle/typeck/variance.rs @@ -197,6 +197,7 @@ use arena; use arena::Arena; use middle::ty; use std::vec; +use std::fmt; use syntax::ast; use syntax::ast_util; use syntax::opt_vec; @@ -235,13 +236,12 @@ enum VarianceTerm<'a> { InferredTerm(InferredIndex), } -impl<'a> ToStr for VarianceTerm<'a> { - fn to_str(&self) -> ~str { +impl<'a> fmt::Show for VarianceTerm<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ConstantTerm(c1) => format!("{}", c1.to_str()), - TransformTerm(v1, v2) => format!("({} \u00D7 {})", - v1.to_str(), v2.to_str()), - InferredTerm(id) => format!("[{}]", { let InferredIndex(i) = id; i }) + ConstantTerm(c1) => write!(f.buf, "{}", c1), + TransformTerm(v1, v2) => write!(f.buf, "({} \u00D7 {})", v1, v2), + InferredTerm(id) => write!(f.buf, "[{}]", { let InferredIndex(i) = id; i }) } } } diff --git a/src/librustdoc/clean.rs b/src/librustdoc/clean.rs index 6e6276e0457..2f6f6726be6 100644 --- a/src/librustdoc/clean.rs +++ b/src/librustdoc/clean.rs @@ -976,7 +976,7 @@ impl Clean for doctree::Static { } } -#[deriving(ToStr, Clone, Encodable, Decodable)] +#[deriving(Show, Clone, Encodable, Decodable)] pub enum Mutability { Mutable, Immutable, diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs index 03186c16733..af082544532 100644 --- a/src/librustdoc/doctree.rs +++ b/src/librustdoc/doctree.rs @@ -58,7 +58,7 @@ impl Module { } } -#[deriving(ToStr, Clone, Encodable, Decodable)] +#[deriving(Show, Clone, Encodable, Decodable)] pub enum StructType { /// A normal struct Plain, diff --git a/src/librustuv/lib.rs b/src/librustuv/lib.rs index adbe4491886..9b327dc4ee4 100644 --- a/src/librustuv/lib.rs +++ b/src/librustuv/lib.rs @@ -45,8 +45,9 @@ via `close` and `delete` methods. #[cfg(test)] extern crate green; use std::cast; -use std::io; +use std::fmt; use std::io::IoError; +use std::io; use std::libc::{c_int, c_void}; use std::ptr::null; use std::ptr; @@ -339,9 +340,9 @@ impl UvError { } } -impl ToStr for UvError { - fn to_str(&self) -> ~str { - format!("{}: {}", self.name(), self.desc()) +impl fmt::Show for UvError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}: {}", self.name(), self.desc()) } } diff --git a/src/libsemver/lib.rs b/src/libsemver/lib.rs index d03d230d8bf..4c596b11ad6 100644 --- a/src/libsemver/lib.rs +++ b/src/libsemver/lib.rs @@ -38,7 +38,6 @@ use std::cmp; use std::fmt; use std::fmt::Show; use std::option::{Option, Some, None}; -use std::to_str::ToStr; /// An identifier in the pre-release or build metadata. If the identifier can /// be parsed as a decimal value, it will be represented with `Numeric`. @@ -71,13 +70,6 @@ impl fmt::Show for Identifier { } } -impl ToStr for Identifier { - #[inline] - fn to_str(&self) -> ~str { - format!("{}", *self) - } -} - /// Represents a version number conforming to the semantic versioning scheme. #[deriving(Clone, Eq)] @@ -118,13 +110,6 @@ impl fmt::Show for Version { } } -impl ToStr for Version { - #[inline] - fn to_str(&self) -> ~str { - format!("{}", *self) - } -} - impl cmp::Ord for Version { #[inline] fn lt(&self, other: &Version) -> bool { diff --git a/src/libserialize/base64.rs b/src/libserialize/base64.rs index 839450ce57c..f43c62f6ffc 100644 --- a/src/libserialize/base64.rs +++ b/src/libserialize/base64.rs @@ -10,6 +10,7 @@ //! Base64 binary-to-text encoding use std::str; +use std::fmt; /// Available encoding character sets pub enum CharacterSet { @@ -165,12 +166,12 @@ pub enum FromBase64Error { InvalidBase64Length, } -impl ToStr for FromBase64Error { - fn to_str(&self) -> ~str { +impl fmt::Show for FromBase64Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidBase64Character(ch, idx) => - format!("Invalid character '{}' at position {}", ch, idx), - InvalidBase64Length => ~"Invalid length", + write!(f.buf, "Invalid character '{}' at position {}", ch, idx), + InvalidBase64Length => write!(f.buf, "Invalid length"), } } } diff --git a/src/libserialize/hex.rs b/src/libserialize/hex.rs index 223a586a5a0..5ec70773c3f 100644 --- a/src/libserialize/hex.rs +++ b/src/libserialize/hex.rs @@ -11,6 +11,7 @@ //! Hex binary-to-text encoding use std::str; use std::vec; +use std::fmt; /// A trait for converting a value to hexadecimal encoding pub trait ToHex { @@ -65,12 +66,12 @@ pub enum FromHexError { InvalidHexLength, } -impl ToStr for FromHexError { - fn to_str(&self) -> ~str { +impl fmt::Show for FromHexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidHexCharacter(ch, idx) => - format!("Invalid character '{}' at position {}", ch, idx), - InvalidHexLength => ~"Invalid input length", + write!(f.buf, "Invalid character '{}' at position {}", ch, idx), + InvalidHexLength => write!(f.buf, "Invalid input length"), } } } diff --git a/src/libstd/any.rs b/src/libstd/any.rs index 06ae20d60bc..551a34fc87f 100644 --- a/src/libstd/any.rs +++ b/src/libstd/any.rs @@ -24,7 +24,6 @@ use cast::transmute; use fmt; use option::{Option, Some, None}; use result::{Result, Ok, Err}; -use to_str::ToStr; use intrinsics::TypeId; use intrinsics; @@ -151,14 +150,6 @@ impl AnyOwnExt for ~Any { // Trait implementations /////////////////////////////////////////////////////////////////////////////// -impl ToStr for ~Any { - fn to_str(&self) -> ~str { ~"~Any" } -} - -impl<'a> ToStr for &'a Any { - fn to_str(&self) -> ~str { ~"&Any" } -} - impl fmt::Show for ~Any { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad("~Any") diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 1ae36ab46aa..ac24a02c15b 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -10,7 +10,7 @@ //! Operations on ASCII strings and characters -use to_str::{ToStr, IntoStr}; +use to_str::{IntoStr}; use str; use str::Str; use str::StrSlice; @@ -127,14 +127,6 @@ impl Ascii { } } -impl ToStr for Ascii { - #[inline] - fn to_str(&self) -> ~str { - // self.chr is always a valid utf8 byte, no need for the check - unsafe { str::raw::from_byte(self.chr) } - } -} - impl<'a> fmt::Show for Ascii { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (self.chr as char).fmt(f) diff --git a/src/libstd/bool.rs b/src/libstd/bool.rs index af745f94fb5..918d42e1bce 100644 --- a/src/libstd/bool.rs +++ b/src/libstd/bool.rs @@ -17,7 +17,6 @@ //! Implementations of the following traits: //! //! * `FromStr` -//! * `ToStr` //! * `Not` //! * `Ord` //! * `TotalOrd` @@ -34,7 +33,6 @@ use option::{None, Option, Some}; use from_str::FromStr; -use to_str::ToStr; use num::FromPrimitive; #[cfg(not(test))] use cmp::{Eq, Ord, TotalOrd, Ordering}; @@ -179,21 +177,6 @@ impl FromStr for bool { } } -impl ToStr for bool { - /// Convert a `bool` to a string. - /// - /// # Examples - /// - /// ```rust - /// assert_eq!(true.to_str(), ~"true"); - /// assert_eq!(false.to_str(), ~"false"); - /// ``` - #[inline] - fn to_str(&self) -> ~str { - if *self { ~"true" } else { ~"false" } - } -} - #[cfg(not(test))] impl Not for bool { /// The logical complement of a boolean value. diff --git a/src/libstd/char.rs b/src/libstd/char.rs index 1ec89d1850f..ed2a88e644b 100644 --- a/src/libstd/char.rs +++ b/src/libstd/char.rs @@ -15,8 +15,6 @@ use option::{None, Option, Some}; use iter::{Iterator, range_step}; use str::StrSlice; use unicode::{derived_property, property, general_category, decompose}; -use to_str::ToStr; -use str; #[cfg(test)] use str::OwnedStr; @@ -344,13 +342,6 @@ pub fn len_utf8_bytes(c: char) -> uint { } } -impl ToStr for char { - #[inline] - fn to_str(&self) -> ~str { - str::from_char(*self) - } -} - #[allow(missing_doc)] pub trait Char { fn is_alphabetic(&self) -> bool; @@ -556,6 +547,7 @@ fn test_escape_unicode() { #[test] fn test_to_str() { + use to_str::ToStr; let s = 't'.to_str(); assert_eq!(s, ~"t"); } diff --git a/src/libstd/fmt/mod.rs b/src/libstd/fmt/mod.rs index a55794b08fe..5c0838fadca 100644 --- a/src/libstd/fmt/mod.rs +++ b/src/libstd/fmt/mod.rs @@ -1055,6 +1055,16 @@ pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> { // Implementations of the core formatting traits +impl Show for @T { + fn fmt(&self, f: &mut Formatter) -> Result { secret_show(&**self, f) } +} +impl Show for ~T { + fn fmt(&self, f: &mut Formatter) -> Result { secret_show(&**self, f) } +} +impl<'a, T: Show> Show for &'a T { + fn fmt(&self, f: &mut Formatter) -> Result { secret_show(*self, f) } +} + impl Bool for bool { fn fmt(&self, f: &mut Formatter) -> Result { secret_string(&(if *self {"true"} else {"false"}), f) diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 91a8d599326..94d32d6d8f3 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -188,7 +188,6 @@ use path::Path; use result::{Ok, Err, Result}; use str::{StrSlice, OwnedStr}; use str; -use to_str::ToStr; use uint; use unstable::finally::try_finally; use vec::{OwnedVector, MutableVector, ImmutableVector, OwnedCloneableVector}; @@ -286,21 +285,7 @@ impl fmt::Show for IoError { } } -// FIXME: #8242 implementing manually because deriving doesn't work for some reason -impl ToStr for IoError { - fn to_str(&self) -> ~str { - let mut s = ~"IoError { kind: "; - s.push_str(self.kind.to_str()); - s.push_str(", desc: "); - s.push_str(self.desc); - s.push_str(", detail: "); - s.push_str(self.detail.to_str()); - s.push_str(" }"); - s - } -} - -#[deriving(Eq, Clone)] +#[deriving(Eq, Clone, Show)] pub enum IoErrorKind { OtherIoError, EndOfFile, @@ -321,31 +306,6 @@ pub enum IoErrorKind { InvalidInput, } -// FIXME: #8242 implementing manually because deriving doesn't work for some reason -impl ToStr for IoErrorKind { - fn to_str(&self) -> ~str { - match *self { - OtherIoError => ~"OtherIoError", - EndOfFile => ~"EndOfFile", - FileNotFound => ~"FileNotFound", - PermissionDenied => ~"PermissionDenied", - ConnectionFailed => ~"ConnectionFailed", - Closed => ~"Closed", - ConnectionRefused => ~"ConnectionRefused", - ConnectionReset => ~"ConnectionReset", - NotConnected => ~"NotConnected", - BrokenPipe => ~"BrokenPipe", - PathAlreadyExists => ~"PathAlreadyExists", - PathDoesntExist => ~"PathDoesntExist", - MismatchedFileTypeForOperation => ~"MismatchedFileTypeForOperation", - IoUnavailable => ~"IoUnavailable", - ResourceUnavailable => ~"ResourceUnavailable", - ConnectionAborted => ~"ConnectionAborted", - InvalidInput => ~"InvalidInput", - } - } -} - pub trait Reader { // Only method which need to get implemented for this trait diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index 13ea552ab3b..e4f36764323 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -9,11 +9,11 @@ // except according to those terms. use container::Container; +use fmt; use from_str::FromStr; use iter::Iterator; use option::{Option, None, Some}; use str::StrSlice; -use to_str::ToStr; use vec::{MutableCloneableVector, ImmutableVector, MutableVector}; pub type Port = u16; @@ -24,26 +24,27 @@ pub enum IpAddr { Ipv6Addr(u16, u16, u16, u16, u16, u16, u16, u16) } -impl ToStr for IpAddr { - fn to_str(&self) -> ~str { +impl fmt::Show for IpAddr { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Ipv4Addr(a, b, c, d) => - format!("{}.{}.{}.{}", a, b, c, d), + write!(fmt.buf, "{}.{}.{}.{}", a, b, c, d), // Ipv4 Compatible address Ipv6Addr(0, 0, 0, 0, 0, 0, g, h) => { - format!("::{}.{}.{}.{}", (g >> 8) as u8, g as u8, - (h >> 8) as u8, h as u8) + write!(fmt.buf, "::{}.{}.{}.{}", (g >> 8) as u8, g as u8, + (h >> 8) as u8, h as u8) } // Ipv4-Mapped address Ipv6Addr(0, 0, 0, 0, 0, 0xFFFF, g, h) => { - format!("::FFFF:{}.{}.{}.{}", (g >> 8) as u8, g as u8, - (h >> 8) as u8, h as u8) + write!(fmt.buf, "::FFFF:{}.{}.{}.{}", (g >> 8) as u8, g as u8, + (h >> 8) as u8, h as u8) } Ipv6Addr(a, b, c, d, e, f, g, h) => - format!("{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}", a, b, c, d, e, f, g, h) + write!(fmt.buf, "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}", + a, b, c, d, e, f, g, h) } } } @@ -55,11 +56,11 @@ pub struct SocketAddr { } -impl ToStr for SocketAddr { - fn to_str(&self) -> ~str { +impl fmt::Show for SocketAddr { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.ip { - Ipv4Addr(..) => format!("{}:{}", self.ip.to_str(), self.port), - Ipv6Addr(..) => format!("[{}]:{}", self.ip.to_str(), self.port), + Ipv4Addr(..) => write!(f.buf, "{}:{}", self.ip, self.port), + Ipv6Addr(..) => write!(f.buf, "[{}]:{}", self.ip, self.port), } } } diff --git a/src/libstd/num/f32.rs b/src/libstd/num/f32.rs index 7b1fe949199..a4eac564ee6 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/num/f32.rs @@ -19,7 +19,6 @@ use libc::{c_float, c_int}; use num::{FPCategory, FPNaN, FPInfinite , FPZero, FPSubnormal, FPNormal}; use num::{Zero, One, Bounded, strconv}; use num; -use to_str; use intrinsics; macro_rules! delegate( @@ -745,11 +744,6 @@ pub fn to_str_exp_digits(num: f32, dig: uint, upper: bool) -> ~str { r } -impl to_str::ToStr for f32 { - #[inline] - fn to_str(&self) -> ~str { to_str_digits(*self, 8) } -} - impl num::ToStrRadix for f32 { /// Converts a float to a string in a given radix /// diff --git a/src/libstd/num/f64.rs b/src/libstd/num/f64.rs index d5a571cdd23..e6b903cbbdb 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/num/f64.rs @@ -20,7 +20,6 @@ use libc::{c_double, c_int}; use num::{FPCategory, FPNaN, FPInfinite , FPZero, FPSubnormal, FPNormal}; use num::{Zero, One, Bounded, strconv}; use num; -use to_str; use intrinsics; pub use cmp::{min, max}; @@ -747,11 +746,6 @@ pub fn to_str_exp_digits(num: f64, dig: uint, upper: bool) -> ~str { r } -impl to_str::ToStr for f64 { - #[inline] - fn to_str(&self) -> ~str { to_str_digits(*self, 8) } -} - impl num::ToStrRadix for f64 { /// Converts a float to a string in a given radix /// diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs index 43a70190812..030aa2d81fa 100644 --- a/src/libstd/num/int_macros.rs +++ b/src/libstd/num/int_macros.rs @@ -273,14 +273,6 @@ pub fn to_str_bytes(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U { f(buf.slice(0, cur)) } -impl ToStr for $T { - /// Convert to a string in base 10. - #[inline] - fn to_str(&self) -> ~str { - format!("{:d}", *self) - } -} - impl ToStrRadix for $T { /// Convert to a string in a given base. #[inline] diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs index d60b5235446..001927e6033 100644 --- a/src/libstd/num/uint_macros.rs +++ b/src/libstd/num/uint_macros.rs @@ -187,14 +187,6 @@ pub fn to_str_bytes(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U { f(buf.slice(0, cur)) } -impl ToStr for $T { - /// Convert to a string in base 10. - #[inline] - fn to_str(&self) -> ~str { - format!("{:u}", *self) - } -} - impl ToStrRadix for $T { /// Convert to a string in a given base. #[inline] diff --git a/src/libstd/option.rs b/src/libstd/option.rs index 44d78be93d6..633d6e92c70 100644 --- a/src/libstd/option.rs +++ b/src/libstd/option.rs @@ -42,16 +42,13 @@ use clone::Clone; use clone::DeepClone; use cmp::{Eq, TotalEq, TotalOrd}; use default::Default; -use fmt; use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize}; use kinds::Send; use mem; -use str::OwnedStr; -use to_str::ToStr; use vec; /// The option type -#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, ToStr)] +#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, Show)] pub enum Option { /// No value None, @@ -380,16 +377,6 @@ impl Option { // Trait implementations ///////////////////////////////////////////////////////////////////////////// -impl fmt::Show for Option { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Some(ref t) => write!(f.buf, "Some({})", *t), - None => write!(f.buf, "None") - } - } -} - impl Default for Option { #[inline] fn default() -> Option { None } diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 13496033fd0..09124f63361 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -71,7 +71,6 @@ use iter::Iterator; use option::{Option, None, Some}; use str; use str::{MaybeOwned, OwnedStr, Str, StrSlice, from_utf8_lossy}; -use to_str::ToStr; use vec; use vec::{CloneableVector, OwnedCloneableVector, OwnedVector, Vector}; use vec::{ImmutableEqVector, ImmutableVector}; @@ -499,16 +498,6 @@ impl<'a, P: GenericPath> fmt::Show for Display<'a, P> { } } -impl<'a, P: GenericPath> ToStr for Display<'a, P> { - /// Returns the path as a string - /// - /// If the path is not UTF-8, invalid sequences with be replaced with the - /// unicode replacement char. This involves allocation. - fn to_str(&self) -> ~str { - self.as_maybe_owned().into_owned() - } -} - impl<'a, P: GenericPath> Display<'a, P> { /// Returns the path as a possibly-owned string. /// diff --git a/src/libstd/result.rs b/src/libstd/result.rs index 39e8b6ad6c1..3f09351ead6 100644 --- a/src/libstd/result.rs +++ b/src/libstd/result.rs @@ -12,14 +12,11 @@ use clone::Clone; use cmp::Eq; -use fmt; use iter::{Iterator, FromIterator}; use option::{None, Option, Some}; -use str::OwnedStr; -use to_str::ToStr; /// `Result` is a type that represents either success (`Ok`) or failure (`Err`). -#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, ToStr)] +#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, Show)] #[must_use] pub enum Result { /// Contains the success value @@ -202,20 +199,6 @@ impl Result { } } -///////////////////////////////////////////////////////////////////////////// -// Trait implementations -///////////////////////////////////////////////////////////////////////////// - -impl fmt::Show for Result { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Ok(ref t) => write!(f.buf, "Ok({})", *t), - Err(ref e) => write!(f.buf, "Err({})", *e) - } - } -} - ///////////////////////////////////////////////////////////////////////////// // Free functions ///////////////////////////////////////////////////////////////////////////// diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 3c094cd631d..daaf46be187 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -98,7 +98,6 @@ use num::Saturating; use option::{None, Option, Some}; use ptr; use ptr::RawPtr; -use to_str::ToStr; use from_str::FromStr; use vec; use vec::{OwnedVector, OwnedCloneableVector, ImmutableVector, MutableVector}; @@ -132,21 +131,11 @@ pub fn from_utf8<'a>(v: &'a [u8]) -> Option<&'a str> { } else { None } } -impl ToStr for ~str { - #[inline] - fn to_str(&self) -> ~str { self.to_owned() } -} - impl FromStr for ~str { #[inline] fn from_str(s: &str) -> Option<~str> { Some(s.to_owned()) } } -impl<'a> ToStr for &'a str { - #[inline] - fn to_str(&self) -> ~str { self.to_owned() } -} - /// Convert a byte to a UTF-8 string /// /// # Failure @@ -1269,11 +1258,6 @@ impl<'a> IntoMaybeOwned<'a> for MaybeOwned<'a> { fn into_maybe_owned(self) -> MaybeOwned<'a> { self } } -impl<'a> ToStr for MaybeOwned<'a> { - #[inline] - fn to_str(&self) -> ~str { self.as_slice().to_owned() } -} - impl<'a> Eq for MaybeOwned<'a> { #[inline] fn eq(&self, other: &MaybeOwned) -> bool { diff --git a/src/libstd/to_str.rs b/src/libstd/to_str.rs index 46a9e93f416..ba3c1c0fc45 100644 --- a/src/libstd/to_str.rs +++ b/src/libstd/to_str.rs @@ -14,10 +14,7 @@ The `ToStr` trait for converting to strings */ -use option::{Some, None}; -use str::OwnedStr; -use iter::Iterator; -use vec::ImmutableVector; +use fmt; /// A generic trait for converting a value to a string pub trait ToStr { @@ -31,47 +28,8 @@ pub trait IntoStr { fn into_str(self) -> ~str; } -impl ToStr for () { - #[inline] - fn to_str(&self) -> ~str { ~"()" } -} - -impl<'a,A:ToStr> ToStr for &'a [A] { - #[inline] - fn to_str(&self) -> ~str { - let mut acc = ~"["; - let mut first = true; - for elt in self.iter() { - if first { - first = false; - } - else { - acc.push_str(", "); - } - acc.push_str(elt.to_str()); - } - acc.push_char(']'); - acc - } -} - -impl ToStr for ~[A] { - #[inline] - fn to_str(&self) -> ~str { - let mut acc = ~"["; - let mut first = true; - for elt in self.iter() { - if first { - first = false; - } - else { - acc.push_str(", "); - } - acc.push_str(elt.to_str()); - } - acc.push_char(']'); - acc - } +impl ToStr for T { + fn to_str(&self) -> ~str { format!("{}", *self) } } #[cfg(test)] diff --git a/src/libstd/tuple.rs b/src/libstd/tuple.rs index b0d51cba103..9d50337efab 100644 --- a/src/libstd/tuple.rs +++ b/src/libstd/tuple.rs @@ -17,7 +17,6 @@ use clone::Clone; #[cfg(not(test))] use default::Default; use fmt; use result::{Ok, Err}; -use to_str::ToStr; // macro for implementing n-ary tuple functions and operations macro_rules! tuple_impls { @@ -119,12 +118,6 @@ macro_rules! tuple_impls { } } - impl<$($T: fmt::Show),+> ToStr for ($($T,)+) { - fn to_str(&self) -> ~str { - format!("{}", *self) - } - } - impl<$($T: fmt::Show),+> fmt::Show for ($($T,)+) { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write_tuple!(f.buf, $(self.$refN()),+) diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index 13725ef2473..faf24da74cc 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -9,6 +9,8 @@ // except according to those terms. use std::hash::{Hash, sip}; +use std::fmt; +use std::fmt::Show; #[deriving(Eq)] pub enum Os { OsWin32, OsMacos, OsLinux, OsAndroid, OsFreebsd, } @@ -271,20 +273,23 @@ impl Hash for Abi { } } -impl ToStr for Abi { - fn to_str(&self) -> ~str { - self.data().name.to_str() +impl fmt::Show for Abi { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.data().name.fmt(f) } } -impl ToStr for AbiSet { - fn to_str(&self) -> ~str { - let mut strs = ~[]; +impl fmt::Show for AbiSet { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if_ok!(write!(f.buf, "\"")); + let mut first = true; self.each(|abi| { - strs.push(abi.data().name); + if first { first = false; } + else { let _ = write!(f.buf, " "); } + let _ = write!(f.buf, "{}", abi.data().name); true }); - format!("\"{}\"", strs.connect(" ")) + write!(f.buf, "\"") } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 4e43592ec5c..7561d8cbbae 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -17,11 +17,12 @@ use opt_vec::OptVec; use parse::token::{InternedString, special_idents, str_to_ident}; use parse::token; +use std::fmt; +use std::fmt::Show; use std::cell::RefCell; use collections::HashMap; use std::option::Option; use std::rc::Rc; -use std::to_str::ToStr; use serialize::{Encodable, Decodable, Encoder, Decoder}; /// A pointer abstraction. FIXME(eddyb) #10676 use Rc in the future. @@ -39,7 +40,7 @@ pub fn P(value: T) -> P { // table) and a SyntaxContext to track renaming and // macro expansion per Flatt et al., "Macros // That Work Together" -#[deriving(Clone, Hash, ToStr, TotalEq, TotalOrd, Show)] +#[deriving(Clone, Hash, TotalEq, TotalOrd, Show)] pub struct Ident { name: Name, ctxt: SyntaxContext } impl Ident { @@ -182,7 +183,7 @@ pub type CrateNum = u32; pub type NodeId = u32; -#[deriving(Clone, TotalEq, TotalOrd, Eq, Encodable, Decodable, Hash, ToStr, Show)] +#[deriving(Clone, TotalEq, TotalOrd, Eq, Encodable, Decodable, Hash, Show)] pub struct DefId { krate: CrateNum, node: NodeId, @@ -277,7 +278,7 @@ pub enum Def { DefMethod(DefId /* method */, Option /* trait */), } -#[deriving(Clone, Eq, Hash, Encodable, Decodable, ToStr)] +#[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)] pub enum DefRegion { DefStaticRegion, DefEarlyBoundRegion(/* index */ uint, /* lifetime decl */ NodeId), @@ -398,12 +399,12 @@ pub enum Sigil { ManagedSigil } -impl ToStr for Sigil { - fn to_str(&self) -> ~str { +impl fmt::Show for Sigil { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - BorrowedSigil => ~"&", - OwnedSigil => ~"~", - ManagedSigil => ~"@" + BorrowedSigil => "&".fmt(f), + OwnedSigil => "~".fmt(f), + ManagedSigil => "@".fmt(f), } } } @@ -768,9 +769,9 @@ pub enum IntTy { TyI64, } -impl ToStr for IntTy { - fn to_str(&self) -> ~str { - ast_util::int_ty_to_str(*self) +impl fmt::Show for IntTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", ast_util::int_ty_to_str(*self)) } } @@ -783,9 +784,9 @@ pub enum UintTy { TyU64, } -impl ToStr for UintTy { - fn to_str(&self) -> ~str { - ast_util::uint_ty_to_str(*self) +impl fmt::Show for UintTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", ast_util::uint_ty_to_str(*self)) } } @@ -795,9 +796,9 @@ pub enum FloatTy { TyF64, } -impl ToStr for FloatTy { - fn to_str(&self) -> ~str { - ast_util::float_ty_to_str(*self) +impl fmt::Show for FloatTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", ast_util::float_ty_to_str(*self)) } } @@ -826,11 +827,11 @@ pub enum Onceness { Many } -impl ToStr for Onceness { - fn to_str(&self) -> ~str { +impl fmt::Show for Onceness { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Once => ~"once", - Many => ~"many" + Once => "once".fmt(f), + Many => "many".fmt(f), } } } @@ -939,12 +940,12 @@ pub enum Purity { ExternFn, // declared with "extern fn" } -impl ToStr for Purity { - fn to_str(&self) -> ~str { +impl fmt::Show for Purity { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ImpureFn => ~"impure", - UnsafeFn => ~"unsafe", - ExternFn => ~"extern" + ImpureFn => "impure".fmt(f), + UnsafeFn => "unsafe".fmt(f), + ExternFn => "extern".fmt(f), } } } diff --git a/src/libsyntax/ast_map.rs b/src/libsyntax/ast_map.rs index 26c4b07fc96..9194cfb0694 100644 --- a/src/libsyntax/ast_map.rs +++ b/src/libsyntax/ast_map.rs @@ -22,6 +22,7 @@ use std::logging; use std::cell::RefCell; use std::iter; use std::vec; +use std::fmt; #[deriving(Clone, Eq)] pub enum PathElem { @@ -37,9 +38,10 @@ impl PathElem { } } -impl ToStr for PathElem { - fn to_str(&self) -> ~str { - token::get_name(self.name()).get().to_str() +impl fmt::Show for PathElem { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let slot = token::get_name(self.name()); + write!(f.buf, "{}", slot.get()) } } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 93edb552bbe..27d1c6fa649 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -341,7 +341,7 @@ pub struct Stability { } /// The available stability levels. -#[deriving(Eq,Ord,Clone,ToStr)] +#[deriving(Eq,Ord,Clone,Show)] pub enum StabilityLevel { Deprecated, Experimental, diff --git a/src/libsyntax/crateid.rs b/src/libsyntax/crateid.rs index 0831f319ce7..d04bedc65b5 100644 --- a/src/libsyntax/crateid.rs +++ b/src/libsyntax/crateid.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::fmt; + /// CrateIds identify crates and include the crate name and optionally a path /// and version. In the full form, they look like relative URLs. Example: /// `github.com/mozilla/rust#std:1.0` would be a package ID with a path of @@ -26,16 +28,17 @@ pub struct CrateId { version: Option<~str>, } -impl ToStr for CrateId { - fn to_str(&self) -> ~str { +impl fmt::Show for CrateId { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if_ok!(write!(f.buf, "{}", self.path)); let version = match self.version { None => "0.0", Some(ref version) => version.as_slice(), }; if self.path == self.name || self.path.ends_with(format!("/{}", self.name)) { - format!("{}\\#{}", self.path, version) + write!(f.buf, "\\#{}", version) } else { - format!("{}\\#{}:{}", self.path, self.name, version) + write!(f.buf, "\\#{}:{}", self.name, version) } } } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 8cf0f128d22..be45008b92a 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -12,8 +12,9 @@ use codemap::{Pos, Span}; use codemap; use std::cell::Cell; -use std::io; +use std::fmt; use std::io::stdio::StdWriter; +use std::io; use std::iter::range; use std::local_data; use term; @@ -162,12 +163,14 @@ pub enum Level { Note, } -impl ToStr for Level { - fn to_str(&self) -> ~str { +impl fmt::Show for Level { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use std::fmt::Show; + match *self { - Fatal | Error => ~"error", - Warning => ~"warning", - Note => ~"note" + Fatal | Error => "error".fmt(f), + Warning => "warning".fmt(f), + Note => "note".fmt(f), } } } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index c9bdd49f86c..a81fc4f6d69 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -40,14 +40,14 @@ use term::Terminal; use term::color::{Color, RED, YELLOW, GREEN, CYAN}; use std::cmp; -use std::io; -use std::io::{File, PortReader, ChanWriter}; +use std::f64; +use std::fmt; use std::io::stdio::StdWriter; +use std::io::{File, PortReader, ChanWriter}; +use std::io; +use std::os; use std::str; use std::task; -use std::to_str::ToStr; -use std::f64; -use std::os; // to be used by rustc to compile tests in libtest pub mod test { @@ -70,11 +70,11 @@ pub enum TestName { StaticTestName(&'static str), DynTestName(~str) } -impl ToStr for TestName { - fn to_str(&self) -> ~str { - match (*self).clone() { - StaticTestName(s) => s.to_str(), - DynTestName(s) => s.to_str() +impl fmt::Show for TestName { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + StaticTestName(s) => f.buf.write_str(s), + DynTestName(ref s) => f.buf.write_str(s.as_slice()), } } } diff --git a/src/libuuid/lib.rs b/src/libuuid/lib.rs index dec27719beb..7a078e4b571 100644 --- a/src/libuuid/lib.rs +++ b/src/libuuid/lib.rs @@ -64,17 +64,15 @@ Examples of string representations: extern crate test; extern crate serialize; -use std::str; -use std::vec; -use std::num::FromStrRadix; -use std::char::Char; -use std::container::Container; -use std::to_str::ToStr; -use std::rand; -use std::rand::Rng; -use std::cmp::Eq; use std::cast::{transmute,transmute_copy}; +use std::cast::{transmute,transmute_copy}; +use std::char::Char; +use std::cmp::Eq; +use std::cmp::Eq; +use std::fmt; use std::hash::{Hash, sip}; +use std::num::FromStrRadix; +use std::rand::Rng; use serialize::{Encoder, Encodable, Decoder, Decodable}; @@ -142,22 +140,21 @@ pub enum ParseError { } /// Converts a ParseError to a string -impl ToStr for ParseError { - #[inline] - fn to_str(&self) -> ~str { +impl fmt::Show for ParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ErrorInvalidLength(found) => - format!("Invalid length; expecting 32, 36 or 45 chars, found {}", - found), + write!(f.buf, "Invalid length; expecting 32, 36 or 45 chars, \ + found {}", found), ErrorInvalidCharacter(found, pos) => - format!("Invalid character; found `{}` (0x{:02x}) at offset {}", - found, found as uint, pos), + write!(f.buf, "Invalid character; found `{}` (0x{:02x}) at \ + offset {}", found, found as uint, pos), ErrorInvalidGroups(found) => - format!("Malformed; wrong number of groups: expected 1 or 5, found {}", - found), + write!(f.buf, "Malformed; wrong number of groups: expected 1 \ + or 5, found {}", found), ErrorInvalidGroupLength(group, found, expecting) => - format!("Malformed; length of group {} was {}, expecting {}", - group, found, expecting), + write!(f.buf, "Malformed; length of group {} was {}, \ + expecting {}", group, found, expecting), } } } @@ -465,9 +462,9 @@ impl FromStr for Uuid { } /// Convert the UUID to a hexadecimal-based string representation -impl ToStr for Uuid { - fn to_str(&self) -> ~str { - self.to_simple_str() +impl fmt::Show for Uuid { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.to_simple_str()) } } diff --git a/src/test/auxiliary/cci_class_cast.rs b/src/test/auxiliary/cci_class_cast.rs index 8fac4a3f322..79bb5aef764 100644 --- a/src/test/auxiliary/cci_class_cast.rs +++ b/src/test/auxiliary/cci_class_cast.rs @@ -9,14 +9,18 @@ // except according to those terms. pub mod kitty { + use std::fmt; + pub struct cat { priv meows : uint, how_hungry : int, name : ~str, } - impl ToStr for cat { - fn to_str(&self) -> ~str { self.name.clone() } + impl fmt::Show for cat { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.name) + } } impl cat { diff --git a/src/test/compile-fail/use-after-move-implicity-coerced-object.rs b/src/test/compile-fail/use-after-move-implicity-coerced-object.rs index 537da535457..085ed5db6df 100644 --- a/src/test/compile-fail/use-after-move-implicity-coerced-object.rs +++ b/src/test/compile-fail/use-after-move-implicity-coerced-object.rs @@ -10,13 +10,15 @@ // ignore-tidy-linelength +use std::fmt; + struct Number { n: i64 } -impl ToStr for Number { - fn to_str(&self) -> ~str { - self.n.to_str() +impl fmt::Show for Number { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.n) } } diff --git a/src/test/run-pass/class-separate-impl.rs b/src/test/run-pass/class-separate-impl.rs index e813210f4f4..55fa783391a 100644 --- a/src/test/run-pass/class-separate-impl.rs +++ b/src/test/run-pass/class-separate-impl.rs @@ -9,6 +9,9 @@ // except according to those terms. // ignore-fast + +use std::fmt; + struct cat { meows : uint, @@ -50,9 +53,9 @@ fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { } } -impl ToStr for cat { - fn to_str(&self) -> ~str { - self.name.clone() +impl fmt::Show for cat { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.name) } } diff --git a/src/test/run-pass/deriving-global.rs b/src/test/run-pass/deriving-global.rs index ffca06dc628..cce3575178e 100644 --- a/src/test/run-pass/deriving-global.rs +++ b/src/test/run-pass/deriving-global.rs @@ -28,19 +28,19 @@ mod submod { // cause errors about unrecognised module `std` (or `extra`) #[deriving(Eq, Ord, TotalEq, TotalOrd, Clone, DeepClone, - ToStr, Rand, + Show, Rand, Encodable, Decodable)] enum A { A1(uint), A2(int) } #[deriving(Eq, Ord, TotalEq, TotalOrd, Clone, DeepClone, - ToStr, Rand, + Show, Rand, Encodable, Decodable)] struct B { x: uint, y: int } #[deriving(Eq, Ord, TotalEq, TotalOrd, Clone, DeepClone, - ToStr, Rand, + Show, Rand, Encodable, Decodable)] struct C(uint, int); diff --git a/src/test/run-pass/deriving-in-fn.rs b/src/test/run-pass/deriving-in-fn.rs index 7fb7d601b81..baa036ee039 100644 --- a/src/test/run-pass/deriving-in-fn.rs +++ b/src/test/run-pass/deriving-in-fn.rs @@ -9,11 +9,11 @@ // except according to those terms. pub fn main() { - #[deriving(ToStr)] + #[deriving(Show)] struct Foo { foo: int, } let f = Foo { foo: 10 }; - let _ = f.to_str(); + format!("{}", f); } diff --git a/src/test/run-pass/deriving-to-str.rs b/src/test/run-pass/deriving-show-2.rs similarity index 71% rename from src/test/run-pass/deriving-to-str.rs rename to src/test/run-pass/deriving-show-2.rs index d9f69bd4a49..a2451c39400 100644 --- a/src/test/run-pass/deriving-to-str.rs +++ b/src/test/run-pass/deriving-show-2.rs @@ -10,30 +10,34 @@ #[feature(struct_variant)]; -#[deriving(ToStr)] +use std::fmt; + +#[deriving(Show)] enum A {} -#[deriving(ToStr)] +#[deriving(Show)] enum B { B1, B2, B3 } -#[deriving(ToStr)] +#[deriving(Show)] enum C { C1(int), C2(B), C3(~str) } -#[deriving(ToStr)] +#[deriving(Show)] enum D { D1{ a: int } } -#[deriving(ToStr)] +#[deriving(Show)] struct E; -#[deriving(ToStr)] +#[deriving(Show)] struct F(int); -#[deriving(ToStr)] +#[deriving(Show)] struct G(int, int); -#[deriving(ToStr)] +#[deriving(Show)] struct H { a: int } -#[deriving(ToStr)] +#[deriving(Show)] struct I { a: int, b: int } -#[deriving(ToStr)] +#[deriving(Show)] struct J(Custom); struct Custom; -impl ToStr for Custom { - fn to_str(&self) -> ~str { ~"yay" } +impl fmt::Show for Custom { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "yay") + } } pub fn main() { @@ -41,11 +45,11 @@ pub fn main() { assert_eq!(B2.to_str(), ~"B2"); assert_eq!(C1(3).to_str(), ~"C1(3)"); assert_eq!(C2(B2).to_str(), ~"C2(B2)"); - assert_eq!(D1{ a: 2 }.to_str(), ~"D1{a: 2}"); + assert_eq!(D1{ a: 2 }.to_str(), ~"D1 { a: 2 }"); assert_eq!(E.to_str(), ~"E"); assert_eq!(F(3).to_str(), ~"F(3)"); assert_eq!(G(3, 4).to_str(), ~"G(3, 4)"); assert_eq!(G(3, 4).to_str(), ~"G(3, 4)"); - assert_eq!(I{ a: 2, b: 4 }.to_str(), ~"I{a: 2, b: 4}"); + assert_eq!(I{ a: 2, b: 4 }.to_str(), ~"I { a: 2, b: 4 }"); assert_eq!(J(Custom).to_str(), ~"J(yay)"); } diff --git a/src/test/run-pass/issue-2904.rs b/src/test/run-pass/issue-2904.rs index 2816609ef97..45f59fe9cd4 100644 --- a/src/test/run-pass/issue-2904.rs +++ b/src/test/run-pass/issue-2904.rs @@ -17,7 +17,7 @@ extern crate extra; use std::io; -use std::to_str; +use std::fmt; enum square { bot, @@ -30,9 +30,9 @@ enum square { empty } -impl to_str::ToStr for square { - fn to_str(&self) -> ~str { - match *self { +impl fmt::Show for square { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", match *self { bot => { ~"R" } wall => { ~"#" } rock => { ~"*" } @@ -41,7 +41,7 @@ impl to_str::ToStr for square { open_lift => { ~"O" } earth => { ~"." } empty => { ~" " } - } + }) } } diff --git a/src/test/run-pass/issue-3563-3.rs b/src/test/run-pass/issue-3563-3.rs index 8e5dd762c63..ae65c46ce71 100644 --- a/src/test/run-pass/issue-3563-3.rs +++ b/src/test/run-pass/issue-3563-3.rs @@ -22,6 +22,7 @@ extern crate extra; // already linked in. Using WriterUtil allows us to use the write_line method. use std::str; use std::vec; +use std::fmt; // Represents a position on a canvas. struct Point { @@ -94,13 +95,13 @@ impl AsciiArt { // Allows AsciiArt to be converted to a string using the libcore ToStr trait. // Note that the %s fmt! specifier will not call this automatically. -impl ToStr for AsciiArt { - fn to_str(&self) -> ~str { +impl fmt::Show for AsciiArt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Convert each line into a string. let lines = self.lines.map(|line| str::from_chars(*line)); // Concatenate the lines together using a new-line. - lines.connect("\n") + write!(f.buf, "{}", lines.connect("\n")) } } diff --git a/src/test/run-pass/new-impl-syntax.rs b/src/test/run-pass/new-impl-syntax.rs index 6def21a389a..30200d4cb18 100644 --- a/src/test/run-pass/new-impl-syntax.rs +++ b/src/test/run-pass/new-impl-syntax.rs @@ -8,14 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::fmt; + struct Thingy { x: int, y: int } -impl ToStr for Thingy { - fn to_str(&self) -> ~str { - format!("\\{ x: {}, y: {} \\}", self.x, self.y) +impl fmt::Show for Thingy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "\\{ x: {}, y: {} \\}", self.x, self.y) } } @@ -23,9 +25,9 @@ struct PolymorphicThingy { x: T } -impl ToStr for PolymorphicThingy { - fn to_str(&self) -> ~str { - self.x.to_str() +impl fmt::Show for PolymorphicThingy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.x) } }