]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
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 | ||
c34b1796 AL |
14 | |
15 | #![feature(core)] | |
1a4d82fc JJ |
16 | |
17 | use std::ops::Index; | |
18 | ||
c34b1796 | 19 | struct Mat<T> { data: Vec<T>, cols: usize, } |
1a4d82fc JJ |
20 | |
21 | impl<T> Mat<T> { | |
c34b1796 | 22 | fn new(data: Vec<T>, cols: usize) -> Mat<T> { |
1a4d82fc JJ |
23 | Mat { data: data, cols: cols } |
24 | } | |
c34b1796 | 25 | fn row<'a>(&'a self, row: usize) -> Row<&'a Mat<T>> { |
1a4d82fc JJ |
26 | Row { mat: self, row: row, } |
27 | } | |
28 | } | |
29 | ||
c34b1796 | 30 | impl<T> Index<(usize, usize)> for Mat<T> { |
1a4d82fc JJ |
31 | type Output = T; |
32 | ||
c34b1796 | 33 | fn index<'a>(&'a self, (row, col): (usize, usize)) -> &'a T { |
1a4d82fc JJ |
34 | &self.data[row * self.cols + col] |
35 | } | |
36 | } | |
37 | ||
c34b1796 | 38 | impl<'a, T> Index<(usize, usize)> for &'a Mat<T> { |
1a4d82fc JJ |
39 | type Output = T; |
40 | ||
c34b1796 | 41 | fn index<'b>(&'b self, index: (usize, usize)) -> &'b T { |
1a4d82fc JJ |
42 | (*self).index(index) |
43 | } | |
44 | } | |
45 | ||
c34b1796 | 46 | struct Row<M> { mat: M, row: usize, } |
1a4d82fc | 47 | |
c34b1796 | 48 | impl<T, M: Index<(usize, usize), Output=T>> Index<usize> for Row<M> { |
1a4d82fc JJ |
49 | type Output = T; |
50 | ||
c34b1796 AL |
51 | fn index<'a>(&'a self, col: usize) -> &'a T { |
52 | &self.mat[(self.row, col)] | |
1a4d82fc JJ |
53 | } |
54 | } | |
55 | ||
56 | fn main() { | |
c34b1796 | 57 | let m = Mat::new(vec!(1, 2, 3, 4, 5, 6), 3); |
1a4d82fc JJ |
58 | let r = m.row(1); |
59 | ||
c34b1796 AL |
60 | assert!(r.index(2) == &6); |
61 | assert!(r[2] == 6); | |
1a4d82fc | 62 | assert!(r[2] == 6); |
1a4d82fc JJ |
63 | assert!(6 == r[2]); |
64 | ||
65 | let e = r[2]; | |
66 | assert!(e == 6); | |
67 | ||
c34b1796 | 68 | let e: usize = r[2]; |
1a4d82fc JJ |
69 | assert!(e == 6); |
70 | } |