]> git.proxmox.com Git - rustc.git/blob - src/test/ui/traits/typeclasses-eq-example.rs
New upstream version 1.58.1+dfsg1
[rustc.git] / src / test / ui / traits / typeclasses-eq-example.rs
1 // run-pass
2
3 #![allow(non_camel_case_types)]
4 #![allow(non_snake_case)]
5 #![allow(dead_code)]
6
7 // Example from lkuper's intern talk, August 2012.
8 use Color::{cyan, magenta, yellow, black};
9 use ColorTree::{leaf, branch};
10
11 trait Equal {
12 fn isEq(&self, a: &Self) -> bool;
13 }
14
15 #[derive(Clone, Copy)]
16 enum Color { cyan, magenta, yellow, black }
17
18 impl Equal for Color {
19 fn isEq(&self, a: &Color) -> bool {
20 match (*self, *a) {
21 (cyan, cyan) => { true }
22 (magenta, magenta) => { true }
23 (yellow, yellow) => { true }
24 (black, black) => { true }
25 _ => { false }
26 }
27 }
28 }
29
30 #[derive(Clone)]
31 enum ColorTree {
32 leaf(Color),
33 branch(Box<ColorTree>, Box<ColorTree>)
34 }
35
36 impl Equal for ColorTree {
37 fn isEq(&self, a: &ColorTree) -> bool {
38 match (self, a) {
39 (&leaf(ref x), &leaf(ref y)) => { x.isEq(&(*y).clone()) }
40 (&branch(ref l1, ref r1), &branch(ref l2, ref r2)) => {
41 (*l1).isEq(&(**l2).clone()) && (*r1).isEq(&(**r2).clone())
42 }
43 _ => { false }
44 }
45 }
46 }
47
48 pub fn main() {
49 assert!(cyan.isEq(&cyan));
50 assert!(magenta.isEq(&magenta));
51 assert!(!cyan.isEq(&yellow));
52 assert!(!magenta.isEq(&cyan));
53
54 assert!(leaf(cyan).isEq(&leaf(cyan)));
55 assert!(!leaf(cyan).isEq(&leaf(yellow)));
56
57 assert!(branch(Box::new(leaf(magenta)), Box::new(leaf(cyan)))
58 .isEq(&branch(Box::new(leaf(magenta)), Box::new(leaf(cyan)))));
59
60 assert!(!branch(Box::new(leaf(magenta)), Box::new(leaf(cyan)))
61 .isEq(&branch(Box::new(leaf(magenta)), Box::new(leaf(magenta)))));
62
63 println!("Assertions all succeeded!");
64 }