chiark / gitweb /
drop empty frames before xmit
[hippotat.git] / src / slip.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use crate::prelude::*;
6
7 pub static SLIP_END_SLICE: &[u8] = &[SLIP_END];
8
9 #[throws(AE)]
10 pub fn check_checkmtu_mimeswap<const TO_MIME: bool>
11   (ic: &InstanceConfig, data: &mut [u8])
12 {
13   for mut packet in data.split_mut(|&c| c == SLIP_END) {
14     if packet.len() > ic.mtu.sat() {
15       throw!(anyhow!("mtu exceeded ({} > {})", packet.len(), ic.mtu));
16     }
17
18     while let Some((i, _)) = packet.iter().enumerate().find(
19       |(_,&c)| c == if TO_MIME { SLIP_ESC } else { SLIP_MIME_ESC }
20     ) {
21       packet[i] = if TO_MIME { SLIP_MIME_ESC } else { SLIP_ESC };
22       match packet.get(i+1) {
23         Some(&SLIP_ESC_END) |
24         Some(&SLIP_ESC_ESC) => Ok(()),
25         _ => Err(anyhow!("SLIP escape not followed by ESC_END or ESC_ESC")),
26       }?;
27       packet = &mut packet[i+2 ..];
28     }
29   }
30 }
31
32 pub type Frame = Vec<u8>;
33 pub type FramesData = Vec<Vec<u8>>;
34
35 #[derive(Default)]
36 pub struct Frames {
37   frames: FramesData,
38   total_len: usize,
39 }
40
41 impl Debug for Frames {
42   #[throws(fmt::Error)]
43   fn fmt(&self, f: &mut fmt::Formatter) {
44     write!(f, "Frames{{n={},len={}}}", &self.frames.len(), &self.total_len)?;
45   }
46 }
47
48 impl Frames {
49   #[throws(Frame)]
50   pub fn add(&mut self, max: u32, frame: Frame) {
51     if frame.len() == 0 { return }
52     let new_total = self.total_len + frame.len() + 1;
53     if new_total > max.sat() { throw!(frame) }
54     self.total_len = new_total;
55     self.frames.push(frame);
56   }
57 }
58
59 impl From<Frames> for FramesData {
60   fn from(frames: Frames) -> FramesData { frames.frames }
61 }