num_bound/
lib.rs

1/**
2 * 
3This module defines a trait `Bound` that provides a method `bound` for bounding a value between a lower and upper limit.
4
5*/
6pub trait Bound: Ord
7{
8    /// Bound a value between a lower and upper limit
9    /// 
10    /// ### Arguments
11    /// 
12    /// * `lower` - The lower limit
13    /// * `upper` - The upper limit
14    /// 
15    /// ### Returns
16    /// 
17    /// The value bounded between the lower and upper limit
18    /// 
19    /// ### Example
20    /// 
21    /// ```
22    /// use num_bound::Bound;
23    ///     
24    /// assert_eq!(1.bound(0, 2), 1);
25    /// assert_eq!(0.bound(0, 2), 0);
26    /// assert_eq!(2.bound(0, 2), 2);
27    /// assert_eq!((-1).bound(0, 2), 0);
28    /// assert_eq!(3.bound(0, 2), 2);
29    /// ```
30    fn bound(self, lower: Self, upper: Self) -> Self;    
31}
32
33
34impl<T: Ord> Bound for T
35{
36    #[inline(always)]
37    fn bound(self, lower: T, upper: T) -> T
38    {
39        if self < lower
40        {
41            lower
42        }
43        else if self > upper
44        {
45            upper
46        }
47        else
48        {
49            self
50        }
51    }
52}
53
54
55#[test]
56fn test_bound_ref()
57{
58    assert_eq!((&1).bound(&0, &2), &1);
59    assert_eq!((&0).bound(&0, &2), &0);
60    assert_eq!((&2).bound(&0, &2), &2);
61    assert_eq!((&-1).bound(&0, &2), &0);
62    assert_eq!((&3).bound(&0, &2), &2);
63}
64
65#[test]
66fn test_bound()
67{
68    assert_eq!(1.bound(0, 2), 1);
69    assert_eq!(0.bound(0, 2), 0);
70    assert_eq!(2.bound(0, 2), 2);
71    assert_eq!((-1).bound(0, 2), 0);
72    assert_eq!(3.bound(0, 2), 2);
73}