open_pql/vm/
store_var_idx.rs

1use super::*;
2
3#[derive(Debug, Clone, Copy, From, PartialEq, Eq)]
4pub struct VmStoreVarIdx(u8);
5
6impl Add<u8> for VmStoreVarIdx {
7    type Output = Self;
8
9    fn add(self, rhs: u8) -> Self::Output {
10        Self(self.0 + rhs)
11    }
12}
13
14impl VmStoreVarIdx {
15    pub const fn to_usize(self) -> usize {
16        self.0 as usize
17    }
18}
19
20impl TryFrom<usize> for VmStoreVarIdx {
21    type Error = PQLError;
22
23    fn try_from(value: usize) -> Result<Self, Self::Error> {
24        if value > u8::MAX as usize {
25            return Err(PQLError::TooManyVariables);
26        }
27
28        Ok(Self(value.to_le_bytes()[0]))
29    }
30}
31
32impl PartialOrd for VmStoreVarIdx {
33    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
34        if self.0 == other.0 {
35            Some(Ordering::Equal)
36        } else {
37            None
38        }
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    impl Arbitrary for VmStoreVarIdx {
47        fn arbitrary(g: &mut quickcheck::Gen) -> Self {
48            Self(u8::arbitrary(g))
49        }
50    }
51
52    #[test]
53    fn test_add() {
54        let v = VmStoreVarIdx(254);
55
56        assert_eq!(v + 1, 255.into());
57    }
58
59    #[test]
60    fn test_ord() {
61        use VmStoreVarIdx as I;
62        assert_eq!(Some(Ordering::Equal), I(0).partial_cmp(&I(0)));
63        assert_eq!(None, I(1).partial_cmp(&I(0)));
64    }
65
66    #[test]
67    fn test_cast() {
68        assert_eq!(
69            VmStoreVarIdx(100),
70            VmStoreVarIdx::try_from(100usize).unwrap()
71        );
72        assert_eq!(100, VmStoreVarIdx(100).to_usize());
73    }
74}