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
21pub use libp2p_core::ProtocolName;
22
23use async_trait::async_trait;
24use futures::prelude::*;
25use std::io;
26
27/// A `RequestResponseCodec` defines the request and response types
28/// for a [`RequestResponse`](crate::RequestResponse) protocol or
29/// protocol family and how they are encoded / decoded on an I/O stream.
30#[async_trait]
31pub trait RequestResponseCodec {
32 /// The type of protocol(s) or protocol versions being negotiated.
33 type Protocol: ProtocolName + Send + Clone;
34 /// The type of inbound and outbound requests.
35 type Request: Send;
36 /// The type of inbound and outbound responses.
37 type Response: Send;
38
39 /// Reads a request from the given I/O stream according to the
40 /// negotiated protocol.
41 async fn read_request<T>(&mut self, protocol: &Self::Protocol, io: &mut T)
42 -> io::Result<Self::Request>
43 where
44 T: AsyncRead + Unpin + Send;
45
46 /// Reads a response from the given I/O stream according to the
47 /// negotiated protocol.
48 async fn read_response<T>(&mut self, protocol: &Self::Protocol, io: &mut T)
49 -> io::Result<Self::Response>
50 where
51 T: AsyncRead + Unpin + Send;
52
53 /// Writes a request to the given I/O stream according to the
54 /// negotiated protocol.
55 async fn write_request<T>(&mut self, protocol: &Self::Protocol, io: &mut T, req: Self::Request)
56 -> io::Result<()>
57 where
58 T: AsyncWrite + Unpin + Send;
59
60 /// Writes a response to the given I/O stream according to the
61 /// negotiated protocol.
62 async fn write_response<T>(&mut self, protocol: &Self::Protocol, io: &mut T, res: Self::Response)
63 -> io::Result<()>
64 where
65 T: AsyncWrite + Unpin + Send;
66}
67