use bytes::Bytes;
use http_body::{Body, Frame, SizeHint};
use http_body_util::combinators::UnsyncBoxBody;
use std::pin::Pin;
use std::task::{Context, Poll};
use crate::Error;
#[non_exhaustive]
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub enum AnyBody<T> {
Box(UnsyncBoxBody<Bytes, Error>),
Inline(T),
}
enum AnyBodyProjection<'a, T> {
Box(Pin<&'a mut UnsyncBoxBody<Bytes, Error>>),
Inline(Pin<&'a mut T>),
}
impl<T> AnyBody<T> {
fn project(self: Pin<&mut Self>) -> AnyBodyProjection<T> {
match unsafe { self.get_unchecked_mut() } {
Self::Box(ptr) => AnyBodyProjection::Box(Pin::new(ptr)),
Self::Inline(ptr) => AnyBodyProjection::Inline(unsafe { Pin::new_unchecked(ptr) }),
}
}
}
impl<T, E> Body for AnyBody<T>
where
T: Body<Data = Bytes, Error = E>,
Error: From<E>,
{
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 self.project() {
AnyBodyProjection::Box(body) => body.poll_frame(context),
AnyBodyProjection::Inline(body) => {
body.poll_frame(context).map_err(|error| error.into())
}
}
}
fn is_end_stream(&self) -> bool {
match self {
Self::Box(body) => body.is_end_stream(),
Self::Inline(body) => body.is_end_stream(),
}
}
fn size_hint(&self) -> SizeHint {
match self {
Self::Box(body) => body.size_hint(),
Self::Inline(body) => body.size_hint(),
}
}
}