karyon_net/codec/
length_codec.rs

1use karyon_core::util::{decode, encode_into_slice};
2
3use crate::{
4    codec::{ByteBuffer, Codec, Decoder, Encoder},
5    Error, Result,
6};
7
8/// The size of the message length.
9const MSG_LENGTH_SIZE: usize = std::mem::size_of::<u32>();
10
11#[derive(Clone)]
12pub struct LengthCodec {}
13impl Codec for LengthCodec {
14    type Message = Vec<u8>;
15    type Error = Error;
16}
17
18impl Encoder for LengthCodec {
19    type EnMessage = Vec<u8>;
20    type EnError = Error;
21    fn encode(&self, src: &Self::EnMessage, dst: &mut ByteBuffer) -> Result<usize> {
22        let length_buf = &mut [0; MSG_LENGTH_SIZE];
23        encode_into_slice(&(src.len() as u32), length_buf)?;
24
25        dst.resize(MSG_LENGTH_SIZE);
26        dst.extend_from_slice(length_buf);
27
28        dst.resize(src.len());
29        dst.extend_from_slice(src);
30
31        Ok(dst.len())
32    }
33}
34
35impl Decoder for LengthCodec {
36    type DeMessage = Vec<u8>;
37    type DeError = Error;
38    fn decode(&self, src: &mut ByteBuffer) -> Result<Option<(usize, Self::DeMessage)>> {
39        if src.len() < MSG_LENGTH_SIZE {
40            return Ok(None);
41        }
42
43        let mut length = [0; MSG_LENGTH_SIZE];
44        length.copy_from_slice(&src.as_ref()[..MSG_LENGTH_SIZE]);
45        let (length, _) = decode::<u32>(&length)?;
46        let length = length as usize;
47
48        if src.len() - MSG_LENGTH_SIZE >= length {
49            Ok(Some((
50                length + MSG_LENGTH_SIZE,
51                src.as_ref()[MSG_LENGTH_SIZE..length + MSG_LENGTH_SIZE].to_vec(),
52            )))
53        } else {
54            Ok(None)
55        }
56    }
57}