]>
git.proxmox.com Git - rustc.git/blob - 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.
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.
13 use std
::ops
::{Deref, DerefMut}
;
16 struct DerefCounter
<T
> {
17 count_imm
: Cell
<usize>,
22 impl<T
> DerefCounter
<T
> {
23 fn new(value
: T
) -> DerefCounter
<T
> {
25 count_imm
: Cell
::new(0),
31 fn counts(&self) -> (usize, usize) {
32 (self.count_imm
.get(), self.count_mut
)
36 impl<T
> Deref
for DerefCounter
<T
> {
39 fn deref(&self) -> &T
{
40 self.count_imm
.set(self.count_imm
.get() + 1);
45 impl<T
> DerefMut
for DerefCounter
<T
> {
46 fn deref_mut(&mut self) -> &mut T
{
53 let mut n
= DerefCounter
::new(0);
54 let mut v
= DerefCounter
::new(Vec
::new());
56 let _
= *n
; // Immutable deref + copy a POD.
57 assert_eq
!(n
.counts(), (1, 0));
59 let _
= (&*n
, &*v
); // Immutable deref + borrow.
60 assert_eq
!(n
.counts(), (2, 0)); assert_eq
!(v
.counts(), (1, 0));
62 let _
= (&mut *n
, &mut *v
); // Mutable deref + mutable borrow.
63 assert_eq
!(n
.counts(), (2, 1)); assert_eq
!(v
.counts(), (1, 1));
65 let mut v2
= Vec
::new();
68 *n
= 5; *v
= v2
; // Mutable deref + assignment.
69 assert_eq
!(n
.counts(), (2, 2)); assert_eq
!(v
.counts(), (1, 2));
71 *n
-= 3; // Mutable deref + assignment with binary operation.
72 assert_eq
!(n
.counts(), (2, 3));
74 // Immutable deref used for calling a method taking &self. (The
75 // typechecker is smarter now about doing this.)
77 assert_eq
!(n
.counts(), (3, 3));
79 // Mutable deref used for calling a method taking &mut self.
81 assert_eq
!(v
.counts(), (1, 3));
83 // Check the final states.
85 let expected
: &[_
] = &[1, 2];
86 assert_eq
!((*v
), expected
);