classicube_relay/packet/
continue.rs1use super::{flags::Flags, FlagsError, Packet};
2use std::io::{Read, Write};
3
4#[derive(Debug, thiserror::Error)]
5pub enum ContinuePacketError {
6 #[error("wrong data_part len")]
7 DataPartLength,
8
9 #[error("couldn't read full data_part")]
10 ReadFullDataPart,
11
12 #[error(transparent)]
13 Flags(#[from] FlagsError),
14
15 #[error(transparent)]
16 Io(#[from] std::io::Error),
17}
18type Result<T> = std::result::Result<T, ContinuePacketError>;
19
20#[derive(Debug, PartialEq, Eq)]
21pub struct ContinuePacket {
22 pub stream_id: u8,
23 pub data_part: Vec<u8>,
24}
25impl ContinuePacket {
26 pub const DATA_PART_LENGTH: usize = 64 - 1;
27
28 pub fn new(stream_id: u8, data_part: Vec<u8>) -> Result<Self> {
29 if data_part.len() != Self::DATA_PART_LENGTH {
30 return Err(ContinuePacketError::DataPartLength);
31 }
32
33 Ok(Self {
34 stream_id,
35 data_part,
36 })
37 }
38
39 pub fn new_reader(stream_id: u8, data_stream: &mut impl Read) -> Result<Self> {
40 let mut data_part = Vec::with_capacity(Packet::DATA_LENGTH);
41
42 let mut buf = [0; Self::DATA_PART_LENGTH];
43 let n = data_stream.read(&mut buf)?;
44
45 data_part.write_all(&buf[..n])?;
46 data_part.resize(Self::DATA_PART_LENGTH, 0);
47
48 Self::new(stream_id, data_part)
49 }
50
51 pub fn encode(&self) -> Result<Vec<u8>> {
52 let mut data = Vec::with_capacity(Packet::DATA_LENGTH);
53
54 data.write_all(
55 &Flags {
56 is_packet_start: false,
57 stream_id: self.stream_id,
58 }
59 .encode()?,
60 )?;
61 data.write_all(&self.data_part)?;
62
63 Ok(data)
64 }
65
66 pub(crate) fn decode(stream_id: u8, data_stream: &mut impl Read) -> Result<Self> {
67 let mut data_part = [0; Self::DATA_PART_LENGTH];
68 let n = data_stream.read(&mut data_part)?;
69
70 if n != Self::DATA_PART_LENGTH {
71 return Err(ContinuePacketError::ReadFullDataPart);
72 }
73
74 Ok(Self {
75 stream_id,
76 data_part: data_part.to_vec(),
77 })
78 }
79}