libp2p_request_response/codec.rs
1// Copyright 2020 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use std::io;
22
23use async_trait::async_trait;
24use futures::prelude::*;
25
26/// A `Codec` defines the request and response types
27/// for a request-response [`Behaviour`](crate::Behaviour) protocol or
28/// protocol family and how they are encoded / decoded on an I/O stream.
29#[async_trait]
30pub trait Codec {
31 /// The type of protocol(s) or protocol versions being negotiated.
32 type Protocol: AsRef<str> + Send + Clone;
33 /// The type of inbound and outbound requests.
34 type Request: Send;
35 /// The type of inbound and outbound responses.
36 type Response: Send;
37
38 /// Reads a request from the given I/O stream according to the
39 /// negotiated protocol.
40 async fn read_request<T>(
41 &mut self,
42 protocol: &Self::Protocol,
43 io: &mut T,
44 ) -> io::Result<Self::Request>
45 where
46 T: AsyncRead + Unpin + Send;
47
48 /// Reads a response from the given I/O stream according to the
49 /// negotiated protocol.
50 async fn read_response<T>(
51 &mut self,
52 protocol: &Self::Protocol,
53 io: &mut T,
54 ) -> io::Result<Self::Response>
55 where
56 T: AsyncRead + Unpin + Send;
57
58 /// Writes a request to the given I/O stream according to the
59 /// negotiated protocol.
60 async fn write_request<T>(
61 &mut self,
62 protocol: &Self::Protocol,
63 io: &mut T,
64 req: Self::Request,
65 ) -> io::Result<()>
66 where
67 T: AsyncWrite + Unpin + Send;
68
69 /// Writes a response to the given I/O stream according to the
70 /// negotiated protocol.
71 async fn write_response<T>(
72 &mut self,
73 protocol: &Self::Protocol,
74 io: &mut T,
75 res: Self::Response,
76 ) -> io::Result<()>
77 where
78 T: AsyncWrite + Unpin + Send;
79}