tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
use std::{
    fmt,
    future::Future,
    io,
    pin::Pin,
    task::{Context, Poll},
};

use futures_io::{AsyncRead, AsyncWrite};
use hyper::rt::{Read as _, ReadBuf, Write as _};

use crate::{Error, Result};

/// Completion of an HTTP protocol switch.
///
/// Await this value after validating the response status and upgrade headers.
/// It resolves to a runtime-agnostic byte stream.
#[derive(Clone)]
pub struct Upgrade {
    inner: Option<hyper::upgrade::OnUpgrade>,
}

impl Upgrade {
    pub(crate) const fn new(inner: hyper::upgrade::OnUpgrade) -> Self {
        Self { inner: Some(inner) }
    }

    pub(crate) const fn unavailable() -> Self {
        Self { inner: None }
    }
}

impl Future for Upgrade {
    type Output = Result<Upgraded>;

    fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
        let Some(upgrade) = &mut self.inner else {
            return Poll::Ready(Err(Error::upgrade()));
        };
        match Pin::new(upgrade).poll(context) {
            Poll::Ready(Ok(stream)) => {
                self.inner = None;
                Poll::Ready(Ok(Upgraded { inner: stream }))
            }
            Poll::Ready(Err(_)) => {
                self.inner = None;
                Poll::Ready(Err(Error::upgrade()))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl fmt::Debug for Upgrade {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Upgrade")
            .field("available", &self.inner.is_some())
            .finish()
    }
}

/// A connection after an HTTP Upgrade or successful `CONNECT`.
///
/// The stream implements the runtime-neutral [`futures_io`] traits, allowing a
/// higher-level protocol such as WebSocket to take ownership without depending
/// on Hyper or a particular async runtime.
pub struct Upgraded {
    inner: hyper::upgrade::Upgraded,
}

impl AsyncRead for Upgraded {
    fn poll_read(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        output: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let mut buffer = ReadBuf::new(output);
        match Pin::new(&mut self.inner).poll_read(context, buffer.unfilled()) {
            Poll::Ready(Ok(())) => Poll::Ready(Ok(buffer.filled().len())),
            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
            Poll::Pending => Poll::Pending,
        }
    }
}

impl AsyncWrite for Upgraded {
    fn poll_write(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        bytes: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.inner).poll_write(context, bytes)
    }

    fn poll_flush(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_flush(context)
    }

    fn poll_close(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_shutdown(context)
    }

    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        buffers: &[io::IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.inner).poll_write_vectored(context, buffers)
    }
}

impl fmt::Debug for Upgraded {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_struct("Upgraded").finish_non_exhaustive()
    }
}