1use crate::crc::crc16;
19use crate::record::{DataField, Records};
20use crate::{Check, Error, Result};
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub struct Format<'a> {
25 pub signature: u16,
27 pub headers: &'a [u8],
29}
30
31impl<'a> Format<'a> {
32 pub fn of<'o>(records: &Records<'_>, out: &'o mut [u8]) -> Option<Format<'o>> {
36 let mut n = 0usize;
37 for r in records.clone() {
38 let header = r.ok()?.header?;
39 out.get_mut(n..n + header.len())?.copy_from_slice(header);
40 n += header.len();
41 }
42 let headers = out.get(..n)?;
43 Some(Format { signature: crc16(headers), headers })
44 }
45
46 pub fn received(signature: u16, headers: &'a [u8]) -> Option<Self> {
49 (crc16(headers) == signature).then_some(Self { signature, headers })
50 }
51}
52
53pub trait Formats {
63 fn headers(&self, signature: u16) -> Option<&[u8]>;
65}
66
67impl Formats for Format<'_> {
68 fn headers(&self, signature: u16) -> Option<&[u8]> {
69 (self.signature == signature).then_some(self.headers)
70 }
71}
72
73impl Formats for [Format<'_>] {
74 fn headers(&self, signature: u16) -> Option<&[u8]> {
75 self.iter().find_map(|f| f.headers(signature))
76 }
77}
78
79impl<F: Formats + ?Sized> Formats for &F {
80 fn headers(&self, signature: u16) -> Option<&[u8]> {
81 (**self).headers(signature)
82 }
83}
84
85#[derive(Clone, Debug)]
88pub struct FormatCache<const N: usize, const B: usize> {
89 entries: [(u16, u8, [u8; B]); N],
90 used: usize,
91 next: usize,
92}
93
94impl<const N: usize, const B: usize> Default for FormatCache<N, B> {
95 fn default() -> Self {
96 Self::new()
97 }
98}
99
100impl<const N: usize, const B: usize> FormatCache<N, B> {
101 pub const fn new() -> Self {
103 Self { entries: [(0, 0, [0; B]); N], used: 0, next: 0 }
104 }
105
106 pub fn insert(&mut self, format: &Format<'_>) -> bool {
109 let len = format.headers.len();
110 let Ok(stored) = u8::try_from(len) else { return false };
111 if len > B || N == 0 {
112 return false;
113 }
114 if self.headers(format.signature).is_some() {
115 return true;
116 }
117 let Some((sig, l, bytes)) = self.entries.get_mut(self.next) else { return false };
118 let Some(dst) = bytes.get_mut(..len) else { return false };
119 dst.copy_from_slice(format.headers);
120 *sig = format.signature;
121 *l = stored;
122 self.next = (self.next + 1) % N;
123 self.used = (self.used + 1).min(N);
124 true
125 }
126}
127
128impl<const N: usize, const B: usize> Formats for FormatCache<N, B> {
129 fn headers(&self, signature: u16) -> Option<&[u8]> {
130 self.entries
131 .iter()
132 .take(self.used)
133 .find(|(s, ..)| *s == signature)
134 .and_then(|(_, l, b)| b.get(..usize::from(*l)))
135 }
136}
137
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub struct Compact<'a> {
141 pub signature: u16,
143 pub crc: u16,
145 pub data: &'a [u8],
147 decrypted: bool,
149}
150
151impl Compact<'_> {
152 pub(crate) fn parse(bytes: &[u8], decrypted: bool) -> Result<Compact<'_>> {
153 let (&[s0, s1, c0, c1], data) = bytes.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
154 let (signature, crc) = (u16::from_le_bytes([s0, s1]), u16::from_le_bytes([c0, c1]));
155 Ok(Compact { signature, crc, data, decrypted })
156 }
157
158 pub fn expand<'o, F: Formats + ?Sized>(&self, formats: &F, out: &'o mut [u8]) -> Result<Records<'o>> {
162 let headers = formats.headers(self.signature).ok_or(Error::UnknownFormat(self.signature))?;
163 let mut h = 0usize; let mut d = 0usize; let mut n = 0usize; let mut put = |bytes: &[u8], n: &mut usize| -> Result<()> {
167 out.get_mut(*n..*n + bytes.len()).ok_or(Error::OutputTooSmall)?.copy_from_slice(bytes);
168 *n += bytes.len();
169 Ok(())
170 };
171 while h < headers.len() {
172 let start = h;
173 let dif = *headers.get(h).ok_or(Error::UnexpectedEnd)?;
174 h += 1;
175 if dif & 0x0F == 0x0F {
176 return Err(Error::InvalidFormat);
178 }
179 let mut ext = dif & 0x80 != 0;
180 while ext {
181 ext = headers.get(h).ok_or(Error::UnexpectedEnd)? & 0x80 != 0;
182 h += 1;
183 }
184 let vif = *headers.get(h).ok_or(Error::UnexpectedEnd)?;
185 h += 1;
186 if vif & 0x7F == 0x7C {
187 return Err(Error::InvalidFormat);
189 }
190 let mut ext = vif & 0x80 != 0;
191 while ext {
192 ext = headers.get(h).ok_or(Error::UnexpectedEnd)? & 0x80 != 0;
193 h += 1;
194 }
195 put(headers.get(start..h).ok_or(Error::UnexpectedEnd)?, &mut n)?;
196 let len = match DataField::from_nibble(dif) {
197 DataField::None | DataField::Selection => 0,
198 DataField::Int(k) | DataField::Bcd(k) => usize::from(k),
199 DataField::Real32 => 4,
200 DataField::Variable => {
201 1 + crate::record::lvar_len(*self.data.get(d).ok_or(Error::UnexpectedEnd)?)?
202 }
203 };
204 put(self.data.get(d..d + len).ok_or(Error::UnexpectedEnd)?, &mut n)?;
205 d += len;
206 }
207 let full = out.get(..n).ok_or(Error::OutputTooSmall)?;
208 if d != self.data.len() || crc16(full) != self.crc {
209 return Err(Error::Verification(Check::FullFrameCrc));
210 }
211 Ok(if self.decrypted { Records::decrypted(full, full.len()) } else { Records::new(full) })
212 }
213}