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