1pub const FLAG: u8 = 0xF9;
9
10pub const SABM: u8 = 0x2F;
12pub const UA: u8 = 0x63;
13pub const DM: u8 = 0x0F;
14pub const DISC: u8 = 0x43;
15pub const UIH: u8 = 0xEF;
16pub const UI: u8 = 0x03;
17pub const PF: u8 = 0x10;
18
19pub const MAX_INFO: usize = 32_767;
22pub const DEFAULT_MAX_RX_INFO: usize = 1_509;
27pub const TX_N1: usize = 31;
31
32const fn crc_table() -> [u8; 256] {
33 let mut table = [0u8; 256];
34 let mut i = 0;
35 while i < 256 {
36 let mut crc = i as u8;
37 let mut bit = 0;
38 while bit < 8 {
39 crc = if crc & 1 != 0 {
40 (crc >> 1) ^ 0xE0
41 } else {
42 crc >> 1
43 };
44 bit += 1;
45 }
46 table[i] = crc;
47 i += 1;
48 }
49 table
50}
51
52static CRC_TABLE: [u8; 256] = crc_table();
53
54pub fn fcs(bytes: &[u8]) -> u8 {
55 let crc = bytes
56 .iter()
57 .fold(0xFFu8, |crc, &b| CRC_TABLE[(crc ^ b) as usize]);
58 0xFF - crc
59}
60
61pub fn encode_address(dlci: u8, cr: bool) -> u8 {
62 ((dlci & 0x3F) << 2) | (u8::from(cr) << 1) | 0x01
63}
64
65pub fn decode_address(addr: u8) -> (u8, bool) {
66 ((addr >> 2) & 0x3F, addr & 0x02 != 0)
67}
68
69pub fn encode_frame(dlci: u8, cr: bool, control: u8, info: &[u8]) -> Vec<u8> {
74 assert!(info.len() <= MAX_INFO, "cmux info field too long");
75 let mut header = vec![encode_address(dlci, cr), control];
76 let len = info.len();
77 if len <= 127 {
78 header.push(((len as u8) << 1) | 0x01);
79 } else {
80 header.push(((len & 0x7F) as u8) << 1);
81 header.push((len >> 7) as u8);
82 }
83 let check = if control & !PF == UI {
84 fcs(&[header.as_slice(), info].concat())
85 } else {
86 fcs(&header)
87 };
88 let mut frame = Vec::with_capacity(header.len() + len + 3);
89 frame.push(FLAG);
90 frame.extend_from_slice(&header);
91 frame.extend_from_slice(info);
92 frame.push(check);
93 frame.push(FLAG);
94 frame
95}
96
97pub fn encode_uih(dlci: u8, payload: &[u8]) -> Vec<u8> {
99 if payload.is_empty() {
100 return encode_frame(dlci, true, UIH, &[]);
101 }
102 payload
103 .chunks(TX_N1)
104 .flat_map(|chunk| encode_frame(dlci, true, UIH, chunk))
105 .collect()
106}
107
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct DecodedFrame {
110 pub dlci: u8,
111 pub cr: bool,
113 pub kind: u8,
115 pub payload: Vec<u8>,
116}
117
118pub struct Deframer {
120 buf: Vec<u8>,
121 max_info: usize,
122}
123
124impl Default for Deframer {
125 fn default() -> Self {
126 Self::with_max_info(DEFAULT_MAX_RX_INFO)
127 }
128}
129
130impl Deframer {
131 pub fn with_max_info(max_info: usize) -> Self {
134 Self {
135 buf: Vec::new(),
136 max_info: max_info.clamp(1, MAX_INFO),
137 }
138 }
139
140 pub fn feed(&mut self, chunk: &[u8]) -> Vec<DecodedFrame> {
141 self.buf.extend_from_slice(chunk);
142 let mut out = Vec::new();
143 let mut pos = 0;
145 loop {
146 match self.buf[pos..].iter().position(|&b| b == FLAG) {
148 Some(i) => pos += i,
149 None => {
150 pos = self.buf.len();
151 break;
152 }
153 }
154 let flags = self.buf[pos..].iter().take_while(|&&b| b == FLAG).count();
156 pos += flags - 1;
157 match self.parse_one(pos) {
158 Parse::Need => break,
159 Parse::Bad => pos += 1,
161 Parse::Frame(frame, used) => {
162 pos += used - 1;
164 out.push(frame);
165 }
166 }
167 }
168 self.buf.drain(..pos);
169 out
170 }
171
172 fn parse_one(&self, pos: usize) -> Parse {
173 let b = &self.buf[pos..];
174 let [_, addr, control, len0, ..] = *b else {
175 return Parse::Need;
176 };
177 if addr & 0x01 == 0 {
178 return Parse::Bad;
179 }
180 let (len, len_octets) = if len0 & 0x01 != 0 {
181 ((len0 >> 1) as usize, 1)
182 } else {
183 let Some(&len1) = b.get(4) else {
184 return Parse::Need;
185 };
186 (((len0 >> 1) as usize) | ((len1 as usize) << 7), 2)
187 };
188 if len > self.max_info {
189 return Parse::Bad;
190 }
191 let header_end = 3 + len_octets;
192 let total = header_end + len + 2; if b.len() < total {
194 return Parse::Need;
195 }
196 let info = &b[header_end..header_end + len];
197 let kind = control & !PF;
198 let expected = if kind == UI {
199 fcs(&b[1..header_end + len])
200 } else {
201 fcs(&b[1..header_end])
202 };
203 if b[header_end + len] != expected || b[total - 1] != FLAG {
204 return Parse::Bad;
205 }
206 let (dlci, cr) = decode_address(addr);
207 Parse::Frame(
208 DecodedFrame {
209 dlci,
210 cr,
211 kind,
212 payload: info.to_vec(),
213 },
214 total,
215 )
216 }
217}
218
219enum Parse {
220 Need,
221 Bad,
222 Frame(DecodedFrame, usize),
223}