use std::io::Write;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use anyhow::Result;
use bytes::Bytes;
use futures_util::Stream;
use futures_util::TryStreamExt;
use http_body::Body;
use http_body::Frame;
use http_body_util::BodyExt;
use pin_project_lite::pin_project;
use tako_rs_core::body::TakoBody;
use tako_rs_core::types::BoxError;
pub fn stream_brotli<B>(body: B, lvl: u32) -> TakoBody
where
B: Body<Data = Bytes, Error = BoxError> + Send + 'static,
{
let stream = body.into_data_stream();
let stream = BrotliStream::new(stream, lvl).map_ok(Frame::data);
TakoBody::from_try_stream(stream)
}
pin_project! {
pub struct BrotliStream<S> {
#[pin] inner: S,
encoder: Option<brotli::CompressorWriter<Vec<u8>>>,
tail: Vec<u8>,
done: bool,
}
}
impl<S> BrotliStream<S> {
fn new(stream: S, level: u32) -> Self {
Self {
inner: stream,
encoder: Some(brotli::CompressorWriter::new(Vec::new(), 4096, level, 22)),
tail: Vec::new(),
done: false,
}
}
}
impl<S> Stream for BrotliStream<S>
where
S: Stream<Item = Result<Bytes, BoxError>>,
{
type Item = Result<Bytes, BoxError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
loop {
if let Some(enc) = this.encoder.as_mut() {
if !enc.get_ref().is_empty() {
let chunk: Vec<u8> = enc.get_mut().drain(..).collect();
return Poll::Ready(Some(Ok(Bytes::from(chunk))));
}
} else if !this.tail.is_empty() {
let chunk: Vec<u8> = this.tail.drain(..).collect();
return Poll::Ready(Some(Ok(Bytes::from(chunk))));
}
if *this.done && this.encoder.is_none() {
return Poll::Ready(None);
}
match this.inner.as_mut().poll_next(cx) {
Poll::Ready(Some(Ok(chunk))) => {
if let Some(enc) = this.encoder.as_mut()
&& let Err(e) = enc.write_all(&chunk).and_then(|()| enc.flush())
{
return Poll::Ready(Some(Err(e.into())));
}
}
Poll::Ready(Some(Err(e))) => {
return Poll::Ready(Some(Err(e)));
}
Poll::Ready(None) => {
*this.done = true;
if let Some(enc) = this.encoder.take() {
*this.tail = enc.into_inner();
continue;
}
return Poll::Ready(None);
}
Poll::Pending => {
return Poll::Pending;
}
}
}
}
}