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
use crate::{Packet, PacketParseError};
use bytes::BytesMut;
use std::io::{self, Cursor};
use tokio_util::codec::{Decoder, Encoder};

pub struct PacketCodec;

impl Decoder for PacketCodec {
    type Item = Packet;
    type Error = PacketParseError;

    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Packet>, Self::Error> {
        Packet::parse(&mut Cursor::new(buf)).map(Some)
    }
}

impl Encoder for PacketCodec {
    type Item = Packet;
    type Error = io::Error;

    fn encode(&mut self, packet: Packet, buf: &mut BytesMut) -> Result<(), Self::Error> {
        packet.serialize(buf);

        Ok(())
    }
}