]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/trait-cast.rs
a9067ef87ba31ce5587fa1be8710347ccee181d8
[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 // ignore-pretty FIXME(#14193)
12
13 #![feature(managed_boxes)]
14
15 // Test cyclic detector when using trait instances.
16
17 use std::cell::RefCell;
18
19 struct Tree(@RefCell<TreeR>);
20 struct TreeR {
21     left: Option<Tree>,
22     right: Option<Tree>,
23     val: Box<to_str:Send>
24 }
25
26 trait to_str {
27     fn to_str_(&self) -> String;
28 }
29
30 impl<T:to_str> to_str for Option<T> {
31     fn to_str_(&self) -> String {
32         match *self {
33           None => { "none".to_string() }
34           Some(ref t) => format!("some({})", t.to_str_()),
35         }
36     }
37 }
38
39 impl to_str for int {
40     fn to_str_(&self) -> String {
41         self.to_str()
42     }
43 }
44
45 impl to_str for Tree {
46     fn to_str_(&self) -> String {
47         let Tree(t) = *self;
48         let this = t.borrow();
49         let (l, r) = (this.left, this.right);
50         let val = &this.val;
51         format!("[{}, {}, {}]", val.to_str_(), l.to_str_(), r.to_str_())
52     }
53 }
54
55 fn foo<T:to_str>(x: T) -> String { x.to_str_() }
56
57 pub fn main() {
58     let t1 = Tree(@RefCell::new(TreeR{left: None,
59                                       right: None,
60                                       val: box 1 as Box<to_str:Send>}));
61     let t2 = Tree(@RefCell::new(TreeR{left: Some(t1),
62                                       right: Some(t1),
63                                       val: box 2 as Box<to_str:Send>}));
64     let expected =
65         "[2, some([1, none, none]), some([1, none, none])]".to_string();
66     assert!(t2.to_str_() == expected);
67     assert!(foo(t2) == expected);
68
69     {
70         let Tree(t1_) = t1;
71         let mut t1 = t1_.borrow_mut();
72         t1.left = Some(t2); // create cycle
73     }
74 }