binbuf/impls/
arb_num.rs

1
2// pub struct Value<T: Base, const B: usize>(T);
3
4// pub trait Base {
5//     fn to_le_bytes<const B: usize>(&self) -> [u8; B];
6//     fn from_le_bytes<const B: usize>(bytes: [u8; B]) -> Self;
7// }
8
9// // Value<u32, 4> Value<u64, 3>
10
11use crate::utils::slice_to_array;
12
13pub trait Base {
14    const LEN: usize;
15    type Bytes;
16    fn to_le_bytes(&self) -> Self::Bytes;
17    fn from_le_bytes(bytes: Self::Bytes) -> Self;
18    fn bytes_to_slice(bytes: &Self::Bytes) -> &[u8];
19    unsafe fn slice_to_bytes(slice: &[u8]) -> Self::Bytes;
20}
21
22// pub trait BaseU64: Base {
23//     fn to_u64(self) -> u64;
24//     fn from_u64(val: u64) -> Self;
25// }
26
27impl Base for u64 {
28    const LEN: usize = 8;
29    type Bytes = [u8; 8];
30    fn to_le_bytes(&self) -> Self::Bytes {
31        u64::to_le_bytes(*self)
32    }
33    fn from_le_bytes(bytes: Self::Bytes) -> Self {
34        u64::from_le_bytes(bytes)
35    }
36    fn bytes_to_slice(bytes: &Self::Bytes) -> &[u8] {
37        bytes
38    }
39    unsafe fn slice_to_bytes(slice: &[u8]) -> Self::Bytes {
40        *slice_to_array(slice)
41    }
42}
43
44// impl BaseU64 for u64 {
45//     fn to_u64(self) -> u64 {
46        
47//     }
48// }
49
50fixed! {
51    #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
52    pub struct Value<const LEN: usize, T>(T);
53    buf! { pub struct Buf<P, const LEN: usize, T: Base>(Value<LEN, T>, P); }
54
55    impl<const LEN: usize, T: Base> I for Value<LEN, T> {
56        type Buf<P> = Buf<P, LEN, T>;
57    }
58}
59
60impl<const LEN: usize, T> Value<LEN, T> {
61    pub fn new(value: T) -> Self {
62        Self(value)
63    }
64
65    pub fn unwrap(self) -> T {
66        self.0
67    }
68}
69
70impl<const LEN: usize, T: Base> crate::Fixed for Value<LEN, T> {
71    const LEN: usize = LEN;
72    fn encode(&self, buf: crate::fixed::BufMut<Self>) {
73        buf.0.copy_from_slice(&T::bytes_to_slice(&self.0.to_le_bytes())[0 .. LEN]);
74    }
75}
76
77impl<const LEN: usize, T: Base> crate::fixed::Decode for Value<LEN, T>
78where [(); T::LEN]: {
79    fn decode(buf: crate::fixed::BufConst<Self>) -> Self {
80        let mut arr = [0; T::LEN];
81        arr[0 .. LEN].copy_from_slice(buf.0.slice());
82        Self(T::from_le_bytes(unsafe { T::slice_to_bytes(&arr) }))
83    }
84}