Skip to main content

ninep_proto/
deku_bytes.rs

1use bytes::Bytes;
2use deku::ctx::Order;
3use deku::prelude::*;
4use deku::reader::Reader;
5use deku::writer::Writer;
6use std::io::{Read, Seek, Write};
7
8#[derive(Debug, Clone, Default)]
9pub struct DekuBytes(pub Bytes);
10
11impl DekuBytes {
12    pub fn new(bytes: Bytes) -> Self {
13        Self(bytes)
14    }
15
16    pub fn len(&self) -> usize {
17        self.0.len()
18    }
19
20    pub fn is_empty(&self) -> bool {
21        self.0.is_empty()
22    }
23}
24
25impl From<Bytes> for DekuBytes {
26    fn from(bytes: Bytes) -> Self {
27        Self(bytes)
28    }
29}
30
31impl From<Vec<u8>> for DekuBytes {
32    fn from(vec: Vec<u8>) -> Self {
33        Self(Bytes::from(vec))
34    }
35}
36
37impl From<DekuBytes> for Bytes {
38    fn from(deku_bytes: DekuBytes) -> Self {
39        deku_bytes.0
40    }
41}
42
43impl AsRef<[u8]> for DekuBytes {
44    fn as_ref(&self) -> &[u8] {
45        &self.0
46    }
47}
48
49impl std::ops::Deref for DekuBytes {
50    type Target = Bytes;
51
52    fn deref(&self) -> &Self::Target {
53        &self.0
54    }
55}
56
57impl<'a> DekuReader<'a, &u32> for DekuBytes {
58    fn from_reader_with_ctx<R: Read + Seek>(
59        reader: &mut Reader<R>,
60        count: &u32,
61    ) -> Result<Self, DekuError> {
62        let count = *count as usize;
63        let mut buf = vec![0u8; count];
64
65        reader.read_bytes(count, &mut buf, Order::Lsb0)?;
66        Ok(Self(Bytes::from(buf)))
67    }
68}
69
70impl DekuWriter<&u32> for DekuBytes {
71    fn to_writer<W: Write + Seek>(
72        &self,
73        writer: &mut Writer<W>,
74        _count: &u32,
75    ) -> Result<(), DekuError> {
76        writer.write_bytes(&self.0)?;
77        Ok(())
78    }
79}