use crate::crc::crc16;
use crate::record::{DataField, Records};
use crate::{Check, Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Format<'a> {
pub signature: u16,
pub headers: &'a [u8],
}
impl<'a> Format<'a> {
pub fn of<'o>(records: &Records<'_>, out: &'o mut [u8]) -> Option<Format<'o>> {
let mut n = 0usize;
for r in records.clone() {
let header = r.ok()?.header?;
out.get_mut(n..n + header.len())?.copy_from_slice(header);
n += header.len();
}
let headers = out.get(..n)?;
Some(Format { signature: crc16(headers), headers })
}
pub fn received(signature: u16, headers: &'a [u8]) -> Option<Self> {
(crc16(headers) == signature).then_some(Self { signature, headers })
}
}
pub trait Formats {
fn headers(&self, signature: u16) -> Option<&[u8]>;
}
impl Formats for Format<'_> {
fn headers(&self, signature: u16) -> Option<&[u8]> {
(self.signature == signature).then_some(self.headers)
}
}
impl Formats for [Format<'_>] {
fn headers(&self, signature: u16) -> Option<&[u8]> {
self.iter().find_map(|f| f.headers(signature))
}
}
impl<F: Formats + ?Sized> Formats for &F {
fn headers(&self, signature: u16) -> Option<&[u8]> {
(**self).headers(signature)
}
}
#[derive(Clone, Debug)]
pub struct FormatCache<const N: usize, const B: usize> {
entries: [(u16, u8, [u8; B]); N],
used: usize,
next: usize,
}
impl<const N: usize, const B: usize> Default for FormatCache<N, B> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize, const B: usize> FormatCache<N, B> {
pub const fn new() -> Self {
Self { entries: [(0, 0, [0; B]); N], used: 0, next: 0 }
}
pub fn insert(&mut self, format: &Format<'_>) -> bool {
let len = format.headers.len();
let Ok(stored) = u8::try_from(len) else { return false };
if len > B || N == 0 {
return false;
}
if self.headers(format.signature).is_some() {
return true;
}
let Some((sig, l, bytes)) = self.entries.get_mut(self.next) else { return false };
let Some(dst) = bytes.get_mut(..len) else { return false };
dst.copy_from_slice(format.headers);
*sig = format.signature;
*l = stored;
self.next = (self.next + 1) % N;
self.used = (self.used + 1).min(N);
true
}
}
impl<const N: usize, const B: usize> Formats for FormatCache<N, B> {
fn headers(&self, signature: u16) -> Option<&[u8]> {
self.entries
.iter()
.take(self.used)
.find(|(s, ..)| *s == signature)
.and_then(|(_, l, b)| b.get(..usize::from(*l)))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Compact<'a> {
pub signature: u16,
pub crc: u16,
pub data: &'a [u8],
decrypted: bool,
}
impl Compact<'_> {
pub(crate) fn parse(bytes: &[u8], decrypted: bool) -> Result<Compact<'_>> {
let (&[s0, s1, c0, c1], data) = bytes.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
let (signature, crc) = (u16::from_le_bytes([s0, s1]), u16::from_le_bytes([c0, c1]));
Ok(Compact { signature, crc, data, decrypted })
}
pub fn expand<'o, F: Formats + ?Sized>(&self, formats: &F, out: &'o mut [u8]) -> Result<Records<'o>> {
let headers = formats.headers(self.signature).ok_or(Error::UnknownFormat(self.signature))?;
let mut h = 0usize; let mut d = 0usize; let mut n = 0usize; let mut put = |bytes: &[u8], n: &mut usize| -> Result<()> {
out.get_mut(*n..*n + bytes.len()).ok_or(Error::OutputTooSmall)?.copy_from_slice(bytes);
*n += bytes.len();
Ok(())
};
while h < headers.len() {
let start = h;
let dif = *headers.get(h).ok_or(Error::UnexpectedEnd)?;
h += 1;
if dif & 0x0F == 0x0F {
return Err(Error::InvalidFormat);
}
let mut ext = dif & 0x80 != 0;
while ext {
ext = headers.get(h).ok_or(Error::UnexpectedEnd)? & 0x80 != 0;
h += 1;
}
let vif = *headers.get(h).ok_or(Error::UnexpectedEnd)?;
h += 1;
if vif & 0x7F == 0x7C {
return Err(Error::InvalidFormat);
}
let mut ext = vif & 0x80 != 0;
while ext {
ext = headers.get(h).ok_or(Error::UnexpectedEnd)? & 0x80 != 0;
h += 1;
}
put(headers.get(start..h).ok_or(Error::UnexpectedEnd)?, &mut n)?;
let len = match DataField::from_nibble(dif) {
DataField::None | DataField::Selection => 0,
DataField::Int(k) | DataField::Bcd(k) => usize::from(k),
DataField::Real32 => 4,
DataField::Variable => {
1 + crate::record::lvar_len(*self.data.get(d).ok_or(Error::UnexpectedEnd)?)?
}
};
put(self.data.get(d..d + len).ok_or(Error::UnexpectedEnd)?, &mut n)?;
d += len;
}
let full = out.get(..n).ok_or(Error::OutputTooSmall)?;
if d != self.data.len() || crc16(full) != self.crc {
return Err(Error::Verification(Check::FullFrameCrc));
}
Ok(if self.decrypted { Records::decrypted(full, full.len()) } else { Records::new(full) })
}
}