Skip to main content

zincio_hyper/
lib.rs

1//! A compatibility layer for using [`hyper`] with the `zincio` async runtime.
2//!
3//! This crate provides the necessary adapters to run `hyper`-based HTTP servers
4//! and clients on top of `zincio` instead of `tokio`. It implements the traits
5//! required by `hyper`'s runtime abstraction:
6//!
7//! - [`ZincioExecutor`]: An executor that spawns tasks on the `zincio` runtime
8//!   using `zincio::spawn`.
9//! - [`ZincioTimer`]: A timer that uses `zincio::time::sleep` for delay operations.
10//! - [`ZincioIo`]: A wrapper type that adapts `zincio`'s I/O types to implement
11//!   `hyper`'s `Read` and `Write` traits, and also implements `tokio`'s
12//!   `AsyncRead` and `AsyncWrite` traits for compatibility.
13//!
14//! # Overview
15//!
16//! This crate enables `hyper` to work with `zincio` by implementing `hyper`'s
17//! runtime traits (`Executor`, `Timer`, `Read`, `Write`, `Sleep`) in terms of
18//! `zincio` primitives.
19//!
20//! ## Executor
21//!
22//! The [`ZincioExecutor`] type implements `hyper::rt::Executor` by spawning
23//! futures onto the `zincio` runtime via `zincio::spawn`.
24//!
25//! ## Timer
26//!
27//! The [`ZincioTimer`] type implements `hyper::rt::Timer` by converting sleep
28//! requests into `zincio::time::sleep` futures wrapped in a compatible type.
29//!
30//! ## I/O Adapters
31//!
32//! The [`ZincioIo<T>`] wrapper adapts any type that implements `tokio::io::AsyncRead`
33//! and `tokio::io::AsyncWrite` to work with `hyper`'s I/O traits. It also
34//! implements the reverse conversion, allowing `hyper`'s I/O types to be used
35//! with `tokio`-style async functions.
36//!
37//! # Implementation notes
38//!
39//! - The `ZincioIo` wrapper uses `Pin<Box<T>>` internally to support the
40//!   trait implementations required by `hyper` and `tokio`.
41//! - The `ZincioSleep` type (internal) implements both `hyper::rt::Sleep`
42//!   and `std::future::Future` to bridge the two runtimes' sleep abstractions.
43//! - Timer handles are properly cancelled when `ZincioSleep` is dropped to
44//!   avoid resource leaks.
45
46use std::{
47    ops::{Deref, DerefMut},
48    pin::Pin,
49    task::{Context, Poll},
50};
51
52use futures_util::FutureExt;
53use hyper::rt::Executor;
54#[cfg(feature = "time")]
55use hyper::rt::{Sleep, Timer};
56use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
57
58/// An executor that spawns tasks onto the `zincio` runtime.
59///
60/// This type implements `hyper::rt::Executor` and uses `zincio::spawn` to
61/// execute futures on the `zincio` runtime.
62#[derive(Debug, Default, Clone, Copy)]
63pub struct ZincioExecutor;
64
65impl<Fut> Executor<Fut> for ZincioExecutor
66where
67    Fut: std::future::Future + 'static,
68    Fut::Output: 'static,
69{
70    #[inline]
71    fn execute(&self, fut: Fut) {
72        zincio::spawn_detached(fut.map(|_| ()));
73    }
74}
75
76/// A timer that uses `zincio`'s time utilities for sleep operations.
77///
78/// This type implements `hyper::rt::Timer` and uses `zincio::time::sleep`
79/// to implement delay operations.
80#[cfg(feature = "time")]
81#[derive(Debug, Default, Clone, Copy)]
82pub struct ZincioTimer;
83
84#[cfg(feature = "time")]
85impl Timer for ZincioTimer {
86    #[inline]
87    fn sleep(&self, duration: std::time::Duration) -> Pin<Box<dyn Sleep>> {
88        Box::pin(ZincioSleep {
89            inner: Box::pin(zincio::time::sleep(duration)),
90        })
91    }
92
93    #[inline]
94    fn sleep_until(&self, deadline: std::time::Instant) -> Pin<Box<dyn Sleep>> {
95        Box::pin(ZincioSleep {
96            inner: Box::pin(zincio::time::sleep_until(deadline)),
97        })
98    }
99
100    #[inline]
101    fn reset(&self, sleep: &mut Pin<Box<dyn Sleep>>, new_deadline: std::time::Instant) {
102        if let Some(mut sleep) = sleep.as_mut().downcast_mut_pin::<ZincioSleep>() {
103            sleep.reset(new_deadline);
104        }
105    }
106}
107
108/// A sleep future that wraps `zincio::time::Sleep` and implements `hyper::rt::Sleep`.
109#[cfg(feature = "time")]
110struct ZincioSleep {
111    inner: Pin<Box<zincio::time::Sleep>>,
112}
113
114#[cfg(feature = "time")]
115impl std::future::Future for ZincioSleep {
116    type Output = ();
117
118    #[inline]
119    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
120        self.inner.as_mut().poll(cx)
121    }
122}
123
124#[cfg(feature = "time")]
125impl Sleep for ZincioSleep {}
126
127#[cfg(feature = "time")]
128unsafe impl Send for ZincioSleep {}
129#[cfg(feature = "time")]
130unsafe impl Sync for ZincioSleep {}
131
132#[cfg(feature = "time")]
133impl ZincioSleep {
134    #[inline]
135    fn reset(&mut self, new_deadline: std::time::Instant) {
136        self.inner.reset(new_deadline);
137    }
138}
139
140/// A wrapper type that adapts I/O types for use with `hyper` and `tokio`.
141///
142/// `ZincioIo<T>` wraps any type `T` that implements `tokio::io::AsyncRead`
143/// and `tokio::io::AsyncWrite` and provides implementations for:
144///
145/// - `hyper::rt::Read` and `hyper::rt::Write`
146/// - `tokio::io::AsyncRead` and `tokio::io::AsyncWrite`
147///
148/// This allows seamless interoperability between `hyper`'s I/O traits and
149/// `tokio`'s async I/O traits when using the `zincio` runtime.
150#[derive(Debug)]
151pub struct ZincioIo<T> {
152    inner: Pin<Box<T>>,
153}
154
155impl<T> ZincioIo<T> {
156    /// Creates a new `ZincioIo` wrapper around the given I/O type.
157    #[inline]
158    pub fn new(inner: T) -> Self {
159        Self {
160            inner: Box::pin(inner),
161        }
162    }
163}
164
165impl<T> Deref for ZincioIo<T> {
166    type Target = Pin<Box<T>>;
167
168    #[inline]
169    fn deref(&self) -> &Self::Target {
170        &self.inner
171    }
172}
173
174impl<T> DerefMut for ZincioIo<T> {
175    #[inline]
176    fn deref_mut(&mut self) -> &mut Self::Target {
177        &mut self.inner
178    }
179}
180
181// Implement hyper::rt::Read for types that implement tokio::io::AsyncRead
182impl<T> hyper::rt::Read for ZincioIo<T>
183where
184    T: AsyncRead,
185{
186    #[inline]
187    fn poll_read(
188        mut self: Pin<&mut Self>,
189        cx: &mut Context<'_>,
190        mut buf: hyper::rt::ReadBufCursor<'_>,
191    ) -> Poll<Result<(), std::io::Error>> {
192        let n = {
193            let mut tbuf = unsafe { ReadBuf::uninit(buf.as_mut()) };
194            match self.inner.as_mut().poll_read(cx, &mut tbuf) {
195                Poll::Ready(Ok(())) => tbuf.filled().len(),
196                Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
197                Poll::Pending => return Poll::Pending,
198            }
199        };
200
201        unsafe { buf.advance(n) };
202        Poll::Ready(Ok(()))
203    }
204}
205
206// Implement hyper::rt::Write for types that implement tokio::io::AsyncWrite
207impl<T> hyper::rt::Write for ZincioIo<T>
208where
209    T: AsyncWrite,
210{
211    #[inline]
212    fn poll_write(
213        mut self: Pin<&mut Self>,
214        cx: &mut Context<'_>,
215        buf: &[u8],
216    ) -> Poll<Result<usize, std::io::Error>> {
217        self.inner.as_mut().poll_write(cx, buf)
218    }
219
220    #[inline]
221    fn poll_flush(
222        mut self: Pin<&mut Self>,
223        cx: &mut Context<'_>,
224    ) -> Poll<Result<(), std::io::Error>> {
225        self.inner.as_mut().poll_flush(cx)
226    }
227
228    #[inline]
229    fn poll_shutdown(
230        mut self: Pin<&mut Self>,
231        cx: &mut Context<'_>,
232    ) -> Poll<Result<(), std::io::Error>> {
233        self.inner.as_mut().poll_shutdown(cx)
234    }
235
236    #[inline]
237    fn is_write_vectored(&self) -> bool {
238        self.inner.is_write_vectored()
239    }
240
241    #[inline]
242    fn poll_write_vectored(
243        mut self: Pin<&mut Self>,
244        cx: &mut Context<'_>,
245        bufs: &[std::io::IoSlice<'_>],
246    ) -> Poll<Result<usize, std::io::Error>> {
247        self.inner.as_mut().poll_write_vectored(cx, bufs)
248    }
249}
250
251// Implement tokio::io::AsyncRead for types that implement hyper::rt::Read
252impl<T> AsyncRead for ZincioIo<T>
253where
254    T: hyper::rt::Read,
255{
256    #[inline]
257    fn poll_read(
258        mut self: Pin<&mut Self>,
259        cx: &mut Context<'_>,
260        tbuf: &mut ReadBuf<'_>,
261    ) -> Poll<std::io::Result<()>> {
262        let filled = tbuf.filled().len();
263        let sub_filled = {
264            let mut buf = unsafe { hyper::rt::ReadBuf::uninit(tbuf.unfilled_mut()) };
265            match self.inner.as_mut().poll_read(cx, buf.unfilled()) {
266                Poll::Ready(Ok(())) => buf.filled().len(),
267                Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
268                Poll::Pending => return Poll::Pending,
269            }
270        };
271
272        unsafe {
273            tbuf.assume_init(sub_filled);
274            tbuf.set_filled(filled + sub_filled);
275        };
276        Poll::Ready(Ok(()))
277    }
278}
279
280// Implement tokio::io::AsyncWrite for types that implement hyper::rt::Write
281impl<T> AsyncWrite for ZincioIo<T>
282where
283    T: hyper::rt::Write,
284{
285    #[inline]
286    fn poll_write(
287        mut self: Pin<&mut Self>,
288        cx: &mut Context<'_>,
289        buf: &[u8],
290    ) -> Poll<Result<usize, std::io::Error>> {
291        self.inner.as_mut().poll_write(cx, buf)
292    }
293
294    #[inline]
295    fn poll_flush(
296        mut self: Pin<&mut Self>,
297        cx: &mut Context<'_>,
298    ) -> Poll<Result<(), std::io::Error>> {
299        self.inner.as_mut().poll_flush(cx)
300    }
301
302    #[inline]
303    fn poll_shutdown(
304        mut self: Pin<&mut Self>,
305        cx: &mut Context<'_>,
306    ) -> Poll<Result<(), std::io::Error>> {
307        self.inner.as_mut().poll_shutdown(cx)
308    }
309
310    #[inline]
311    fn is_write_vectored(&self) -> bool {
312        self.inner.is_write_vectored()
313    }
314
315    #[inline]
316    fn poll_write_vectored(
317        mut self: Pin<&mut Self>,
318        cx: &mut Context<'_>,
319        bufs: &[std::io::IoSlice<'_>],
320    ) -> Poll<Result<usize, std::io::Error>> {
321        self.inner.as_mut().poll_write_vectored(cx, bufs)
322    }
323}