use crate::BodyWriter;
use async_trait::async_trait;
use bytes::Bytes;
use conjure_error::Error;
use hyper::header::HeaderValue;
use pin_project::pin_project;
use std::pin::Pin;
#[async_trait]
pub trait Body {
fn content_length(&self) -> Option<u64>;
fn content_type(&self) -> HeaderValue;
fn full_body(&self) -> Option<Bytes> {
None
}
async fn write(self: Pin<&mut Self>, w: Pin<&mut BodyWriter>) -> Result<(), Error>;
async fn reset(self: Pin<&mut Self>) -> bool;
}
pub struct BytesBody {
body: Bytes,
content_type: HeaderValue,
}
impl BytesBody {
pub fn new<T>(body: T, content_type: HeaderValue) -> BytesBody
where
T: Into<Bytes>,
{
BytesBody {
body: body.into(),
content_type,
}
}
}
#[async_trait]
impl Body for BytesBody {
fn content_length(&self) -> Option<u64> {
Some(self.body.len() as u64)
}
fn content_type(&self) -> HeaderValue {
self.content_type.clone()
}
fn full_body(&self) -> Option<Bytes> {
Some(self.body.clone())
}
async fn write(self: Pin<&mut Self>, _: Pin<&mut BodyWriter>) -> Result<(), Error> {
unreachable!()
}
async fn reset(self: Pin<&mut Self>) -> bool {
true
}
}
#[pin_project]
pub(crate) struct ResetTrackingBody<T>
where
T: ?Sized,
{
needs_reset: bool,
#[pin]
body: T,
}
impl<T> ResetTrackingBody<T>
where
T: Body + Send,
{
pub fn new(body: T) -> ResetTrackingBody<T> {
ResetTrackingBody {
needs_reset: false,
body,
}
}
}
impl<T> ResetTrackingBody<T>
where
T: ?Sized,
{
pub fn needs_reset(&self) -> bool {
self.needs_reset
}
}
#[async_trait]
impl<T> Body for ResetTrackingBody<T>
where
T: ?Sized + Body + Send,
{
fn content_length(&self) -> Option<u64> {
self.body.content_length()
}
fn content_type(&self) -> HeaderValue {
self.body.content_type()
}
fn full_body(&self) -> Option<Bytes> {
self.body.full_body()
}
async fn write(self: Pin<&mut Self>, w: Pin<&mut BodyWriter>) -> Result<(), Error> {
let this = self.project();
*this.needs_reset = true;
this.body.write(w).await
}
async fn reset(self: Pin<&mut Self>) -> bool {
let this = self.project();
let ok = this.body.reset().await;
if ok {
*this.needs_reset = false;
}
ok
}
}