Debian Codegraph @

src/utils/general.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use std::cmp::Ordering;
2
3 #[inline]
4 pub(crate) const fn sort_partial_fn<T: PartialOrd>(is_descending: bool) -> fn(T, T) -> Ordering {
5 if is_descending {
6 partial_ordering_desc
7 } else {
8 partial_ordering
9 }
10 }
11
12 /// Returns an [`Ordering`] between two [`PartialOrd`]s.
13 #[inline]
14 pub(crate) fn partial_ordering<T: PartialOrd>(a: T, b: T) -> Ordering {
15 a.partial_cmp(&b).unwrap_or(Ordering::Equal)
16 }
17
18 /// Returns a reversed [`Ordering`] between two [`PartialOrd`]s.
19 ///
20 /// This is simply a wrapper function around [`partial_ordering`] that reverses
21 /// the result.
22 #[inline]
23 pub(crate) fn partial_ordering_desc<T: PartialOrd>(a: T, b: T) -> Ordering {
24 partial_ordering(a, b).reverse()
25 }
26
27 /// A trait for additional clamping functions on numeric types.
28 pub(crate) trait ClampExt {
29 /// Restrict a value by a lower bound. If the current value is _lower_ than
30 /// `lower_bound`, it will be set to `_lower_bound`.
31 #[cfg_attr(not(test), expect(dead_code))]
32 fn clamp_lower(&self, lower_bound: Self) -> Self;
33
34 /// Restrict a value by an upper bound. If the current value is _greater_
35 /// than `upper_bound`, it will be set to `upper_bound`.
36 fn clamp_upper(&self, upper_bound: Self) -> Self;
37 }
38
39 macro_rules! clamp_num_impl {
40 ( $($NumType:ty),+ $(,)? ) => {
41 $(
42 impl ClampExt for $NumType {
43 fn clamp_lower(&self, lower_bound: Self) -> Self {
44 if *self < lower_bound {
45 lower_bound
46 } else {
47 *self
48 }
49 }
50
51 fn clamp_upper(&self, upper_bound: Self) -> Self {
52 if *self > upper_bound {
53 upper_bound
54 } else {
55 *self
56 }
57 }
58 }
59 )*
60 };
61 }
62
63 clamp_num_impl!(u8, u16, u32, u64, usize);
64
65 /// Checked log2.
66 pub(crate) fn saturating_log2(value: f64) -> f64 {
67 if value > 0.0 { value.log2() } else { 0.0 }
68 }
69
70 /// Checked log10.
71 pub(crate) fn saturating_log10(value: f64) -> f64 {
72 if value > 0.0 { value.log10() } else { 0.0 }
73 }
74
75 #[cfg(test)]
76 mod test {
77 use super::*;
78
79 #[test]
80 fn test_clamp_upper() {
81 let val: usize = 100;
82 assert_eq!(val.clamp_upper(150), 100);
83
84 let val: usize = 100;
85 assert_eq!(val.clamp_upper(100), 100);
86
87 let val: usize = 100;
88 assert_eq!(val.clamp_upper(50), 50);
89 }
90
91 #[test]
92 fn test_clamp_lower() {
93 let val: usize = 100;
94 assert_eq!(val.clamp_lower(150), 150);
95
96 let val: usize = 100;
97 assert_eq!(val.clamp_lower(100), 100);
98
99 let val: usize = 100;
100 assert_eq!(val.clamp_lower(50), 100);
101 }
102 }