]> git.proxmox.com Git - rustc.git/blob - src/test/run-pass/overloaded-deref-count.rs
Imported Upstream version 1.0.0~beta.3
[rustc.git] / src / test / run-pass / overloaded-deref-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
12 use std::cell::Cell;
13 use std::ops::{Deref, DerefMut};
14 use std::vec::Vec;
15
16 struct DerefCounter<T> {
17 count_imm: Cell<usize>,
18 count_mut: usize,
19 value: T
20 }
21
22 impl<T> DerefCounter<T> {
23 fn new(value: T) -> DerefCounter<T> {
24 DerefCounter {
25 count_imm: Cell::new(0),
26 count_mut: 0,
27 value: value
28 }
29 }
30
31 fn counts(&self) -> (usize, usize) {
32 (self.count_imm.get(), self.count_mut)
33 }
34 }
35
36 impl<T> Deref for DerefCounter<T> {
37 type Target = T;
38
39 fn deref(&self) -> &T {
40 self.count_imm.set(self.count_imm.get() + 1);
41 &self.value
42 }
43 }
44
45 impl<T> DerefMut for DerefCounter<T> {
46 fn deref_mut(&mut self) -> &mut T {
47 self.count_mut += 1;
48 &mut self.value
49 }
50 }
51
52 pub fn main() {
53 let mut n = DerefCounter::new(0);
54 let mut v = DerefCounter::new(Vec::new());
55
56 let _ = *n; // Immutable deref + copy a POD.
57 assert_eq!(n.counts(), (1, 0));
58
59 let _ = (&*n, &*v); // Immutable deref + borrow.
60 assert_eq!(n.counts(), (2, 0)); assert_eq!(v.counts(), (1, 0));
61
62 let _ = (&mut *n, &mut *v); // Mutable deref + mutable borrow.
63 assert_eq!(n.counts(), (2, 1)); assert_eq!(v.counts(), (1, 1));
64
65 let mut v2 = Vec::new();
66 v2.push(1);
67
68 *n = 5; *v = v2; // Mutable deref + assignment.
69 assert_eq!(n.counts(), (2, 2)); assert_eq!(v.counts(), (1, 2));
70
71 *n -= 3; // Mutable deref + assignment with binary operation.
72 assert_eq!(n.counts(), (2, 3));
73
74 // Immutable deref used for calling a method taking &self. (The
75 // typechecker is smarter now about doing this.)
76 (*n).to_string();
77 assert_eq!(n.counts(), (3, 3));
78
79 // Mutable deref used for calling a method taking &mut self.
80 (*v).push(2);
81 assert_eq!(v.counts(), (1, 3));
82
83 // Check the final states.
84 assert_eq!(*n, 2);
85 let expected: &[_] = &[1, 2];
86 assert_eq!((*v), expected);
87 }