]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/issue-15734.rs
daf14b4c2ffc4e0c33ba335c092ef7c3d869e4f7
[rust.git] / src / test / run-pass / issue-15734.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 // If `Index` used an associated type for its output, this test would
12 // work more smoothly.
13
14
15 #![feature(core)]
16
17 use std::ops::Index;
18
19 struct Mat<T> { data: Vec<T>, cols: usize, }
20
21 impl<T> Mat<T> {
22     fn new(data: Vec<T>, cols: usize) -> Mat<T> {
23         Mat { data: data, cols: cols }
24     }
25     fn row<'a>(&'a self, row: usize) -> Row<&'a Mat<T>> {
26         Row { mat: self, row: row, }
27     }
28 }
29
30 impl<T> Index<(usize, usize)> for Mat<T> {
31     type Output = T;
32
33     fn index<'a>(&'a self, (row, col): (usize, usize)) -> &'a T {
34         &self.data[row * self.cols + col]
35     }
36 }
37
38 impl<'a, T> Index<(usize, usize)> for &'a Mat<T> {
39     type Output = T;
40
41     fn index<'b>(&'b self, index: (usize, usize)) -> &'b T {
42         (*self).index(index)
43     }
44 }
45
46 struct Row<M> { mat: M, row: usize, }
47
48 impl<T, M: Index<(usize, usize), Output=T>> Index<usize> for Row<M> {
49     type Output = T;
50
51     fn index<'a>(&'a self, col: usize) -> &'a T {
52         &self.mat[(self.row, col)]
53     }
54 }
55
56 fn main() {
57     let m = Mat::new(vec![1, 2, 3, 4, 5, 6], 3);
58     let r = m.row(1);
59
60     assert_eq!(r.index(2), &6);
61     assert_eq!(r[2], 6);
62     assert_eq!(r[2], 6);
63     assert_eq!(6, r[2]);
64
65     let e = r[2];
66     assert_eq!(e, 6);
67
68     let e: usize = r[2];
69     assert_eq!(e, 6);
70 }