encase/core/
size_value.rs

1use core::num::NonZeroU64;
2
3/// Helper type for size calculations
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub struct SizeValue(pub NonZeroU64);
6
7impl SizeValue {
8    #[inline]
9    pub const fn new(val: u64) -> Self {
10        match val {
11            0 => panic!("Size can't be 0!"),
12            val => {
13                // SAFETY: This is safe since we checked if the value is 0
14                Self(unsafe { NonZeroU64::new_unchecked(val) })
15            }
16        }
17    }
18
19    #[inline]
20    pub const fn from(val: NonZeroU64) -> Self {
21        Self(val)
22    }
23
24    #[inline]
25    pub const fn get(&self) -> u64 {
26        self.0.get()
27    }
28
29    #[inline]
30    pub const fn mul(self, rhs: u64) -> Self {
31        match self.get().checked_mul(rhs) {
32            None => panic!("Overflow occurred while multiplying size values!"),
33            Some(val) => {
34                // SAFETY: This is safe since we checked for overflow
35                Self(unsafe { NonZeroU64::new_unchecked(val) })
36            }
37        }
38    }
39}
40
41#[cfg(test)]
42mod test {
43    use super::SizeValue;
44
45    #[test]
46    fn new() {
47        assert_eq!(4, SizeValue::new(4).get());
48    }
49
50    #[test]
51    #[should_panic]
52    fn new_panic() {
53        SizeValue::new(0);
54    }
55
56    #[test]
57    fn mul() {
58        assert_eq!(SizeValue::new(64), SizeValue::new(8).mul(8));
59    }
60
61    #[test]
62    #[should_panic]
63    fn mul_panic() {
64        SizeValue::new(8).mul(u64::MAX);
65    }
66
67    #[test]
68    fn derived_traits() {
69        let size = SizeValue::new(8);
70        #[allow(clippy::clone_on_copy)]
71        let size_clone = size.clone();
72
73        assert!(size == size_clone);
74
75        assert_eq!(format!("{size:?}"), "SizeValue(8)");
76    }
77}