Skip to content

Commit

Permalink
refine TunPacketCodec
Browse files Browse the repository at this point in the history
  • Loading branch information
ssrlive committed Jan 11, 2024
1 parent e944758 commit b67bb65
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions src/async/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

use std::io;

use byteorder::{NativeEndian, NetworkEndian, WriteBytesExt};
use bytes::{BufMut, Bytes, BytesMut};
use tokio_util::codec::{Decoder, Encoder};

Expand Down Expand Up @@ -54,6 +53,7 @@ impl PacketProtocol {
}

#[cfg(target_os = "windows")]
#[allow(dead_code)]
fn into_pi_field(self) -> Result<u16, io::Error> {
unimplemented!()
}
Expand Down Expand Up @@ -134,17 +134,22 @@ impl Encoder<TunPacket> for TunPacketCodec {
fn encode(&mut self, item: TunPacket, dst: &mut BytesMut) -> Result<(), Self::Error> {
dst.reserve(item.get_bytes().len() + 4);
match item {
TunPacket(proto, bytes) if self.0 => {
// build the packet information header comprising of 2 u16
// fields: flags and protocol.
let mut buf = Vec::<u8>::with_capacity(4);

// flags is always 0
buf.write_u16::<NativeEndian>(0)?;
// write the protocol as network byte order
buf.write_u16::<NetworkEndian>(proto.into_pi_field()?)?;

dst.put_slice(&buf);
TunPacket(_proto, bytes) if self.0 => {
#[cfg(unix)]
{
use byteorder::{NativeEndian, NetworkEndian, WriteBytesExt};

// build the packet information header comprising of 2 u16
// fields: flags and protocol.
let mut buf = Vec::<u8>::with_capacity(4);

// flags is always 0
buf.write_u16::<NativeEndian>(0)?;
// write the protocol as network byte order
buf.write_u16::<NetworkEndian>(_proto.into_pi_field()?)?;

dst.put_slice(&buf);
}
dst.put(bytes);
}
TunPacket(_, bytes) => dst.put(bytes),
Expand Down

0 comments on commit b67bb65

Please sign in to comment.