1use std::{error::Error, fmt::Display};
2
3use log::{debug, warn};
4
5#[derive(Debug, Clone)]
6pub struct Frame {
7 content: Vec<u8>,
8}
9
10impl Frame {
11 pub fn new(content: Vec<u8>) -> Self {
12 Self { content }
13 }
14
15 pub fn parse_sequence(seq: &[u8], existing: Option<Vec<u8>>) -> (Vec<Frame>, Vec<u8>) {
16 let mut parsed = vec![];
17
18 let mut byte_cache: Vec<u8> = vec![];
19 let mut temp: Vec<u8> = vec![];
20 if let Some(existing) = existing {
21 existing.iter().for_each(|u| {
22 temp.push(*u);
23 });
24 }
25 for ch in seq {
26 if *ch == 0x7e {
27 if temp.len() > 0 {
28 if let Ok(frame) = Self::parse(&temp) {
30 debug!(target: "atc-frame", "Parsed frame: `{}`", frame);
31 parsed.push(frame);
32 } else {
33 warn!(target: "atc-frame", "Unable to parse sequence: `{:?}`", temp);
34 }
35 temp.clear()
36 }
37 } else if *ch == 0x7d {
38 byte_cache.push(0x7d);
40 } else if *ch == 0x5d {
41 if let Some(byte) = byte_cache.last() {
42 if *byte == 0x7d {
43 temp.push(0x7d);
44 byte_cache.clear();
45 }
46 }
47 } else if *ch == 0x5e {
48 if let Some(byte) = byte_cache.last() {
49 if *byte == 0x7d {
50 temp.push(0x7e);
51 byte_cache.clear();
52 }
53 }
54 } else {
55 temp.push(*ch);
56 }
57 }
58 if temp.len() > 0 {
59 if let Ok(frame) = Frame::parse(&temp) {
60 debug!(target: "atc-frame", "Parsed frame: `{}`", frame);
61 parsed.push(frame);
62 temp.clear();
63 }
64 }
65 (parsed, temp.iter().map(|c| *c as u8).collect::<Vec<u8>>())
66 }
67
68 fn parse(temp: &Vec<u8>) -> Result<Frame, Box<dyn Error>> {
69 Ok(Frame::new(temp.clone()))
70 }
71}
72
73impl From<String> for Frame {
74 fn from(value: String) -> Self {
75 Self {
76 content: value.as_bytes().to_vec(),
77 }
78 }
79}
80
81impl From<&str> for Frame {
82 fn from(value: &str) -> Self {
83 Self {
84 content: value.as_bytes().to_vec(),
85 }
86 }
87}
88
89impl Display for Frame {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 write!(
92 f,
93 "Frame<{}>",
94 String::from_utf8(self.content.clone()).unwrap()
95 )
96 }
97}
98
99impl Into<Vec<u8>> for Frame {
100 fn into(self) -> Vec<u8> {
101 let mut ret: Vec<u8> = vec![0x7e];
102 self.content.iter().for_each(|u| {
103 if *u == 0x7e {
104 ret.push(0x7d);
105 ret.push(0x5e);
106 } else if *u == 0x7d {
107 ret.push(0x7d);
108 ret.push(0x5d);
109 } else {
110 ret.push(*u)
111 }
112 });
113
114 ret
115 }
116}
117
118impl Into<String> for Frame {
119 fn into(self) -> String {
120 String::from_utf8(self.content).unwrap()
121 }
122}