aboutsummaryrefslogtreecommitdiff
path: root/net/src/codec/bytes_codec.rs
blob: b319e53705969e718ec0000ebde590e7b30905b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use crate::{
    codec::{Codec, Decoder, Encoder},
    Result,
};

#[derive(Clone)]
pub struct BytesCodec {}
impl Codec for BytesCodec {
    type Item = Vec<u8>;
}

impl Encoder for BytesCodec {
    type EnItem = Vec<u8>;
    fn encode(&self, src: &Self::EnItem, dst: &mut [u8]) -> Result<usize> {
        dst[..src.len()].copy_from_slice(src);
        Ok(src.len())
    }
}

impl Decoder for BytesCodec {
    type DeItem = Vec<u8>;
    fn decode(&self, src: &mut [u8]) -> Result<Option<(usize, Self::DeItem)>> {
        if src.is_empty() {
            Ok(None)
        } else {
            Ok(Some((src.len(), src.to_vec())))
        }
    }
}