use core::iter::FusedIterator;
use core::{error, fmt};
use crate::crc32::ap_crc32_update;
const SIGNATURE: &[u8; 4] = b"skyb";
const FEATURE_CRC32: u8 = 1;
const CHECKSUM_OFFSET: usize = 6;
const CHECKSUM_LENGTH: usize = 4;
const BLOCK_HEADER_LENGTH: usize = 3;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BinaryBlockType(pub u8);
impl BinaryBlockType {
pub const TRAJECTORY: Self = Self(1);
pub const LIGHT_PROGRAM: Self = Self(2);
pub const COMMENT: Self = Self(3);
pub const RTH_PLAN: Self = Self(4);
pub const YAW_CONTROL: Self = Self(5);
pub const EVENT_LIST: Self = Self(6);
pub const GCS_LIGHT_CONTROL_SETUP: Self = Self(7);
pub const SHOW_METADATA: Self = Self(8);
const END: Self = Self(0);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BinaryBlock<'a> {
pub block_type: BinaryBlockType,
pub body: &'a [u8],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BinaryFileError {
InvalidSignature,
UnsupportedVersion(u8),
TruncatedHeader,
ChecksumMismatch {
expected: u32,
actual: u32,
},
TruncatedBlockHeader,
TruncatedBlock,
}
impl fmt::Display for BinaryFileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidSignature => f.write_str("not a Skybrush binary show file"),
Self::UnsupportedVersion(version) => {
write!(f, "unsupported version of the show file format: {version}")
}
Self::TruncatedHeader => f.write_str("the show file ends in its header"),
Self::ChecksumMismatch { expected, actual } => write!(
f,
"checksum mismatch: the header says {expected:#010x}, the contents give {actual:#010x}"
),
Self::TruncatedBlockHeader => {
f.write_str("the show file ends in the header of a block")
}
Self::TruncatedBlock => f.write_str("the show file ends in the middle of a block"),
}
}
}
impl error::Error for BinaryFileError {}
#[derive(Clone, Copy, Debug)]
pub struct BinaryFile<'a> {
bytes: &'a [u8],
version: u8,
start_of_first_block: usize,
}
impl<'a> BinaryFile<'a> {
pub fn new(bytes: &'a [u8]) -> Result<Self, BinaryFileError> {
let (signature, rest) = bytes
.split_first_chunk::<4>()
.ok_or(BinaryFileError::InvalidSignature)?;
if signature != SIGNATURE {
return Err(BinaryFileError::InvalidSignature);
}
let (&version, rest) = rest.split_first().ok_or(BinaryFileError::TruncatedHeader)?;
let (features, rest) = match version {
1 => (0, rest),
2 => {
let (&features, rest) =
rest.split_first().ok_or(BinaryFileError::TruncatedHeader)?;
(features, rest)
}
_ => return Err(BinaryFileError::UnsupportedVersion(version)),
};
let rest = if features & FEATURE_CRC32 == 0 {
rest
} else {
let (checksum, rest) = rest
.split_first_chunk::<CHECKSUM_LENGTH>()
.ok_or(BinaryFileError::TruncatedHeader)?;
let expected = u32::from_le_bytes(*checksum);
let actual = checksum_of(bytes);
if expected != actual {
return Err(BinaryFileError::ChecksumMismatch { expected, actual });
}
rest
};
let parser = Self {
bytes,
version,
start_of_first_block: bytes.len() - rest.len(),
};
parser.blocks().peek_header()?;
Ok(parser)
}
#[must_use]
pub const fn version(&self) -> u8 {
self.version
}
#[must_use]
pub fn blocks(&self) -> Blocks<'a> {
Blocks {
rest: self
.bytes
.get(self.start_of_first_block..)
.unwrap_or_default(),
}
}
pub fn find_first_block_by_type(
&self,
block_type: BinaryBlockType,
) -> Result<Option<BinaryBlock<'a>>, BinaryFileError> {
for block in self.blocks() {
let block = block?;
if block.block_type == block_type {
return Ok(Some(block));
}
}
Ok(None)
}
}
fn checksum_of(bytes: &[u8]) -> u32 {
let (head, rest) = bytes.split_at(CHECKSUM_OFFSET.min(bytes.len()));
let tail = rest.get(CHECKSUM_LENGTH..).unwrap_or_default();
let crc = ap_crc32_update(0, head);
let crc = ap_crc32_update(crc, &[0; CHECKSUM_LENGTH]);
ap_crc32_update(crc, tail)
}
#[derive(Clone, Debug)]
pub struct Blocks<'a> {
rest: &'a [u8],
}
impl Blocks<'_> {
fn peek_header(&self) -> Result<Option<(BinaryBlockType, usize)>, BinaryFileError> {
let Some((&block_type, rest)) = self.rest.split_first() else {
return Ok(None);
};
let length = rest
.first_chunk::<2>()
.ok_or(BinaryFileError::TruncatedBlockHeader)?;
let block_type = BinaryBlockType(block_type);
if block_type == BinaryBlockType::END {
return Ok(None);
}
Ok(Some((block_type, usize::from(u16::from_le_bytes(*length)))))
}
}
impl<'a> Iterator for Blocks<'a> {
type Item = Result<BinaryBlock<'a>, BinaryFileError>;
fn next(&mut self) -> Option<Self::Item> {
let result = match self.peek_header() {
Ok(None) => None,
Ok(Some((block_type, length))) => {
let rest = self.rest.get(BLOCK_HEADER_LENGTH..).unwrap_or_default();
match rest.split_at_checked(length) {
Some((body, rest)) => {
self.rest = rest;
return Some(Ok(BinaryBlock { block_type, body }));
}
None => Some(Err(BinaryFileError::TruncatedBlock)),
}
}
Err(err) => Some(Err(err)),
};
self.rest = &[];
result
}
}
impl FusedIterator for Blocks<'_> {}
#[cfg(test)]
mod tests {
use super::*;
fn blocks(bytes: &[u8]) -> Result<([BinaryBlockType; 2], usize), BinaryFileError> {
let parser = BinaryFile::new(bytes)?;
let mut types = [BinaryBlockType::END; 2];
let mut count = 0;
for (slot, block) in types.iter_mut().zip(parser.blocks()) {
*slot = block?.block_type;
count += 1;
}
Ok((types, count))
}
#[test]
fn blocks_are_views_into_the_file() {
let bytes = b"skyb\x01\x03\x02\x00hi\x7f\x00\x00";
let parser = BinaryFile::new(bytes).unwrap();
let mut iter = parser.blocks();
assert_eq!(
iter.next(),
Some(Ok(BinaryBlock {
block_type: BinaryBlockType::COMMENT,
body: b"hi"
}))
);
assert_eq!(
iter.next(),
Some(Ok(BinaryBlock {
block_type: BinaryBlockType(0x7f),
body: b""
}))
);
assert_eq!(iter.next(), None);
assert_eq!(parser.version(), 1);
}
#[test]
fn errors_end_the_iteration() {
let parser = BinaryFile::new(b"skyb\x01\x03\x02\x00hi\x01\x05\x00ab").unwrap();
let mut iter = parser.blocks();
assert!(matches!(iter.next(), Some(Ok(_))));
assert_eq!(iter.next(), Some(Err(BinaryFileError::TruncatedBlock)));
assert_eq!(iter.next(), None);
}
#[test]
fn type_zero_ends_the_list_but_needs_a_length() {
assert_eq!(
blocks(b"skyb\x01\x00\x00\x00\x03\x00\x00"),
Ok(([BinaryBlockType::END; 2], 0))
);
assert_eq!(
blocks(b"skyb\x01\x00"),
Err(BinaryFileError::TruncatedBlockHeader)
);
}
#[test]
fn checksum_covers_the_file_without_itself() {
let mut bytes = *b"skyb\x02\x01\0\0\0\0\x03\x01\x00!";
let crc = ap_crc32_update(0, &bytes);
bytes[6..10].copy_from_slice(&crc.to_le_bytes());
assert!(BinaryFile::new(&bytes).is_ok());
bytes[13] = b'?';
assert!(matches!(
BinaryFile::new(&bytes),
Err(BinaryFileError::ChecksumMismatch { expected, .. }) if expected == crc
));
}
}