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
//! Limb encoding

use super::{Limb, Word};
use crate::Encoding;

impl Encoding for Limb {
    const BIT_SIZE: usize = Self::BIT_SIZE;
    const BYTE_SIZE: usize = Self::BYTE_SIZE;

    #[cfg(target_pointer_width = "32")]
    type Repr = [u8; 4];
    #[cfg(target_pointer_width = "64")]
    type Repr = [u8; 8];

    #[inline]
    fn from_be_bytes(bytes: Self::Repr) -> Self {
        Limb(Word::from_be_bytes(bytes))
    }

    #[inline]
    fn from_le_bytes(bytes: Self::Repr) -> Self {
        Limb(Word::from_le_bytes(bytes))
    }

    #[inline]
    fn to_be_bytes(&self) -> Self::Repr {
        self.0.to_be_bytes()
    }

    #[inline]
    fn to_le_bytes(&self) -> Self::Repr {
        self.0.to_le_bytes()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use proptest::prelude::*;

    prop_compose! {
        fn limb()(inner in any::<Word>()) -> Limb {
            Limb(inner)
        }
    }

    proptest! {
        #[test]
        fn roundtrip(a in limb()) {
            assert_eq!(a, Limb::from_be_bytes(a.to_be_bytes()));
            assert_eq!(a, Limb::from_le_bytes(a.to_le_bytes()));
        }
    }

    proptest! {
        #[test]
        fn reverse(a in limb()) {
            let mut bytes = a.to_be_bytes();
            bytes.reverse();
            assert_eq!(a, Limb::from_le_bytes(bytes));

            let mut bytes = a.to_le_bytes();
            bytes.reverse();
            assert_eq!(a, Limb::from_be_bytes(bytes));
        }
    }
}