tokio_u8_codec/
lib.rs

1//! A Tokio codec that just reads and writes u8s.
2//!
3//! This is probably not a very performant way to process streams of bytes because it only
4//! looks at one byte at a time.
5//!
6//! ```
7//! extern crate bytes;
8//! extern crate tokio_io;
9//! extern crate tokio_u8_codec;
10//!
11//! use tokio_io::codec::{Decoder, Encoder};
12//! use tokio_u8_codec::U8Codec;
13//! use bytes::BytesMut;
14//!
15//! fn main() {
16//!     let mut buf: BytesMut = Default::default();
17//!     let mut codec: U8Codec = Default::default();
18//!     codec.encode(1, &mut buf).unwrap();
19//!     codec.encode(2, &mut buf).unwrap();
20//!     assert_eq!(codec.decode(&mut buf).unwrap(), Some(1));
21//!     assert_eq!(codec.decode(&mut buf).unwrap(), Some(2));
22//!     assert_eq!(codec.decode(&mut buf).unwrap(), None);
23//! }
24//! ```
25extern crate bytes;
26extern crate tokio_io;
27
28use bytes::BytesMut;
29use tokio_io::codec::{Decoder, Encoder};
30
31
32#[derive(Debug)]
33pub enum Error {
34    Fmt(std::fmt::Error),
35    Io(std::io::Error),
36}
37
38impl From<std::io::Error> for Error {
39    fn from(e: std::io::Error) -> Self {
40        Error::Io(e)
41    }
42}
43
44#[derive(Default)]
45pub struct U8Codec {}
46
47impl Encoder for U8Codec {
48    type Item = u8;
49    type Error = Error;
50
51    fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
52        Ok(dst.extend(&[item]))
53    }
54}
55impl Decoder for U8Codec {
56    type Item = u8;
57    type Error = std::io::Error;
58
59    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
60        if src.is_empty() {
61            Ok(None)
62        } else {
63            Ok(Some(src.split_to(1)[0]))
64        }
65    }
66}