spaces/discrete/
ordinal.rs

1use crate::prelude::*;
2use std::ops::Range;
3
4impl Space for Range<usize> {
5    const DIM: usize = 1;
6
7    type Value = usize;
8
9    fn card(&self) -> Card {
10        // TODO: when the Step trait drops, we can replace this with a direct call to
11        // Step::steps_between.
12        //      See https://github.com/rust-lang/rust/issues/42168
13        Card::Finite(self.len())
14    }
15
16    fn contains(&self, val: &usize) -> bool { Range::contains(&self, val) }
17}
18
19impl OrderedSpace for Range<usize> {
20    fn min(&self) -> Option<usize> { Some(self.start) }
21
22    fn max(&self) -> Option<usize> { Some(self.end - 1) }
23}
24
25impl FiniteSpace for Range<usize> {
26    fn to_ordinal(&self) -> Range<Self::Value> { self.clone() }
27}
28
29impl Union for Range<usize> {
30    fn union(self, other: &Range<usize>) -> Range<usize> {
31        Range {
32            start: self.start.min(other.start),
33            end: self.end.max(other.end)
34        }
35    }
36}
37
38impl Intersect for Range<usize> {
39    fn intersect(self, other: &Range<usize>) -> Range<usize> {
40        Range {
41            start: self.start.max(other.start),
42            end: self.end.min(other.end)
43        }
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[cfg(feature = "serialize")]
52    extern crate serde_test;
53    #[cfg(feature = "serialize")]
54    use self::serde_test::{assert_tokens, Token};
55
56    #[test]
57    fn test_card() {
58        fn check(size: usize) {
59            let d = 0..size;
60
61            assert_eq!(d.card(), Card::Finite(size));
62        }
63
64        check(5);
65        check(10);
66        check(100);
67    }
68
69    #[test]
70    fn test_bounds() {
71        fn check(size: usize) {
72            let d = 0..size;
73
74            assert_eq!(d.inf().unwrap(), 0);
75            assert_eq!(d.sup().unwrap(), size - 1);
76
77            assert!(d.contains(&0));
78            assert!(d.contains(&(size - 1)));
79            assert!(!d.contains(&size));
80        }
81
82        check(5);
83        check(10);
84        check(100);
85    }
86
87    #[test]
88    fn test_to_ordinal() {
89        assert_eq!((0..1).to_ordinal(), 0..1);
90        assert_eq!((0..5).to_ordinal(), 0..5);
91        assert_eq!((0..10).to_ordinal(), 0..10);
92    }
93
94    #[cfg(feature = "serialize")]
95    #[test]
96    fn test_serialisation() {
97        fn check(size: usize) {
98            let d = Ordinal::new(size);
99
100            assert_tokens(
101                &d,
102                &[
103                    Token::NewtypeStruct { name: "Ordinal", },
104                    Token::U64(size as u64),
105                ],
106            );
107        }
108
109        check(5);
110        check(10);
111        check(100);
112    }
113}