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