1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use crate::prelude::*;
use std::{fmt, ops::Range};

/// Type representing binary (base-2) values.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct Binary;

impl Space for Binary {
    type Value = bool;

    fn dim(&self) -> Dim { Dim::one() }

    fn card(&self) -> Card { Card::Finite(2) }
}

impl BoundedSpace for Binary {
    fn inf(&self) -> Option<bool> { Some(false) }

    fn sup(&self) -> Option<bool> { Some(true) }

    fn contains(&self, _: bool) -> bool { true }
}

impl FiniteSpace for Binary {
    fn range(&self) -> Range<Self::Value> { false..true }
}

impl_union_intersect!(Binary, Binary);

impl Surjection<bool, bool> for Binary {
    fn map_onto(&self, val: bool) -> bool { val }
}

impl fmt::Display for Binary {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{{0, 1}}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "serialize")]
    extern crate serde_test;
    #[cfg(feature = "serialize")]
    use self::serde_test::{assert_tokens, Token};

    #[test]
    fn test_dim() {
        let d = Binary;

        assert_eq!(d.dim(), Dim::one());
    }

    #[test]
    fn test_card() {
        let d = Binary;

        assert_eq!(d.card(), Card::Finite(2));
    }

    #[test]
    fn test_bounds() {
        let d = Binary;

        assert_eq!(d.inf().unwrap(), false);
        assert_eq!(d.sup().unwrap(), true);

        assert!(d.contains(false));
        assert!(d.contains(true));
    }

    #[test]
    fn test_range() {
        let d = Binary;
        let r = d.range();

        assert!(r == (false..true) || r == (true..false));
    }

    #[test]
    fn test_surjection() {
        let d = Binary;

        assert_eq!(d.map_onto(true), true);
        assert_eq!(d.map_onto(false), false);
    }

    #[cfg(feature = "serialize")]
    #[test]
    fn test_serialisation() {
        let d = Binary;

        assert_tokens(&d, &[Token::UnitStruct { name: "Binary" }]);
    }
}