Skip to main content

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) => Self::new(val),
34        }
35    }
36}
37
38#[cfg(test)]
39mod test {
40    use super::SizeValue;
41    use alloc::format;
42
43    #[test]
44    fn new() {
45        assert_eq!(4, SizeValue::new(4).get());
46    }
47
48    #[test]
49    #[should_panic]
50    fn new_panic() {
51        SizeValue::new(0);
52    }
53
54    #[test]
55    fn mul() {
56        assert_eq!(SizeValue::new(64), SizeValue::new(8).mul(8));
57    }
58
59    #[test]
60    #[should_panic]
61    fn mul_panic() {
62        SizeValue::new(8).mul(u64::MAX);
63    }
64
65    #[test]
66    #[should_panic]
67    fn mul_zero_panic() {
68        SizeValue::new(8).mul(0);
69    }
70
71    #[test]
72    fn derived_traits() {
73        let size = SizeValue::new(8);
74        #[allow(clippy::clone_on_copy)]
75        let size_clone = size.clone();
76
77        assert!(size == size_clone);
78
79        assert_eq!(format!("{size:?}"), "SizeValue(8)");
80    }
81}