#![allow(missing_docs)]
use bytes::Bytes;
use crate::chunk::Chunk;
use crate::chunk::chunk_header::CHUNK_HEADER_SIZE;
use crate::packet::{PACKET_HEADER_SIZE, Packet};
use crate::util::get_padding_size;
fn with_checksum(data: &[u8]) -> Bytes {
let mut packet = data.to_vec();
if packet.len() >= PACKET_HEADER_SIZE {
packet[8..12].fill(0);
let checksum = crc32c::crc32c(&packet);
packet[8..12].copy_from_slice(&checksum.to_le_bytes());
}
Bytes::from(packet)
}
pub fn packet_unmarshal(data: &[u8]) {
let _ = Packet::unmarshal(&Bytes::copy_from_slice(data));
}
pub fn packet_unmarshal_fixed_checksum(data: &[u8]) {
let _ = Packet::unmarshal(&with_checksum(data));
}
fn chunk_sizes_are_what_is_written(chunks: &[Box<dyn Chunk>]) {
for chunk in chunks {
let Ok(written) = chunk.marshal() else {
continue;
};
assert_eq!(
written.len(),
CHUNK_HEADER_SIZE + chunk.value_length(),
"a chunk writes the size it declares: {chunk:?}"
);
let field = usize::from(u16::from_be_bytes([written[2], written[3]]));
assert_eq!(
field,
written.len(),
"the Chunk Length field is what was written: {chunk:?}"
);
}
}
fn roundtrip(raw: &Bytes) {
let Ok(first) = Packet::unmarshal(raw) else {
return;
};
chunk_sizes_are_what_is_written(&first.chunks);
let Ok(written) = first.marshal() else {
return;
};
assert_eq!(
written.len(),
first.marshaled_len(),
"marshaled_len is what is written"
);
let ends = chunk_ends(&written);
assert_eq!(
ends.len(),
first.chunks.len(),
"every written chunk is framed by its length"
);
assert_eq!(
ends.last().copied().unwrap_or(0),
written.len() - PACKET_HEADER_SIZE,
"the chunks, each padded to 4 octets, are the whole packet"
);
let second = Packet::unmarshal(&written).expect("what was written parses");
assert_eq!(
second.chunks.len(),
first.chunks.len(),
"the same chunks are read back"
);
chunk_sizes_are_what_is_written(&second.chunks);
let again = second.marshal().expect("and is written again");
assert_eq!(again, written, "marshal(parse(.)) is a fixed point");
}
fn chunk_ends(packet: &[u8]) -> Vec<usize> {
let mut ends = vec![];
let mut offset = PACKET_HEADER_SIZE;
while offset + CHUNK_HEADER_SIZE <= packet.len() {
let length = usize::from(u16::from_be_bytes([packet[offset + 2], packet[offset + 3]]));
if length < CHUNK_HEADER_SIZE {
break;
}
offset += length + get_padding_size(length);
ends.push(offset - PACKET_HEADER_SIZE);
}
ends
}
pub fn packet_roundtrip(data: &[u8]) {
roundtrip(&with_checksum(data));
}
pub fn chunks_roundtrip(data: &[u8]) {
let mut packet = Vec::with_capacity(PACKET_HEADER_SIZE + data.len());
packet.extend_from_slice(&[0x13, 0x88, 0x13, 0x89, 0, 0, 0, 1, 0, 0, 0, 0]);
packet.extend_from_slice(data);
roundtrip(&with_checksum(&packet));
}