Skip to main content

fuel_core_p2p/
codecs.rs

1pub mod gossipsub;
2pub mod postcard;
3pub mod request_response;
4
5use crate::gossipsub::messages::GossipTopicTag;
6use libp2p::request_response as libp2p_request_response;
7
8use std::{
9    borrow::Cow,
10    io,
11};
12
13pub trait Encoder: Send {
14    /// Returns the serialized object as a slice.
15    fn into_bytes(self) -> Vec<u8>;
16}
17
18/// The trait encodes the type to the bytes and passes it to the `Encoder`,
19/// which stores it and provides a reference to it. That allows gives more
20/// flexibility and more performant encoding, allowing the use of slices and arrays
21/// instead of vectors in some cases. Since the [`Encoder`] returns `Cow<[u8]>`,
22/// it is always possible to take ownership of the serialized value.
23pub trait Encode<T: ?Sized> {
24    type Error;
25    /// The encoder type that stores serialized object.
26    type Encoder<'a>: Encoder
27    where
28        T: 'a;
29
30    /// Encodes the object to the bytes and passes it to the `Encoder`.
31    fn encode<'a>(&self, t: &'a T) -> Result<Self::Encoder<'a>, Self::Error>;
32}
33
34/// The trait decodes the type from the bytes.
35pub trait Decode<T> {
36    type Error;
37    /// Decodes the type `T` from the bytes.
38    fn decode(&self, bytes: &[u8]) -> Result<T, Self::Error>;
39}
40
41impl Encoder for Cow<'_, [u8]> {
42    fn into_bytes(self) -> Vec<u8> {
43        self.into_owned()
44    }
45}
46
47/// Implement this in order to handle serialization & deserialization of Gossipsub messages
48pub trait GossipsubCodec {
49    type RequestMessage;
50    type ResponseMessage;
51
52    fn encode(&self, data: Self::RequestMessage) -> Result<Vec<u8>, io::Error>;
53
54    fn decode(
55        &self,
56        encoded_data: &[u8],
57        gossipsub_topic: GossipTopicTag,
58    ) -> Result<Self::ResponseMessage, io::Error>;
59}
60
61pub trait RequestResponseProtocols: libp2p_request_response::Codec {
62    /// Returns RequestResponse's Protocol
63    /// Needed for initialization of RequestResponse Behaviour
64    fn get_req_res_protocols(
65        &self,
66    ) -> impl Iterator<Item = <Self as libp2p_request_response::Codec>::Protocol>;
67}