]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/typeclasses-eq-example.rs
Auto merge of #28816 - petrochenkov:unistruct, r=nrc
[rust.git] / src / test / run-pass / typeclasses-eq-example.rs
1 // Copyright 2012 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 #![allow(unknown_features)]
12 #![feature(box_syntax)]
13
14 // Example from lkuper's intern talk, August 2012.
15 use Color::{cyan, magenta, yellow, black};
16 use ColorTree::{leaf, branch};
17
18 trait Equal {
19     fn isEq(&self, a: &Self) -> bool;
20 }
21
22 #[derive(Clone, Copy)]
23 enum Color { cyan, magenta, yellow, black }
24
25 impl Equal for Color {
26     fn isEq(&self, a: &Color) -> bool {
27         match (*self, *a) {
28           (cyan, cyan)       => { true  }
29           (magenta, magenta) => { true  }
30           (yellow, yellow)   => { true  }
31           (black, black)     => { true  }
32           _                  => { false }
33         }
34     }
35 }
36
37 #[derive(Clone)]
38 enum ColorTree {
39     leaf(Color),
40     branch(Box<ColorTree>, Box<ColorTree>)
41 }
42
43 impl Equal for ColorTree {
44     fn isEq(&self, a: &ColorTree) -> bool {
45         match (self, a) {
46           (&leaf(ref x), &leaf(ref y)) => { x.isEq(&(*y).clone()) }
47           (&branch(ref l1, ref r1), &branch(ref l2, ref r2)) => {
48             (*l1).isEq(&(**l2).clone()) && (*r1).isEq(&(**r2).clone())
49           }
50           _ => { false }
51         }
52     }
53 }
54
55 pub fn main() {
56     assert!(cyan.isEq(&cyan));
57     assert!(magenta.isEq(&magenta));
58     assert!(!cyan.isEq(&yellow));
59     assert!(!magenta.isEq(&cyan));
60
61     assert!(leaf(cyan).isEq(&leaf(cyan)));
62     assert!(!leaf(cyan).isEq(&leaf(yellow)));
63
64     assert!(branch(box leaf(magenta), box leaf(cyan))
65         .isEq(&branch(box leaf(magenta), box leaf(cyan))));
66
67     assert!(!branch(box leaf(magenta), box leaf(cyan))
68         .isEq(&branch(box leaf(magenta), box leaf(magenta))));
69
70     println!("Assertions all succeeded!");
71 }