4 use std::ops::{Deref, DerefMut};
7 struct DerefCounter<T> {
8 count_imm: Cell<usize>,
13 impl<T> DerefCounter<T> {
14 fn new(value: T) -> DerefCounter<T> {
16 count_imm: Cell::new(0),
22 fn counts(&self) -> (usize, usize) {
23 (self.count_imm.get(), self.count_mut)
27 impl<T> Deref for DerefCounter<T> {
30 fn deref(&self) -> &T {
31 self.count_imm.set(self.count_imm.get() + 1);
36 impl<T> DerefMut for DerefCounter<T> {
37 fn deref_mut(&mut self) -> &mut T {
44 let mut n = DerefCounter::new(0);
45 let mut v = DerefCounter::new(Vec::new());
47 let _ = *n; // Immutable deref + copy a POD.
48 assert_eq!(n.counts(), (1, 0));
50 let _ = (&*n, &*v); // Immutable deref + borrow.
51 assert_eq!(n.counts(), (2, 0)); assert_eq!(v.counts(), (1, 0));
53 let _ = (&mut *n, &mut *v); // Mutable deref + mutable borrow.
54 assert_eq!(n.counts(), (2, 1)); assert_eq!(v.counts(), (1, 1));
56 let mut v2 = Vec::new();
59 *n = 5; *v = v2; // Mutable deref + assignment.
60 assert_eq!(n.counts(), (2, 2)); assert_eq!(v.counts(), (1, 2));
62 *n -= 3; // Mutable deref + assignment with binary operation.
63 assert_eq!(n.counts(), (2, 3));
65 // Immutable deref used for calling a method taking &self. (The
66 // typechecker is smarter now about doing this.)
68 assert_eq!(n.counts(), (3, 3));
70 // Mutable deref used for calling a method taking &mut self.
72 assert_eq!(v.counts(), (1, 3));
74 // Check the final states.
76 let expected: &[_] = &[1, 2];
77 assert_eq!((*v), expected);