]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/overloaded-deref.rs
auto merge of #13600 : brandonw/rust/master, r=brson
[rust.git] / src / test / run-pass / overloaded-deref.rs
1 // Copyright 2014 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 use std::cell::RefCell;
12 use std::rc::Rc;
13 use std::strbuf::StrBuf;
14
15 #[deriving(Eq, Show)]
16 struct Point {
17     x: int,
18     y: int
19 }
20
21 pub fn main() {
22     assert_eq!(*Rc::new(5), 5);
23     assert_eq!(***Rc::new(~~5), 5);
24     assert_eq!(*Rc::new(Point {x: 2, y: 4}), Point {x: 2, y: 4});
25
26     let i = Rc::new(RefCell::new(2));
27     let i_value = *(*i).borrow();
28     *(*i).borrow_mut() = 5;
29     assert_eq!((i_value, *(*i).borrow()), (2, 5));
30
31     let s = Rc::new(~"foo");
32     assert_eq!(*s, ~"foo");
33     assert_eq!((*s).as_slice(), "foo");
34
35     let mut_s = Rc::new(RefCell::new(StrBuf::from_str("foo")));
36     (*(*mut_s).borrow_mut()).push_str("bar");
37     // assert_eq! would fail here because it stores the LHS and RHS in two locals.
38     assert!((*(*mut_s).borrow()).as_slice() == "foobar");
39     assert!((*(*mut_s).borrow_mut()).as_slice() == "foobar");
40
41     let p = Rc::new(RefCell::new(Point {x: 1, y: 2}));
42     (*(*p).borrow_mut()).x = 3;
43     (*(*p).borrow_mut()).y += 3;
44     assert_eq!(*(*p).borrow(), Point {x: 3, y: 5});
45
46     let v = Rc::new(RefCell::new(vec!(1, 2, 3)));
47     *(*(*v).borrow_mut()).get_mut(0) = 3;
48     *(*(*v).borrow_mut()).get_mut(1) += 3;
49     assert_eq!((*(*(*v).borrow()).get(0),
50                 *(*(*v).borrow()).get(1),
51                 *(*(*v).borrow()).get(2)), (3, 5, 3));
52 }