]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/operator-overloading.rs
Auto merge of #28816 - petrochenkov:unistruct, r=nrc
[rust.git] / src / test / run-pass / operator-overloading.rs
1 // Copyright 2012-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 #![feature(core)]
12
13 use std::cmp;
14 use std::ops;
15
16 #[derive(Copy, Clone, Debug)]
17 struct Point {
18     x: isize,
19     y: isize
20 }
21
22 impl ops::Add for Point {
23     type Output = Point;
24
25     fn add(self, other: Point) -> Point {
26         Point {x: self.x + other.x, y: self.y + other.y}
27     }
28 }
29
30 impl ops::Sub for Point {
31     type Output = Point;
32
33     fn sub(self, other: Point) -> Point {
34         Point {x: self.x - other.x, y: self.y - other.y}
35     }
36 }
37
38 impl ops::Neg for Point {
39     type Output = Point;
40
41     fn neg(self) -> Point {
42         Point {x: -self.x, y: -self.y}
43     }
44 }
45
46 impl ops::Not for Point {
47     type Output = Point;
48
49     fn not(self) -> Point {
50         Point {x: !self.x, y: !self.y }
51     }
52 }
53
54 impl ops::Index<bool> for Point {
55     type Output = isize;
56
57     fn index(&self, x: bool) -> &isize {
58         if x {
59             &self.x
60         } else {
61             &self.y
62         }
63     }
64 }
65
66 impl cmp::PartialEq for Point {
67     fn eq(&self, other: &Point) -> bool {
68         (*self).x == (*other).x && (*self).y == (*other).y
69     }
70     fn ne(&self, other: &Point) -> bool { !(*self).eq(other) }
71 }
72
73 pub fn main() {
74     let mut p = Point {x: 10, y: 20};
75     p = p + Point {x: 101, y: 102};
76     p = p - Point {x: 100, y: 100};
77     assert_eq!(p + Point {x: 5, y: 5}, Point {x: 16, y: 27});
78     assert_eq!(-p, Point {x: -11, y: -22});
79     assert_eq!(p[true], 11);
80     assert_eq!(p[false], 22);
81
82     let q = !p;
83     assert_eq!(q.x, !(p.x));
84     assert_eq!(q.y, !(p.y));
85
86     // Issue #1733
87     result(p[true]);
88 }
89
90 fn result(i: isize) { }