use crate::protocol::ipv4::{self}; use bytes::{Buf, BytesMut}; use std::io; use tokio_util::codec::Decoder; use tokio_util::codec::Encoder; /****************************************************************************** * Encoder/Decoder trait ******************************************************************************/ #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Default)] pub struct IPv4Codec(C); impl IPv4Codec { pub fn new(c: C) -> Self { IPv4Codec(c) } } impl Decoder for IPv4Codec where C: Decoder, std::io::Error: From<::Error>, { type Item = C::Item; type Error = io::Error; fn decode(&mut self, data: &mut BytesMut) -> Result, io::Error> { println!("IPv4Codec -> decode(), handle data len: {}", data.len()); if data.len() < 20 { println!("IPv4Codec decode: no enough data"); return Ok(None); } else { let parsed_ipv4 = ipv4::parse_ipv4(data); if let Ok((ipv4_payload, ipv4_header)) = parsed_ipv4 { println!("{:?}, Payload: {}", ipv4_header, ipv4_payload.len()); // Skip the 20-byte length. data.advance(20); let decoded = self.0.decode(data)?; match decoded { None => { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, format!(" IPv4 Frame of length {} is too large.", 111), )); } Some(inner) => Ok(Some(inner)), } } else { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, format!("Invalid ipv4 frame"), )); } } } } impl Encoder for IPv4Codec where C: Encoder, std::io::Error: From, { type Error = io::Error; fn encode(&mut self, _item: T, _buf: &mut BytesMut) -> Result<(), io::Error> { // TODO Ok(()) } }