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.
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.
12 use std::ops::{Deref, DerefMut};
14 #[deriving(PartialEq)]
15 struct DerefCounter<T> {
16 count_imm: Cell<uint>,
21 impl<T> DerefCounter<T> {
22 fn new(value: T) -> DerefCounter<T> {
24 count_imm: Cell::new(0),
30 fn counts(&self) -> (uint, uint) {
31 (self.count_imm.get(), self.count_mut)
35 impl<T> Deref<T> for DerefCounter<T> {
36 fn deref(&self) -> &T {
37 self.count_imm.set(self.count_imm.get() + 1);
42 impl<T> DerefMut<T> for DerefCounter<T> {
43 fn deref_mut(&mut self) -> &mut T {
49 #[deriving(PartialEq, Show)]
56 fn get(&self) -> (int, int) {
62 let mut p = DerefCounter::new(Point {x: 0, y: 0});
65 assert_eq!(p.counts(), (1, 0));
68 assert_eq!(p.counts(), (2, 0));
71 assert_eq!(p.counts(), (2, 1));
74 assert_eq!(p.counts(), (2, 2));
77 assert_eq!(p.counts(), (2, 3));
79 // Check the final state.
80 assert_eq!(*p, Point {x: 3, y: 0});