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
//! The goal of this module is to make checking whether a number
//! is between two other numbers as easy as possible.

#[cfg(test)]
mod tests {
    use super::Interval;
    
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
    
    #[test]
    fn check_open_containment() {
        let interval = Interval::new(0u8,10u8);
        assert!(interval.contains(3u8));
    }
    
    #[test]
    fn check_closed_containment() {
        let interval = Interval::new(-3f32, 4f32);
        assert!(interval.contains_closed(-3f32));
    }
}


use std::cmp::PartialOrd;

/// An `Interval` struct represents an interval.
/// The main appeal is that it allows checking if
/// a number is between the interval bounds more easily
/// than manually writing the inequality comparisons yourself.
pub struct Interval<T :PartialOrd> {
    low :T,
    high :T,
}

impl<T :PartialOrd> Interval<T> {
    /// The `new` function enables construction of an Interval 
    /// without needing to think about which
    /// boundary is greater.
    pub fn new(bound1 :T, bound2 :T) -> Interval<T> {
        if bound1 < bound2 {
            Interval{low : bound1, high :bound2}
        } else {
            Interval{low : bound2, high : bound1}
        }
    }
    
    /// The `contains` function enables
    /// easy checking if a value is contained in the open
    /// version of an interval (the bounds are 
    /// not part of the interval).
    pub fn contains(&self, value :T) -> bool {
        self.low < value && value < self.high
    }
    
    /// The `contains_closed` enables
    /// easy cheching if a value is contained in the contained
    /// in the closed version of an interval (the bounds are
    /// part of the interval).
    pub fn contains_closed(&self, value :T) -> bool {
        self.low <= value && value <= self.high
    }
}