2018-08-30 07:18:55 -05:00
|
|
|
// run-pass
|
2014-03-11 15:27:55 -05:00
|
|
|
use std::cell::Cell;
|
|
|
|
use std::ops::{Deref, DerefMut};
|
|
|
|
|
2014-12-30 22:32:49 -06:00
|
|
|
#[derive(PartialEq)]
|
2014-03-11 15:27:55 -05:00
|
|
|
struct DerefCounter<T> {
|
2015-03-25 19:06:52 -05:00
|
|
|
count_imm: Cell<usize>,
|
|
|
|
count_mut: usize,
|
2014-03-11 15:27:55 -05:00
|
|
|
value: T
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> DerefCounter<T> {
|
|
|
|
fn new(value: T) -> DerefCounter<T> {
|
|
|
|
DerefCounter {
|
|
|
|
count_imm: Cell::new(0),
|
|
|
|
count_mut: 0,
|
|
|
|
value: value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-25 19:06:52 -05:00
|
|
|
fn counts(&self) -> (usize, usize) {
|
2014-03-11 15:27:55 -05:00
|
|
|
(self.count_imm.get(), self.count_mut)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-01 13:53:20 -06:00
|
|
|
impl<T> Deref for DerefCounter<T> {
|
|
|
|
type Target = T;
|
|
|
|
|
2014-07-17 23:44:59 -05:00
|
|
|
fn deref(&self) -> &T {
|
2014-03-11 15:27:55 -05:00
|
|
|
self.count_imm.set(self.count_imm.get() + 1);
|
|
|
|
&self.value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-01 13:53:20 -06:00
|
|
|
impl<T> DerefMut for DerefCounter<T> {
|
2014-07-17 23:44:59 -05:00
|
|
|
fn deref_mut(&mut self) -> &mut T {
|
2014-03-11 15:27:55 -05:00
|
|
|
self.count_mut += 1;
|
|
|
|
&mut self.value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-28 07:34:18 -06:00
|
|
|
#[derive(PartialEq, Debug)]
|
2014-03-11 15:27:55 -05:00
|
|
|
struct Point {
|
2015-03-25 19:06:52 -05:00
|
|
|
x: isize,
|
|
|
|
y: isize
|
2014-03-11 15:27:55 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Point {
|
2015-03-25 19:06:52 -05:00
|
|
|
fn get(&self) -> (isize, isize) {
|
2014-03-11 15:27:55 -05:00
|
|
|
(self.x, self.y)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn main() {
|
|
|
|
let mut p = DerefCounter::new(Point {x: 0, y: 0});
|
|
|
|
|
|
|
|
let _ = p.x;
|
|
|
|
assert_eq!(p.counts(), (1, 0));
|
|
|
|
|
|
|
|
let _ = &p.x;
|
|
|
|
assert_eq!(p.counts(), (2, 0));
|
|
|
|
|
|
|
|
let _ = &mut p.y;
|
|
|
|
assert_eq!(p.counts(), (2, 1));
|
|
|
|
|
|
|
|
p.x += 3;
|
|
|
|
assert_eq!(p.counts(), (2, 2));
|
|
|
|
|
|
|
|
p.get();
|
2014-09-23 18:07:21 -05:00
|
|
|
assert_eq!(p.counts(), (3, 2));
|
2014-03-11 15:27:55 -05:00
|
|
|
|
|
|
|
// Check the final state.
|
|
|
|
assert_eq!(*p, Point {x: 3, y: 0});
|
|
|
|
}
|