simple_hyper_client/connector/
hyper_adapter.rs

1/* Copyright (c) Fortanix, Inc.
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7use crate::connector::{NetworkConnection, NetworkConnector};
8
9use hyper::client::connect::Connection;
10use hyper::service::Service;
11use hyper::Uri;
12use tokio::io::{AsyncRead, AsyncWrite};
13use tokio::sync::Mutex;
14
15use std::error::Error as StdError;
16use std::future::Future;
17use std::pin::Pin;
18use std::sync::Arc;
19
20/// An adapter that given `T: hyper::client::connect::Connect`
21/// implements [`NetworkConnector`]
22///
23/// NOTE: this is only meant as a last resort, if you can directly
24/// implement [`NetworkConnector`] for your connector then avoid
25/// using this adapter to reduce allocations.
26pub struct HyperConnectorAdapter<T>(Arc<Mutex<T>>);
27
28impl<T> HyperConnectorAdapter<T> {
29    pub fn new(inner: T) -> Self {
30        HyperConnectorAdapter(Arc::new(Mutex::new(inner)))
31    }
32}
33
34impl<S, T> NetworkConnector for HyperConnectorAdapter<S>
35where
36    S: Service<Uri, Response = T> + Send + 'static,
37    S::Error: Into<Box<dyn StdError + Send + Sync>>,
38    S::Future: Unpin + Send,
39    T: AsyncRead + AsyncWrite + Connection + Unpin + Send + 'static,
40{
41    fn connect(
42        &self,
43        uri: Uri,
44    ) -> Pin<
45        Box<dyn Future<Output = Result<NetworkConnection, Box<dyn StdError + Send + Sync>>> + Send>,
46    > {
47        let inner = self.0.clone();
48        Box::pin(async move {
49            match inner.lock().await.call(uri).await {
50                Ok(conn) => Ok(NetworkConnection::new(conn)),
51                Err(e) => Err(e.into()),
52            }
53        })
54    }
55}