]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/overloaded-autoderef-count.rs
auto merge of #17654 : gereeter/rust/no-unnecessary-cell, r=alexcrichton
[rust.git] / src / test / run-pass / overloaded-autoderef-count.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::Cell;
12 use std::ops::{Deref, DerefMut};
13
14 #[deriving(PartialEq)]
15 struct DerefCounter<T> {
16     count_imm: Cell<uint>,
17     count_mut: uint,
18     value: T
19 }
20
21 impl<T> DerefCounter<T> {
22     fn new(value: T) -> DerefCounter<T> {
23         DerefCounter {
24             count_imm: Cell::new(0),
25             count_mut: 0,
26             value: value
27         }
28     }
29
30     fn counts(&self) -> (uint, uint) {
31         (self.count_imm.get(), self.count_mut)
32     }
33 }
34
35 impl<T> Deref<T> for DerefCounter<T> {
36     fn deref(&self) -> &T {
37         self.count_imm.set(self.count_imm.get() + 1);
38         &self.value
39     }
40 }
41
42 impl<T> DerefMut<T> for DerefCounter<T> {
43     fn deref_mut(&mut self) -> &mut T {
44         self.count_mut += 1;
45         &mut self.value
46     }
47 }
48
49 #[deriving(PartialEq, Show)]
50 struct Point {
51     x: int,
52     y: int
53 }
54
55 impl Point {
56     fn get(&self) -> (int, int) {
57         (self.x, self.y)
58     }
59 }
60
61 pub fn main() {
62     let mut p = DerefCounter::new(Point {x: 0, y: 0});
63
64     let _ = p.x;
65     assert_eq!(p.counts(), (1, 0));
66
67     let _ = &p.x;
68     assert_eq!(p.counts(), (2, 0));
69
70     let _ = &mut p.y;
71     assert_eq!(p.counts(), (2, 1));
72
73     p.x += 3;
74     assert_eq!(p.counts(), (2, 2));
75
76     p.get();
77     assert_eq!(p.counts(), (3, 2));
78
79     // Check the final state.
80     assert_eq!(*p, Point {x: 3, y: 0});
81 }