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