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
use byteorder::{BigEndian, WriteBytesExt};
use std::io::Write;
use crate::{utils, ByteArray, DecodeError, DecodePacket, EncodeError, EncodePacket};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BinaryData(Vec<u8>);
impl BinaryData {
#[must_use]
pub const fn new() -> Self {
Self(Vec::new())
}
pub fn from_slice(data: &[u8]) -> Result<Self, EncodeError> {
utils::validate_two_bytes_data(data)?;
Ok(Self(data.to_vec()))
}
#[must_use]
pub fn bytes(&self) -> usize {
2 + self.0.len()
}
pub fn clear(&mut self) {
self.0.clear();
}
}
impl AsRef<[u8]> for BinaryData {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl AsMut<Vec<u8>> for BinaryData {
fn as_mut(&mut self) -> &mut Vec<u8> {
&mut self.0
}
}
impl DecodePacket for BinaryData {
fn decode(ba: &mut ByteArray) -> Result<Self, DecodeError> {
let len = ba.read_u16()?;
let data = ba.read_bytes(len as usize)?;
Ok(Self(data.to_vec()))
}
}
impl EncodePacket for BinaryData {
fn encode(&self, buf: &mut Vec<u8>) -> Result<usize, EncodeError> {
#[allow(clippy::cast_possible_truncation)]
let len = self.0.len() as u16;
buf.write_u16::<BigEndian>(len)?;
buf.write_all(&self.0)?;
Ok(self.bytes())
}
}