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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use bytes::{Buf, BufMut, Bytes, BytesMut};
use ref_cast::RefCast;

use crate::{error::*, EpeeValue, InnerMarker, Marker};

#[derive(RefCast)]
#[repr(transparent)]
pub struct ContainerAsBlob<T: Containerable + EpeeValue>(Vec<T>);

impl<T: Containerable + EpeeValue> From<Vec<T>> for ContainerAsBlob<T> {
    fn from(value: Vec<T>) -> Self {
        ContainerAsBlob(value)
    }
}

impl<T: Containerable + EpeeValue> From<ContainerAsBlob<T>> for Vec<T> {
    fn from(value: ContainerAsBlob<T>) -> Self {
        value.0
    }
}

impl<'a, T: Containerable + EpeeValue> From<&'a Vec<T>> for &'a ContainerAsBlob<T> {
    fn from(value: &'a Vec<T>) -> Self {
        ContainerAsBlob::ref_cast(value)
    }
}

impl<T: Containerable + EpeeValue> EpeeValue for ContainerAsBlob<T> {
    const MARKER: Marker = Marker::new(InnerMarker::String);

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        let bytes = Bytes::read(r, marker)?;
        if bytes.len() % T::SIZE != 0 {
            return Err(Error::Value(
                "Can't convert blob container to Vec type.".to_string(),
            ));
        }

        Ok(ContainerAsBlob(
            bytes.chunks(T::SIZE).map(T::from_bytes).collect(),
        ))
    }

    fn should_write(&self) -> bool {
        !self.0.is_empty()
    }

    fn epee_default_value() -> Option<Self> {
        Some(ContainerAsBlob(vec![]))
    }

    fn write<B: BufMut>(self, w: &mut B) -> crate::Result<()> {
        let mut buf = BytesMut::with_capacity(self.0.len() * T::SIZE);
        self.0.iter().for_each(|tt| tt.push_bytes(&mut buf));
        buf.write(w)
    }
}

pub trait Containerable {
    const SIZE: usize;

    /// Returns `Self` from bytes.
    ///
    /// `bytes` is guaranteed to be [`Self::SIZE`] long.
    fn from_bytes(bytes: &[u8]) -> Self;

    fn push_bytes(&self, buf: &mut BytesMut);
}

macro_rules! int_container_able {
    ($int:ty ) => {
        impl Containerable for $int {
            const SIZE: usize = size_of::<$int>();

            fn from_bytes(bytes: &[u8]) -> Self {
                <$int>::from_le_bytes(bytes.try_into().unwrap())
            }

            fn push_bytes(&self, buf: &mut BytesMut) {
                buf.put_slice(&self.to_le_bytes())
            }
        }
    };
}

int_container_able!(u16);
int_container_able!(u32);
int_container_able!(u64);
int_container_able!(u128);

int_container_able!(i8);
int_container_able!(i16);
int_container_able!(i32);
int_container_able!(i64);
int_container_able!(i128);