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
71
72
73
74
75
use crate::{Decoder, Encoder};
use bytes::{Bytes, BytesMut};
use std::io::Error;
pub struct BytesCodec {}
impl Decoder for BytesCodec {
type Item = Bytes;
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let len = src.len();
if len > 0 {
Ok(Some(src.split_to(len).freeze()))
} else {
Ok(None)
}
}
}
impl Encoder for BytesCodec {
type Item = Bytes;
type Error = Error;
fn encode(&mut self, src: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
dst.extend_from_slice(&src);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::BytesCodec;
use crate::Framed;
use futures::{executor, TryStreamExt};
use std::io::Cursor;
#[test]
fn decodes() {
let mut buf = [0u8; 32];
let expected = buf.clone();
let cur = Cursor::new(&mut buf);
let mut framed = Framed::new(cur, BytesCodec {});
let read = executor::block_on(framed.try_next()).unwrap().unwrap();
assert_eq!(&read[..], &expected[..]);
assert!(executor::block_on(framed.try_next()).unwrap().is_none());
}
}