tez 0.0.2

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
use std::{
    convert::Infallible,
    error::Error as StdError,
    pin::Pin,
    task::{Context, Poll},
};

use bytes::Bytes;
use http_body::{Body as HttpBody, Frame, SizeHint};
use http_body_util::{BodyExt as _, combinators::UnsyncBoxBody};

use crate::Error;

pub(crate) enum Kind {
    Empty,
    Buffered(Option<Bytes>),
    Streaming(UnsyncBoxBody<Bytes, Error>),
}

pub(crate) enum Replayable {
    Empty,
    Buffered(Bytes),
}

/// An owned body for Tez requests and responses.
///
/// Tez bodies implement the standard [`http_body::Body`] contract. Buffered
/// values can be replayed internally; wrapped streams are consumed once.
/// [`Body::from`] accepts [`Bytes`], byte vectors, strings, and byte slices.
/// Use [`Body::wrap`] for streaming data or trailers.
pub struct Body {
    kind: Kind,
}

impl Body {
    /// Creates an absent body.
    ///
    /// This is also the value returned by [`Default::default`].
    #[must_use]
    pub const fn empty() -> Self {
        Self { kind: Kind::Empty }
    }

    /// Wraps a standard streaming HTTP body for one-time use.
    ///
    /// Data frames become [`Bytes`]; size hints and trailers are preserved.
    /// Errors from the wrapped body are mapped to Tez's backend-neutral
    /// [`Error`] type.
    #[must_use]
    pub fn wrap<B>(body: B) -> Self
    where
        B: HttpBody + Send + 'static,
        B::Data: Into<Bytes>,
        B::Error: StdError + Send + Sync + 'static,
    {
        Self::from_http_body(body, |_| Error::body())
    }

    pub(crate) fn from_http_body<B, F>(body: B, map_error: F) -> Self
    where
        B: HttpBody + Send + 'static,
        B::Data: Into<Bytes>,
        F: FnMut(B::Error) -> Error + Send + 'static,
    {
        let remaining = body.size_hint();
        let body = body
            .map_frame(|frame| frame.map_data(Into::into))
            .map_err(map_error)
            .boxed_unsync();
        let body = HintedBody {
            inner: body,
            remaining,
        }
        .boxed_unsync();
        Self {
            kind: Kind::Streaming(body),
        }
    }

    pub(crate) fn into_kind(self) -> Kind {
        self.kind
    }

    /// Returns the remaining bytes when this body is buffered.
    ///
    /// Empty bodies return an empty slice. Streaming bodies return `None`
    /// because their bytes are not available until they are consumed.
    #[must_use]
    pub fn as_bytes(&self) -> Option<&[u8]> {
        match &self.kind {
            Kind::Empty | Kind::Buffered(None) => Some(&[]),
            Kind::Buffered(Some(bytes)) => Some(bytes),
            Kind::Streaming(_) => None,
        }
    }

    pub(crate) fn into_replayable(self) -> Result<Replayable, Self> {
        match self.kind {
            Kind::Empty => Ok(Replayable::Empty),
            Kind::Buffered(Some(bytes)) => Ok(Replayable::Buffered(bytes)),
            Kind::Buffered(None) => Ok(Replayable::Buffered(Bytes::new())),
            Kind::Streaming(body) => Err(Self::from_kind(Kind::Streaming(body))),
        }
    }

    pub(crate) fn into_buffered_bytes(self) -> Result<Bytes, Self> {
        match self.kind {
            Kind::Empty | Kind::Buffered(None) => Ok(Bytes::new()),
            Kind::Buffered(Some(bytes)) => Ok(bytes),
            Kind::Streaming(body) => Err(Self::from_kind(Kind::Streaming(body))),
        }
    }

    pub(crate) const fn from_kind(kind: Kind) -> Self {
        Self { kind }
    }
}

impl Replayable {
    pub(crate) fn body(&self) -> Body {
        match self {
            Self::Empty => Body::empty(),
            Self::Buffered(bytes) => Body::from(bytes.clone()),
        }
    }
}

impl Default for Body {
    fn default() -> Self {
        Self::empty()
    }
}

impl From<Bytes> for Body {
    fn from(bytes: Bytes) -> Self {
        Self {
            kind: Kind::Buffered(Some(bytes)),
        }
    }
}

impl From<Vec<u8>> for Body {
    fn from(bytes: Vec<u8>) -> Self {
        Self::from(Bytes::from(bytes))
    }
}

impl From<String> for Body {
    fn from(text: String) -> Self {
        Self::from(text.into_bytes())
    }
}

impl From<&str> for Body {
    fn from(text: &str) -> Self {
        Self::from(text.as_bytes())
    }
}

impl From<&[u8]> for Body {
    fn from(bytes: &[u8]) -> Self {
        Self::from(bytes.to_vec())
    }
}

impl Unpin for Body {}

struct HintedBody {
    inner: UnsyncBoxBody<Bytes, Error>,
    remaining: SizeHint,
}

impl HttpBody for HintedBody {
    type Data = Bytes;
    type Error = Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        context: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        let this = self.get_mut();
        let polled = Pin::new(&mut this.inner).poll_frame(context);
        if let Poll::Ready(Some(Ok(frame))) = &polled
            && let Some(data) = frame.data_ref()
        {
            let consumed = data.len() as u64;
            let lower = this.remaining.lower().saturating_sub(consumed);
            let upper = this
                .remaining
                .upper()
                .map(|upper| upper.saturating_sub(consumed));
            this.remaining.set_lower(lower);
            if let Some(upper) = upper {
                this.remaining.set_upper(upper);
            }
        }
        polled
    }

    fn is_end_stream(&self) -> bool {
        self.inner.is_end_stream()
    }

    fn size_hint(&self) -> SizeHint {
        self.remaining
    }
}

impl HttpBody for Body {
    type Data = Bytes;
    type Error = Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        context: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        match &mut self.get_mut().kind {
            Kind::Empty => Poll::Ready(None),
            Kind::Buffered(bytes) => Poll::Ready(bytes.take().map(Frame::data).map(Ok)),
            Kind::Streaming(body) => Pin::new(body).poll_frame(context),
        }
    }

    fn is_end_stream(&self) -> bool {
        match &self.kind {
            Kind::Empty => true,
            Kind::Buffered(bytes) => bytes.is_none(),
            Kind::Streaming(body) => body.is_end_stream(),
        }
    }

    fn size_hint(&self) -> SizeHint {
        match &self.kind {
            Kind::Empty => SizeHint::with_exact(0),
            Kind::Buffered(Some(bytes)) => SizeHint::with_exact(bytes.len() as u64),
            Kind::Buffered(None) => SizeHint::with_exact(0),
            Kind::Streaming(body) => body.size_hint(),
        }
    }
}

impl From<Infallible> for Error {
    fn from(never: Infallible) -> Self {
        match never {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use http_body_util::Full;

    #[tokio::test]
    async fn bytes_body_yields_one_data_frame() {
        let mut body = Body::from("tez");

        assert_eq!(body.as_bytes(), Some(&b"tez"[..]));
        assert_eq!(body.size_hint().exact(), Some(3));
        assert_eq!(
            body.frame().await.unwrap().unwrap().into_data().unwrap(),
            "tez"
        );
        assert!(body.frame().await.is_none());
        assert_eq!(body.as_bytes(), Some(&[][..]));
        assert!(body.is_end_stream());
    }

    #[tokio::test]
    async fn wrapped_http_body_preserves_standard_frames() {
        let mut body = Body::wrap(Full::new(Bytes::from_static(b"stream")));

        assert_eq!(body.as_bytes(), None);
        assert_eq!(body.size_hint().exact(), Some(6));
        assert_eq!(
            body.frame().await.unwrap().unwrap().into_data().unwrap(),
            "stream"
        );
        assert_eq!(body.size_hint().exact(), Some(0));
        assert!(body.frame().await.is_none());
    }
}