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
57const READ_CHUNK_SIZE: usize = 64 * 1024;
58
59impl<'a> DekuReader<'a, &u32> for DekuBytes {
60    fn from_reader_with_ctx<R: Read + Seek>(
61        reader: &mut Reader<R>,
62        count: &u32,
63    ) -> Result<Self, DekuError> {
64        let count = *count as usize;
65        // Do not allocate an untrusted length until the input supplies it.
66        let mut buf = Vec::with_capacity(count.min(READ_CHUNK_SIZE));
67        let mut remaining = count;
68        while remaining > 0 {
69            let chunk = remaining.min(READ_CHUNK_SIZE);
70            let start = buf.len();
71            buf.resize(start + chunk, 0);
72            reader.read_bytes(chunk, &mut buf[start..], Order::Lsb0)?;
73            remaining -= chunk;
74        }
75        Ok(Self(Bytes::from(buf)))
76    }
77}
78
79impl DekuWriter<&u32> for DekuBytes {
80    fn to_writer<W: Write + Seek>(
81        &self,
82        writer: &mut Writer<W>,
83        _count: &u32,
84    ) -> Result<(), DekuError> {
85        writer.write_bytes(&self.0)?;
86        Ok(())
87    }
88}