]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/overloaded-index-autoderef.rs
rollup merge of #20568: huonw/ungate-AT-globs
[rust.git] / src / test / run-pass / overloaded-index-autoderef.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 // Test overloaded indexing combined with autoderef.
12
13 use std::ops::{Index, IndexMut};
14
15 struct Foo {
16     x: int,
17     y: int,
18 }
19
20 impl Index<int> for Foo {
21     type Output = int;
22
23     fn index(&self, z: &int) -> &int {
24         if *z == 0 {
25             &self.x
26         } else {
27             &self.y
28         }
29     }
30 }
31
32 impl IndexMut<int> for Foo {
33     type Output = int;
34
35     fn index_mut(&mut self, z: &int) -> &mut int {
36         if *z == 0 {
37             &mut self.x
38         } else {
39             &mut self.y
40         }
41     }
42 }
43
44 trait Int {
45     fn get(self) -> int;
46     fn get_from_ref(&self) -> int;
47     fn inc(&mut self);
48 }
49
50 impl Int for int {
51     fn get(self) -> int { self }
52     fn get_from_ref(&self) -> int { *self }
53     fn inc(&mut self) { *self += 1; }
54 }
55
56 fn main() {
57     let mut f = box Foo {
58         x: 1,
59         y: 2,
60     };
61
62     assert_eq!(f[1], 2);
63
64     f[0] = 3;
65
66     assert_eq!(f[0], 3);
67
68     // Test explicit IndexMut where `f` must be autoderef:
69     {
70         let p = &mut f[1];
71         *p = 4;
72     }
73
74     // Test explicit Index where `f` must be autoderef:
75     {
76         let p = &f[1];
77         assert_eq!(*p, 4);
78     }
79
80     // Test calling methods with `&mut self`, `self, and `&self` receivers:
81     f[1].inc();
82     assert_eq!(f[1].get(), 5);
83     assert_eq!(f[1].get_from_ref(), 5);
84 }