simple_hyper_client/connector/
mod.rs1use hyper::client::connect::{Connected, Connection};
8use hyper::service::Service;
9use hyper::Uri;
10use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
11
12use std::error::Error as StdError;
13use std::future::Future;
14use std::io;
15use std::pin::Pin;
16use std::sync::Arc;
17use std::task::{Context, Poll};
18
19pub mod http;
20pub mod hyper_adapter;
21
22pub use self::http::{ConnectError, HttpConnection, HttpConnector};
23pub use self::hyper_adapter::HyperConnectorAdapter;
24
25trait NetworkStream: AsyncRead + AsyncWrite + Connection + Unpin + Send + 'static {}
26
27impl<T> NetworkStream for T where T: AsyncRead + AsyncWrite + Connection + Unpin + Send + 'static {}
28
29pub struct NetworkConnection(Box<dyn NetworkStream>);
31
32impl NetworkConnection {
33 pub fn new<S>(stream: S) -> Self
34 where
35 S: AsyncRead + AsyncWrite + Connection + Unpin + Send + 'static,
36 {
37 NetworkConnection(Box::new(stream))
38 }
39}
40
41impl Connection for NetworkConnection {
42 fn connected(&self) -> Connected {
43 self.0.connected()
44 }
45}
46
47impl AsyncRead for NetworkConnection {
48 fn poll_read(
49 self: Pin<&mut Self>,
50 cx: &mut Context<'_>,
51 buf: &mut ReadBuf<'_>,
52 ) -> Poll<io::Result<()>> {
53 Pin::new(&mut self.get_mut().0).poll_read(cx, buf)
54 }
55}
56
57impl AsyncWrite for NetworkConnection {
58 fn poll_write(
59 self: Pin<&mut Self>,
60 cx: &mut Context<'_>,
61 buf: &[u8],
62 ) -> Poll<io::Result<usize>> {
63 Pin::new(&mut self.get_mut().0).poll_write(cx, buf)
64 }
65
66 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
67 Pin::new(&mut self.get_mut().0).poll_flush(cx)
68 }
69
70 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
71 Pin::new(&mut self.get_mut().0).poll_shutdown(cx)
72 }
73}
74
75pub trait NetworkConnector: Send + Sync + 'static {
77 fn connect(
78 &self,
79 uri: Uri,
80 ) -> Pin<
81 Box<dyn Future<Output = Result<NetworkConnection, Box<dyn StdError + Send + Sync>>> + Send>,
82 >;
83}
84
85#[derive(Clone)]
86pub(crate) struct ConnectorAdapter(Arc<dyn NetworkConnector>);
87
88impl ConnectorAdapter {
89 pub fn new<T: NetworkConnector>(connector: T) -> Self {
90 Self(Arc::new(connector))
91 }
92}
93
94impl Service<Uri> for ConnectorAdapter {
95 type Response = NetworkConnection;
96 type Error = Box<dyn StdError + Send + Sync>;
97 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
98
99 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
100 Poll::Ready(Ok(()))
101 }
102
103 fn call(&mut self, uri: Uri) -> Self::Future {
104 self.0.connect(uri)
105 }
106}