Skip to main content

ethrex_p2p/discv5/
codec.rs

1use crate::discv5::messages::{Packet, PacketCodecError};
2
3use bytes::BytesMut;
4use ethrex_common::H256;
5use std::io::{Error, ErrorKind};
6use tokio_util::codec::{Decoder, Encoder};
7
8#[derive(Debug)]
9pub struct Discv5Codec {
10    local_node_id: H256,
11}
12
13impl Discv5Codec {
14    pub fn new(local_node_id: H256) -> Self {
15        Self { local_node_id }
16    }
17}
18
19impl Decoder for Discv5Codec {
20    type Item = Packet;
21    type Error = PacketCodecError;
22
23    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
24        if !buf.is_empty() {
25            Ok(Some(Packet::decode(
26                &self.local_node_id,
27                &buf.split_to(buf.len()),
28            )?))
29        } else {
30            Ok(None)
31        }
32    }
33}
34
35impl Encoder<Packet> for Discv5Codec {
36    type Error = PacketCodecError;
37
38    fn encode(&mut self, _packet: Packet, _buf: &mut BytesMut) -> Result<(), Self::Error> {
39        Err(Error::new(
40            ErrorKind::Unsupported,
41            "Discv5Codec is receive-only; the server handles its own encoding",
42        )
43        .into())
44    }
45}