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
use crate::{error::Error, Deparsable, PResult, Parsable};
fn try_split_at(input: &[u8], at: usize) -> PResult<&[u8]> {
(input.len() >= at)
.then(|| input.split_at(at))
.ok_or(Error::NotEnoughBytes)
}
#[derive(Debug, Default)]
pub struct VarBytes<'a, L> {
length: L,
slice: &'a [u8],
}
impl<L> AsRef<[u8]> for VarBytes<'_, L> {
fn as_ref(&self) -> &[u8] { self.slice }
}
impl<'a, C, L> Parsable<'a, C> for VarBytes<'a, L>
where
C: Copy,
L: Copy + Into<u64> + Parsable<'a, ()>,
{
fn read(bytes: &'a [u8], _context: C) -> PResult<Self> {
let (length, bytes) = L::read(bytes, ())?;
let (slice, bytes) = try_split_at(bytes, length.into() as _)?;
Ok((Self { length, slice }, bytes))
}
}
impl<L> Deparsable for VarBytes<'_, L>
where
L: Deparsable,
{
fn write(&self, w: &mut impl std::io::Write) -> std::io::Result<()> {
self.length.write(w)?;
self.slice.write(w)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct VarStructs<L, T> {
length: L,
vec: Vec<T>,
}
impl<L, T> AsRef<[T]> for VarStructs<L, T> {
fn as_ref(&self) -> &[T] { &self.vec }
}
impl<L, T> AsMut<[T]> for VarStructs<L, T> {
fn as_mut(&mut self) -> &mut [T] { &mut self.vec }
}
impl<'a, C, L, T> Parsable<'a, C> for VarStructs<L, T>
where
C: Copy,
L: Copy + Into<u64> + Parsable<'a, ()>,
T: Parsable<'a, C>,
{
fn read(bytes: &'a [u8], context: C) -> PResult<Self> {
let (length, mut bytes) = L::read(bytes, ())?;
let vec = (0..length.into())
.map(|_| {
let (t, tail) = T::read(bytes, context)?;
bytes = tail;
Ok(t)
})
.collect::<Result<Vec<_>, _>>()?;
Ok((Self { length, vec }, bytes))
}
}
impl<L, T> Deparsable for VarStructs<L, T>
where
L: Deparsable,
T: Deparsable,
{
fn write(&self, w: &mut impl std::io::Write) -> std::io::Result<()> {
self.length.write(w)?;
self.vec.write(w)?;
Ok(())
}
}