]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/trait-cast.rs
test: Remove all uses of `~str` from the test suite.
[rust.git] / src / test / run-pass / trait-cast.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![feature(managed_boxes)]
12
13 // Test cyclic detector when using trait instances.
14
15 use std::cell::RefCell;
16
17 struct Tree(@RefCell<TreeR>);
18 struct TreeR {
19     left: Option<Tree>,
20     right: Option<Tree>,
21     val: Box<to_str:Send>
22 }
23
24 trait to_str {
25     fn to_str_(&self) -> StrBuf;
26 }
27
28 impl<T:to_str> to_str for Option<T> {
29     fn to_str_(&self) -> StrBuf {
30         match *self {
31           None => { "none".to_strbuf() }
32           Some(ref t) => format_strbuf!("some({})", t.to_str_()),
33         }
34     }
35 }
36
37 impl to_str for int {
38     fn to_str_(&self) -> StrBuf {
39         self.to_str().to_strbuf()
40     }
41 }
42
43 impl to_str for Tree {
44     fn to_str_(&self) -> StrBuf {
45         let Tree(t) = *self;
46         let this = t.borrow();
47         let (l, r) = (this.left, this.right);
48         let val = &this.val;
49         format_strbuf!("[{}, {}, {}]",
50                        val.to_str_(),
51                        l.to_str_(),
52                        r.to_str_())
53     }
54 }
55
56 fn foo<T:to_str>(x: T) -> StrBuf { x.to_str_() }
57
58 pub fn main() {
59     let t1 = Tree(@RefCell::new(TreeR{left: None,
60                                       right: None,
61                                       val: box 1 as Box<to_str:Send>}));
62     let t2 = Tree(@RefCell::new(TreeR{left: Some(t1),
63                                       right: Some(t1),
64                                       val: box 2 as Box<to_str:Send>}));
65     let expected =
66         "[2, some([1, none, none]), some([1, none, none])]".to_strbuf();
67     assert!(t2.to_str_() == expected);
68     assert!(foo(t2) == expected);
69
70     {
71         let Tree(t1_) = t1;
72         let mut t1 = t1_.borrow_mut();
73         t1.left = Some(t2); // create cycle
74     }
75 }