tun/async/
codec.rs

1//            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
2//                    Version 2, December 2004
3//
4// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
5//
6// Everyone is permitted to copy and distribute verbatim or modified
7// copies of this license document, and changing it is allowed as long
8// as the name is changed.
9//
10//            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
11//   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
12//
13//  0. You just DO WHAT THE FUCK YOU WANT TO.
14use bytes::{BufMut, BytesMut};
15use tokio_util::codec::{Decoder, Encoder};
16
17/// A TUN packet Encoder/Decoder.
18#[derive(Debug, Default)]
19pub struct TunPacketCodec(usize);
20
21impl TunPacketCodec {
22    /// Create a new `TunPacketCodec` specifying whether the underlying
23    ///  tunnel Device has enabled the packet information header.
24    pub fn new(mtu: usize) -> TunPacketCodec {
25        TunPacketCodec(mtu)
26    }
27}
28
29impl Decoder for TunPacketCodec {
30    type Item = Vec<u8>;
31    type Error = std::io::Error;
32
33    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
34        if buf.is_empty() {
35            return Ok(None);
36        }
37        let pkt = buf.split_to(buf.len());
38        //reserve enough space for the next packet
39        buf.reserve(self.0);
40        Ok(Some(pkt.freeze().to_vec()))
41    }
42}
43
44impl Encoder<Vec<u8>> for TunPacketCodec {
45    type Error = std::io::Error;
46
47    fn encode(&mut self, item: Vec<u8>, dst: &mut BytesMut) -> Result<(), Self::Error> {
48        let bytes = item.as_slice();
49        dst.reserve(bytes.len());
50        dst.put(bytes);
51        Ok(())
52    }
53}