Remove all ToStr impls, add Show impls

This commit changes the ToStr trait to:

    impl<T: fmt::Show> 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
This commit is contained in:
Alex Crichton 2014-02-19 18:56:33 -08:00
parent 7cc6b5e0a3
commit b78b749810
55 changed files with 414 additions and 607 deletions

View File

@ -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 }
~~~

View File

@ -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<K, V> {
@ -106,11 +107,10 @@ impl<K: TotalOrd, V: TotalEq> TotalOrd for BTree<K, V> {
}
}
impl<K: ToStr + TotalOrd, V: ToStr> ToStr for BTree<K, V> {
impl<K: fmt::Show + TotalOrd, V: fmt::Show> fmt::Show for BTree<K, V> {
///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<K: TotalOrd, V: TotalEq> TotalOrd for Node<K, V> {
}
}
impl<K: ToStr + TotalOrd, V: ToStr> ToStr for Node<K, V> {
impl<K: fmt::Show + TotalOrd, V: fmt::Show> fmt::Show for Node<K, V> {
///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<K: TotalOrd, V: TotalEq> TotalOrd for Leaf<K, V> {
}
impl<K: ToStr + TotalOrd, V: ToStr> ToStr for Leaf<K, V> {
impl<K: fmt::Show + TotalOrd, V: fmt::Show> fmt::Show for Leaf<K, V> {
///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<K: TotalOrd, V: TotalEq> TotalOrd for Branch<K, V> {
}
}
impl<K: ToStr + TotalOrd, V: ToStr> ToStr for Branch<K, V> {
impl<K: fmt::Show + TotalOrd, V: fmt::Show> fmt::Show for Branch<K, V> {
///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<K: TotalOrd, V: TotalEq> TotalOrd for LeafElt<K, V> {
}
}
impl<K: ToStr + TotalOrd, V: ToStr> ToStr for LeafElt<K, V> {
impl<K: fmt::Show + TotalOrd, V: fmt::Show> fmt::Show for LeafElt<K, V> {
///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<K: TotalOrd, V: TotalEq> TotalOrd for BranchElt<K, V> {
}
}
impl<K: ToStr + TotalOrd, V: ToStr> ToStr for BranchElt<K, V> {
///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<K: fmt::Show + TotalOrd, V: fmt::Show> fmt::Show for BranchElt<K, V> {
/// 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)
}
}

View File

@ -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<E> {
// We must maintain the invariant that no bits are set

View File

@ -606,10 +606,6 @@ impl<A: fmt::Show + Hash + Eq, B: fmt::Show> fmt::Show for HashMap<A, B> {
}
}
impl<K: fmt::Show + Hash + Eq, V: fmt::Show> ToStr for HashMap<K, V> {
fn to_str(&self) -> ~str { format!("{}", *self) }
}
/// HashMap iterator
#[deriving(Clone)]
pub struct Entries<'a, K, V> {
@ -888,10 +884,6 @@ impl<A: fmt::Show + Hash + Eq> fmt::Show for HashSet<A> {
}
}
impl<A: fmt::Show + Hash + Eq> ToStr for HashSet<A> {
fn to_str(&self) -> ~str { format!("{}", *self) }
}
impl<K: Eq + Hash> FromIterator<K> for HashSet<K> {
fn from_iterator<T: Iterator<K>>(iter: &mut T) -> HashSet<K> {
let (lower, _) = iter.size_hint();

View File

@ -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<K: Hash + Eq, V> LruCache<K, V> {
}
}
impl<A: ToStr + Hash + Eq, B: ToStr> ToStr for LruCache<A, B> {
impl<A: fmt::Show + Hash + Eq, B: fmt::Show> fmt::Show for LruCache<A, B> {
/// 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"\}")
}
}

View File

@ -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<A:ToJson> ToJson for Option<A> {
}
}
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)
}
}

View File

@ -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(())
}
}
}

View File

@ -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),

View File

@ -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 {

View File

@ -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<T: Clone + Num> One for Cmplx<T> {
}
/* string conversions */
impl<T: ToStr + Num + Ord> ToStr for Cmplx<T> {
fn to_str(&self) -> ~str {
impl<T: fmt::Show + Num + Ord> fmt::Show for Cmplx<T> {
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)
}
}
}

View File

@ -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<T: Clone + Integer + Ord>
}
/* String conversions */
impl<T: ToStr> ToStr for Ratio<T> {
impl<T: fmt::Show> fmt::Show for Ratio<T> {
/// 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<T: ToStrRadix> ToStrRadix for Ratio<T> {

View File

@ -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())
}
}
// ______________________________________________________________________

View File

@ -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 {

View File

@ -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<Variance>
}
#[deriving(Clone, Eq, Decodable, Encodable)]
#[deriving(Clone, Eq, Decodable, Encodable, Show)]
pub enum Variance {
Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
Invariant, // T<A> <: T<B> 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<T> {
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<Purity>),
@ -826,7 +829,7 @@ pub struct ParamBounds {
pub type BuiltinBounds = EnumSet<BuiltinBound>;
#[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!("<generic \\#{}>", self.to_uint()) }
impl fmt::Show for TyVid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
write!(f.buf, "<generic \\#{}>", 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!("<generic integer \\#{}>", self.to_uint()) }
impl fmt::Show for IntVid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "<generic integer \\#{}>", 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!("<generic float \\#{}>", self.to_uint()) }
impl fmt::Show for FloatVid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "<generic float \\#{}>", 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<TypeContents,TypeContents> 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)
}
}

View File

@ -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 })
}
}
}

View File

@ -976,7 +976,7 @@ impl Clean<Item> for doctree::Static {
}
}
#[deriving(ToStr, Clone, Encodable, Decodable)]
#[deriving(Show, Clone, Encodable, Decodable)]
pub enum Mutability {
Mutable,
Immutable,

View File

@ -58,7 +58,7 @@ impl Module {
}
}
#[deriving(ToStr, Clone, Encodable, Decodable)]
#[deriving(Show, Clone, Encodable, Decodable)]
pub enum StructType {
/// A normal struct
Plain,

View File

@ -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())
}
}

View File

@ -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 {

View File

@ -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"),
}
}
}

View File

@ -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"),
}
}
}

View File

@ -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")

View File

@ -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)

View File

@ -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<bool> for bool {
/// The logical complement of a boolean value.

View File

@ -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");
}

View File

@ -1055,6 +1055,16 @@ pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
// Implementations of the core formatting traits
impl<T: Show> Show for @T {
fn fmt(&self, f: &mut Formatter) -> Result { secret_show(&**self, f) }
}
impl<T: Show> 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)

View File

@ -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

View File

@ -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),
}
}
}

View File

@ -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
///

View File

@ -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
///

View File

@ -273,14 +273,6 @@ pub fn to_str_bytes<U>(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]

View File

@ -187,14 +187,6 @@ pub fn to_str_bytes<U>(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]

View File

@ -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<T> {
/// No value
None,
@ -380,16 +377,6 @@ impl<T: Default> Option<T> {
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
impl<T: fmt::Show> fmt::Show for Option<T> {
#[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<T> Default for Option<T> {
#[inline]
fn default() -> Option<T> { None }

View File

@ -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.
///

View File

@ -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<T, E> {
/// Contains the success value
@ -202,20 +199,6 @@ impl<T, E> Result<T, E> {
}
}
/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
impl<T: fmt::Show, E: fmt::Show> fmt::Show for Result<T, E> {
#[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
/////////////////////////////////////////////////////////////////////////////

View File

@ -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 {

View File

@ -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<A:ToStr> 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<T: fmt::Show> ToStr for T {
fn to_str(&self) -> ~str { format!("{}", *self) }
}
#[cfg(test)]

View File

@ -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()),+)

View File

@ -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, "\"")
}
}

View File

@ -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<T> in the future.
@ -39,7 +40,7 @@ pub fn P<T: 'static>(value: T) -> P<T> {
// 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<DefId> /* 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),
}
}
}

View File

@ -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())
}
}

View File

@ -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,

View File

@ -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)
}
}
}

View File

@ -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),
}
}
}

View File

@ -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()),
}
}
}

View File

@ -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())
}
}

View File

@ -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 {

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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);

View File

@ -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);
}

View File

@ -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)");
}

View File

@ -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 => { ~" " }
}
})
}
}

View File

@ -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"))
}
}

View File

@ -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<T> {
x: T
}
impl<T:ToStr> ToStr for PolymorphicThingy<T> {
fn to_str(&self) -> ~str {
self.x.to_str()
impl<T:fmt::Show> fmt::Show for PolymorphicThingy<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "{}", self.x)
}
}