rat_widget/
range_op.rs

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
99
100
101
102
//!
//! Bounded numeric operations.
//!

/// Bounded numeric operations.
///
/// Useful for taking steps within a range.
///
/// When used with a reversed range it steps
/// in the reversed direction.
///
pub trait RangeOp
where
    Self: Sized,
{
    type Step;

    /// Addition. Bounded to min/max.
    fn add_clamp(self, delta: Self::Step, bounds: (Self, Self)) -> Self;

    /// Subtraction. Bounded to min/max.
    fn sub_clamp(self, delta: Self::Step, bounds: (Self, Self)) -> Self;
}

macro_rules! u_range_op {
    ($value_ty:ty, $step_ty:ty) => {
        impl RangeOp for $value_ty {
            type Step = $step_ty;

            #[inline(always)]
            fn add_clamp(self, delta: Self::Step, bounds: (Self, Self)) -> Self {
                self.saturating_add(delta).clamp(bounds.0, bounds.1)
            }

            #[inline(always)]
            fn sub_clamp(self, delta: Self::Step, bounds: (Self, Self)) -> Self {
                self.saturating_sub(delta).clamp(bounds.0, bounds.1)
            }
        }
    };
}

macro_rules! i_range_op {
    ($value_ty:ty, $step_ty:ty) => {
        impl RangeOp for $value_ty {
            type Step = $step_ty;

            #[inline(always)]
            fn add_clamp(self, delta: Self::Step, bounds: (Self, Self)) -> Self {
                self.saturating_add_unsigned(delta)
                    .clamp(bounds.0, bounds.1)
            }

            #[inline(always)]
            fn sub_clamp(self, delta: Self::Step, bounds: (Self, Self)) -> Self {
                self.saturating_sub_unsigned(delta)
                    .clamp(bounds.0, bounds.1)
            }
        }
    };
}

u_range_op!(u8, u8);
u_range_op!(u16, u16);
u_range_op!(u32, u32);
u_range_op!(u64, u64);
u_range_op!(u128, u128);
u_range_op!(usize, usize);
i_range_op!(i8, u8);
i_range_op!(i16, u16);
i_range_op!(i32, u32);
i_range_op!(i64, u64);
i_range_op!(i128, u128);
i_range_op!(isize, usize);

impl RangeOp for f32 {
    type Step = f32;

    #[inline(always)]
    fn add_clamp(self, delta: Self, bounds: (Self, Self)) -> Self {
        (self + delta).clamp(bounds.0, bounds.1)
    }

    #[inline(always)]
    fn sub_clamp(self, delta: Self, bounds: (Self, Self)) -> Self {
        (self - delta).clamp(bounds.0, bounds.1)
    }
}

impl RangeOp for f64 {
    type Step = f64;

    #[inline(always)]
    fn add_clamp(self, delta: Self, bounds: (Self, Self)) -> Self {
        (self + delta).clamp(bounds.0, bounds.1)
    }

    #[inline(always)]
    fn sub_clamp(self, delta: Self, bounds: (Self, Self)) -> Self {
        (self - delta).clamp(bounds.0, bounds.1)
    }
}