1use crate::app::Authenticity;
19use crate::crc::crc16;
20use crate::record::{DataField, Records};
21use crate::{Check, Error, Result};
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub struct Format<'a> {
26 pub signature: u16,
28 pub headers: &'a [u8],
30}
31
32impl<'a> Format<'a> {
33 pub fn of<'o>(records: &Records<'_>, out: &'o mut [u8]) -> Option<Format<'o>> {
37 let mut n = 0usize;
38 for r in records.clone() {
39 let header = r.ok()?.header?;
40 out.get_mut(n..n + header.len())?.copy_from_slice(header);
41 n += header.len();
42 }
43 let headers = out.get(..n)?;
44 Some(Format { signature: crc16(headers), headers })
45 }
46
47 pub fn received(signature: u16, headers: &'a [u8]) -> Option<Self> {
50 (crc16(headers) == signature).then_some(Self { signature, headers })
51 }
52}
53
54pub trait Formats {
64 fn headers(&self, signature: u16) -> Option<&[u8]>;
66}
67
68impl Formats for Format<'_> {
69 fn headers(&self, signature: u16) -> Option<&[u8]> {
70 (self.signature == signature).then_some(self.headers)
71 }
72}
73
74impl Formats for [Format<'_>] {
75 fn headers(&self, signature: u16) -> Option<&[u8]> {
76 self.iter().find_map(|f| f.headers(signature))
77 }
78}
79
80impl<F: Formats + ?Sized> Formats for &F {
81 fn headers(&self, signature: u16) -> Option<&[u8]> {
82 (**self).headers(signature)
83 }
84}
85
86#[derive(Clone, Debug)]
89pub struct FormatCache<const N: usize, const B: usize> {
90 entries: [(u16, u8, [u8; B]); N],
91 used: usize,
92 next: usize,
93}
94
95impl<const N: usize, const B: usize> Default for FormatCache<N, B> {
96 fn default() -> Self {
97 Self::new()
98 }
99}
100
101impl<const N: usize, const B: usize> FormatCache<N, B> {
102 pub const fn new() -> Self {
104 Self { entries: [(0, 0, [0; B]); N], used: 0, next: 0 }
105 }
106
107 pub fn insert(&mut self, format: &Format<'_>) -> bool {
110 let len = format.headers.len();
111 let Ok(stored) = u8::try_from(len) else { return false };
112 if len > B || N == 0 {
113 return false;
114 }
115 if self.headers(format.signature).is_some() {
116 return true;
117 }
118 let Some((sig, l, bytes)) = self.entries.get_mut(self.next) else { return false };
119 let Some(dst) = bytes.get_mut(..len) else { return false };
120 dst.copy_from_slice(format.headers);
121 *sig = format.signature;
122 *l = stored;
123 self.next = (self.next + 1) % N;
124 self.used = (self.used + 1).min(N);
125 true
126 }
127}
128
129impl<const N: usize, const B: usize> Formats for FormatCache<N, B> {
130 fn headers(&self, signature: u16) -> Option<&[u8]> {
131 self.entries
132 .iter()
133 .take(self.used)
134 .find(|(s, ..)| *s == signature)
135 .and_then(|(_, l, b)| b.get(..usize::from(*l)))
136 }
137}
138
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub struct Compact<'a> {
142 pub signature: u16,
144 pub crc: u16,
146 pub data: &'a [u8],
148 decrypted: bool,
150}
151
152impl Compact<'_> {
153 pub(crate) fn parse(bytes: &[u8], decrypted: bool) -> Result<Compact<'_>> {
154 let (&[s0, s1, c0, c1], data) = bytes.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
155 let (signature, crc) = (u16::from_le_bytes([s0, s1]), u16::from_le_bytes([c0, c1]));
156 Ok(Compact { signature, crc, data, decrypted })
157 }
158
159 pub fn expand<'o, F: Formats + ?Sized>(&self, formats: &F, out: &'o mut [u8]) -> Result<Records<'o>> {
163 let headers = formats.headers(self.signature).ok_or(Error::UnknownFormat(self.signature))?;
164 let mut h = 0usize; let mut d = 0usize; let mut n = 0usize; let mut put = |bytes: &[u8], n: &mut usize| -> Result<()> {
168 out.get_mut(*n..*n + bytes.len()).ok_or(Error::OutputTooSmall)?.copy_from_slice(bytes);
169 *n += bytes.len();
170 Ok(())
171 };
172 while h < headers.len() {
173 let start = h;
174 let dif = *headers.get(h).ok_or(Error::UnexpectedEnd)?;
175 h += 1;
176 if dif & 0x0F == 0x0F {
177 return Err(Error::InvalidFormat);
179 }
180 let mut ext = dif & 0x80 != 0;
181 while ext {
182 ext = headers.get(h).ok_or(Error::UnexpectedEnd)? & 0x80 != 0;
183 h += 1;
184 }
185 let vif = *headers.get(h).ok_or(Error::UnexpectedEnd)?;
186 h += 1;
187 if vif & 0x7F == 0x7C {
188 return Err(Error::InvalidFormat);
190 }
191 let mut ext = vif & 0x80 != 0;
192 while ext {
193 ext = headers.get(h).ok_or(Error::UnexpectedEnd)? & 0x80 != 0;
194 h += 1;
195 }
196 put(headers.get(start..h).ok_or(Error::UnexpectedEnd)?, &mut n)?;
197 let len = match DataField::from_nibble(dif) {
198 DataField::None | DataField::Selection => 0,
199 DataField::Int(k) | DataField::Bcd(k) => usize::from(k),
200 DataField::Real32 => 4,
201 DataField::Variable => {
202 1 + crate::record::lvar_len(*self.data.get(d).ok_or(Error::UnexpectedEnd)?)?
203 }
204 };
205 put(self.data.get(d..d + len).ok_or(Error::UnexpectedEnd)?, &mut n)?;
206 d += len;
207 }
208 let full = out.get(..n).ok_or(Error::OutputTooSmall)?;
209 if d != self.data.len() || crc16(full) != self.crc {
210 return Err(Error::Verification(Check::FullFrameCrc));
211 }
212 Ok(if self.decrypted {
214 Records::protected(full, full.len(), Authenticity::Encrypted, Authenticity::Encrypted)
215 } else {
216 Records::new(full)
217 })
218 }
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 #[test]
226 fn expanded_records_keep_the_frames_authenticity() {
227 let full = [0x04, 0x13, 0x01, 0x02, 0x03, 0x04];
230 let mut layout = [0u8; 8];
231 let format = Format::of(&Records::new(&full), &mut layout).unwrap();
232 let [s0, s1] = format.signature.to_le_bytes();
233 let [c0, c1] = crc16(&full).to_le_bytes();
234 let bytes = [s0, s1, c0, c1, 0x01, 0x02, 0x03, 0x04];
235 for (decrypted, expected) in [(true, Authenticity::Encrypted), (false, Authenticity::None)] {
236 let mut out = [0u8; 16];
237 let mut records = Compact::parse(&bytes, decrypted).unwrap().expand(&format, &mut out).unwrap();
238 assert_eq!(records.next().unwrap().unwrap().authenticity, expected);
239 }
240 }
241}