use karyon_core::util::{decode, encode_into_slice}; use crate::{ codec::{Codec, Decoder, Encoder}, Result, }; /// The size of the message length. const MSG_LENGTH_SIZE: usize = std::mem::size_of::(); #[derive(Clone)] pub struct LengthCodec {} impl Codec for LengthCodec { type Item = Vec; } impl Encoder for LengthCodec { type EnItem = Vec; fn encode(&self, src: &Self::EnItem, dst: &mut [u8]) -> Result { let length_buf = &mut [0; MSG_LENGTH_SIZE]; encode_into_slice(&(src.len() as u32), length_buf)?; dst[..MSG_LENGTH_SIZE].copy_from_slice(length_buf); dst[MSG_LENGTH_SIZE..src.len() + MSG_LENGTH_SIZE].copy_from_slice(src); Ok(src.len() + MSG_LENGTH_SIZE) } } impl Decoder for LengthCodec { type DeItem = Vec; fn decode(&self, src: &mut [u8]) -> Result> { if src.len() < MSG_LENGTH_SIZE { return Ok(None); } let mut length = [0; MSG_LENGTH_SIZE]; length.copy_from_slice(&src[..MSG_LENGTH_SIZE]); let (length, _) = decode::(&length)?; let length = length as usize; if src.len() - MSG_LENGTH_SIZE >= length { Ok(Some(( length + MSG_LENGTH_SIZE, src[MSG_LENGTH_SIZE..length + MSG_LENGTH_SIZE].to_vec(), ))) } else { Ok(None) } } }