|
| 1 | +iface to_str { fn to_str() -> str; } |
| 2 | + |
| 3 | +impl of to_str for int { |
| 4 | + fn to_str() -> str { int::str(self) } |
| 5 | +} |
| 6 | +impl of to_str for uint { |
| 7 | + fn to_str() -> str { uint::str(self) } |
| 8 | +} |
| 9 | +impl of to_str for u8 { |
| 10 | + fn to_str() -> str { uint::str(self as uint) } |
| 11 | +} |
| 12 | +impl of to_str for float { |
| 13 | + fn to_str() -> str { float::to_str(self, 4u) } |
| 14 | +} |
| 15 | +impl of to_str for bool { |
| 16 | + fn to_str() -> str { bool::to_str(self) } |
| 17 | +} |
| 18 | +impl of to_str for () { |
| 19 | + fn to_str() -> str { "()" } |
| 20 | +} |
| 21 | +impl of to_str for str { |
| 22 | + fn to_str() -> str { self } |
| 23 | +} |
| 24 | + |
| 25 | +impl <A: to_str copy, B: to_str copy> of to_str for (A, B) { |
| 26 | + fn to_str() -> str { |
| 27 | + let (a, b) = self; |
| 28 | + "(" + a.to_str() + ", " + b.to_str() + ")" |
| 29 | + } |
| 30 | +} |
| 31 | +impl <A: to_str copy, B: to_str copy, C: to_str copy> of to_str for (A, B, C){ |
| 32 | + fn to_str() -> str { |
| 33 | + let (a, b, c) = self; |
| 34 | + "(" + a.to_str() + ", " + b.to_str() + ", " + c.to_str() + ")" |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +impl <A: to_str> of to_str for [A] { |
| 39 | + fn to_str() -> str { |
| 40 | + let acc = "[", first = true; |
| 41 | + for elt in self { |
| 42 | + if first { first = false; } |
| 43 | + else { acc += ", "; } |
| 44 | + acc += elt.to_str(); |
| 45 | + } |
| 46 | + acc += "]"; |
| 47 | + acc |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl <A: to_str> of to_str for @A { |
| 52 | + fn to_str() -> str { "@" + (*self).to_str() } |
| 53 | +} |
| 54 | +impl <A: to_str> of to_str for ~A { |
| 55 | + fn to_str() -> str { "~" + (*self).to_str() } |
| 56 | +} |
| 57 | + |
| 58 | +#[cfg(test)] |
| 59 | +mod tests { |
| 60 | + #[test] |
| 61 | + fn test_simple_types() { |
| 62 | + assert 1.to_str() == "1"; |
| 63 | + assert (-1).to_str() == "-1"; |
| 64 | + assert 200u.to_str() == "200"; |
| 65 | + assert 2u8.to_str() == "2"; |
| 66 | + assert true.to_str() == "true"; |
| 67 | + assert false.to_str() == "false"; |
| 68 | + assert ().to_str() == "()"; |
| 69 | + assert "hi".to_str() == "hi"; |
| 70 | + } |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn test_tuple_types() { |
| 74 | + assert (1, 2).to_str() == "(1, 2)"; |
| 75 | + assert ("a", "b", false).to_str() == "(a, b, false)"; |
| 76 | + assert ((), ((), 100)).to_str() == "((), ((), 100))"; |
| 77 | + } |
| 78 | + |
| 79 | + fn test_vectors() { |
| 80 | + let x: [int] = []; |
| 81 | + assert x.to_str() == "[]"; |
| 82 | + assert [1].to_str() == "[1]"; |
| 83 | + assert [1, 2, 3].to_str() == "[1, 2, 3]"; |
| 84 | + assert [[], [1], [1, 1]].to_str() == "[[], [1], [1, 1]]"; |
| 85 | + } |
| 86 | + |
| 87 | + fn test_pointer_types() { |
| 88 | + assert (@1).to_str() == "@1"; |
| 89 | + assert (~(true, false)).to_str() == "~(true, false)"; |
| 90 | + } |
| 91 | +} |
0 commit comments