chiark / gitweb /
mimeswap
[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 }