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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use tokio_util::codec::{Decoder, Encoder};
use bytes::{BytesMut, BufMut};
use std::io::{Error, ErrorKind};


#[allow(unused_imports)]
use futures::sink::SinkExt;


fn check(left: usize, right: usize, data: &[u8]) -> Result<(), Error> {
    if let Ok(num_string) = String::from_utf8(Vec::from(&data[..left])) {
        if let Ok(exp_size) = num_string.parse::<usize>() {
            if right > left && (right - 1) - left == exp_size {
                return Ok(());
            }
        }
    }
    Err(Error::new(ErrorKind::InvalidData, "Invalid data"))
}


fn extract_frameborders(src: &BytesMut) -> Option<(usize, usize)> {
    let left_idx = src.iter().position(|&b| b == b':');
    let right_idx = src.iter().position(|&b| b == b',');

    match (left_idx, right_idx) {
        (Some(l), Some(r)) => Some((l, r)),
        _ => None
    }
}

pub struct NetStringCodec {}

impl NetStringCodec {
    pub fn extract_frame(&self, src: &mut BytesMut) -> Result<Option<String>, Box<dyn std::error::Error>> {
        if let Some((lhs, rhs)) = extract_frameborders(src) {
            check(lhs, rhs, src)?;
            let data = src.split_to(rhs + 1); // <- modify src
            let data = String::from_utf8(Vec::from(&data[lhs + 1..rhs]))?;
            return Ok(Some(data));
        }
        Ok(None)
    }
}

impl Decoder for NetStringCodec {
    type Item = String;
    type Error = Error;

    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        println!("Trying to decode {:?}", src);

        match self.extract_frame(src) {
            Ok(frame) => Ok(frame),
            Err(_) => Err(Error::new(ErrorKind::InvalidData, "Could not parse data"))
        }
    }
}


impl Encoder<String> for NetStringCodec {
    type Error = std::io::Error;

    fn encode(&mut self, item: String, dst: &mut BytesMut) -> Result<(), Self::Error> {
        let data = format!("{}:{},", item.len(), item);
        dst.put(data.as_bytes());
        Ok(())
    }
}