encase/core/
size_value.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
use core::num::NonZeroU64;

/// Helper type for size calculations
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SizeValue(pub NonZeroU64);

impl SizeValue {
    #[inline]
    pub const fn new(val: u64) -> Self {
        match val {
            0 => panic!("Size can't be 0!"),
            val => {
                // SAFETY: This is safe since we checked if the value is 0
                Self(unsafe { NonZeroU64::new_unchecked(val) })
            }
        }
    }

    #[inline]
    pub const fn from(val: NonZeroU64) -> Self {
        Self(val)
    }

    #[inline]
    pub const fn get(&self) -> u64 {
        self.0.get()
    }

    #[inline]
    pub const fn mul(self, rhs: u64) -> Self {
        match self.get().checked_mul(rhs) {
            None => panic!("Overflow occurred while multiplying size values!"),
            Some(val) => {
                // SAFETY: This is safe since we checked for overflow
                Self(unsafe { NonZeroU64::new_unchecked(val) })
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::SizeValue;

    #[test]
    fn new() {
        assert_eq!(4, SizeValue::new(4).get());
    }

    #[test]
    #[should_panic]
    fn new_panic() {
        SizeValue::new(0);
    }

    #[test]
    fn mul() {
        assert_eq!(SizeValue::new(64), SizeValue::new(8).mul(8));
    }

    #[test]
    #[should_panic]
    fn mul_panic() {
        SizeValue::new(8).mul(u64::MAX);
    }

    #[test]
    fn derived_traits() {
        let size = SizeValue::new(8);
        #[allow(clippy::clone_on_copy)]
        let size_clone = size.clone();

        assert!(size == size_clone);

        assert_eq!(format!("{size:?}"), "SizeValue(8)");
    }
}