use std::io;
use std::ops::ControlFlow;
use std::pin::Pin;
use std::task::{Context, Poll, ready};
use bytes::{Buf, Bytes};
use flate2::{Compress, Compression, Crc, FlushCompress, Status};
use http::HeaderMap;
use http_body::{Body as HttpBody, Frame, SizeHint};
use navree_kernel::BoxError;
use pin_project_lite::pin_project;
const BUFFER: usize = 4096;
const HEADER: [u8; 10] = [0x1f, 0x8b, 0x08, 0, 0, 0, 0, 0, 0, 0xff];
const LEVEL: u32 = 6;
pin_project! {
pub(crate) struct GzipBody<B> {
#[pin]
body: B,
chunk: Bytes,
drained: bool,
ended: bool,
trailers: Option<HeaderMap>,
encoder: Encoder,
room: usize,
done: bool,
}
}
impl<B> GzipBody<B> {
pub(crate) fn new(body: B) -> Self {
Self {
body,
chunk: Bytes::new(),
drained: false,
ended: false,
trailers: None,
encoder: Encoder::new(),
room: BUFFER,
done: false,
}
}
}
impl<B> HttpBody for GzipBody<B>
where
B: HttpBody<Data = Bytes>,
B::Error: Into<BoxError>,
{
type Data = Bytes;
type Error = BoxError;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, BoxError>>> {
let mut this = self.project();
if !*this.done {
if *this.room == 0 {
*this.room = BUFFER;
}
let mut out = Out::new(*this.room);
let mut source = Source {
body: this.body.as_mut(),
chunk: this.chunk,
drained: this.drained,
ended: this.ended,
trailers: this.trailers,
};
match ready!(this.encoder.poll(&mut source, cx, &mut out)) {
Ok(()) if out.len == 0 => *this.done = true,
Ok(()) => {
*this.room -= out.len;
return Poll::Ready(Some(Ok(Frame::data(out.into_bytes()))));
}
Err(Failure::Body(error)) => return Poll::Ready(Some(Err(error))),
Err(Failure::Deflate(error)) => return Poll::Ready(Some(Err(error.into()))),
}
}
if let Some(trailers) = this.trailers.take() {
return Poll::Ready(Some(Ok(Frame::trailers(trailers))));
}
if *this.ended {
return Poll::Ready(None);
}
let next = match ready!(this.body.poll_frame(cx)) {
Some(Ok(frame)) => match frame.into_data() {
Ok(data) if data.has_remaining() => Some(Err(
"the body sent data after the end of its gzip stream".into(),
)),
Ok(_) => None,
Err(frame) => Some(Ok(frame)),
},
Some(Err(error)) => Some(Err(error.into())),
None => None,
};
*this.ended = next.is_none();
Poll::Ready(next)
}
fn size_hint(&self) -> SizeHint {
SizeHint::new()
}
fn is_end_stream(&self) -> bool {
false
}
}
enum Failure {
Body(BoxError),
Deflate(io::Error),
}
struct Source<'a, B> {
body: Pin<&'a mut B>,
chunk: &'a mut Bytes,
drained: &'a mut bool,
ended: &'a mut bool,
trailers: &'a mut Option<HeaderMap>,
}
impl<B> Source<'_, B>
where
B: HttpBody<Data = Bytes>,
B::Error: Into<BoxError>,
{
fn fill(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
while self.chunk.is_empty() && !*self.drained {
match ready!(self.body.as_mut().poll_frame(cx)) {
Some(Ok(frame)) => match frame.into_data() {
Ok(data) => *self.chunk = data,
Err(frame) => {
*self.drained = true;
*self.trailers = frame.into_trailers().ok();
}
},
Some(Err(error)) => return Poll::Ready(Err(error.into())),
None => {
*self.drained = true;
*self.ended = true;
}
}
}
Poll::Ready(Ok(()))
}
}
struct Out {
buf: Vec<u8>,
len: usize,
}
impl Out {
fn new(room: usize) -> Self {
Self {
buf: vec![0; room],
len: 0,
}
}
fn is_full(&self) -> bool {
self.len == self.buf.len()
}
fn copy(&mut self, bytes: &[u8]) -> usize {
let free = &mut self.buf[self.len..];
let n = free.len().min(bytes.len());
free[..n].copy_from_slice(&bytes[..n]);
self.len += n;
n
}
fn deflate(
&mut self,
deflate: &mut Compress,
input: &[u8],
flush: FlushCompress,
) -> io::Result<(Status, usize)> {
let (taken, written) = (deflate.total_in(), deflate.total_out());
let status = deflate
.compress(input, &mut self.buf[self.len..], flush)
.map_err(io::Error::other)?;
let taken = usize::try_from(deflate.total_in() - taken).map_err(io::Error::other)?;
let written = usize::try_from(deflate.total_out() - written).map_err(io::Error::other)?;
self.len += written;
Ok((status, taken))
}
fn into_bytes(mut self) -> Bytes {
self.buf.truncate(self.len);
Bytes::from(self.buf)
}
}
enum Step {
Encoding {
read: usize,
},
Flushing,
Finishing,
Done,
Failed(io::Error),
}
enum Part {
Header(usize),
Deflate,
Footer([u8; 8], usize),
Done,
}
struct Encoder {
deflate: Compress,
crc: Crc,
part: Part,
flushed: bool,
step: Step,
}
impl Encoder {
fn new() -> Self {
Self {
deflate: Compress::new(Compression::new(LEVEL), false),
crc: Crc::new(),
part: Part::Header(0),
flushed: true,
step: Step::Encoding { read: 0 },
}
}
fn poll<B>(
&mut self,
source: &mut Source<'_, B>,
cx: &mut Context<'_>,
out: &mut Out,
) -> Poll<Result<(), Failure>>
where
B: HttpBody<Data = Bytes>,
B::Error: Into<BoxError>,
{
if let ControlFlow::Break(result) = self.advance(out, None) {
return Poll::Ready(result.map_err(Failure::Deflate));
}
loop {
let (flow, ready) = match source.fill(cx) {
Poll::Pending => (self.advance(out, None), false),
Poll::Ready(Ok(())) => {
let mut taken = 0;
let flow = self.advance(out, Some((&source.chunk[..], &mut taken)));
source.chunk.advance(taken.min(source.chunk.len()));
(flow, true)
}
Poll::Ready(Err(error)) => return Poll::Ready(Err(Failure::Body(error))),
};
if let ControlFlow::Break(result) = flow {
return Poll::Ready(result.map_err(Failure::Deflate));
}
if !ready {
return if out.len == 0 {
Poll::Pending
} else {
Poll::Ready(Ok(()))
};
}
}
}
fn advance(
&mut self,
out: &mut Out,
input: Option<(&[u8], &mut usize)>,
) -> ControlFlow<io::Result<()>> {
let mut input = input;
loop {
self.step = match std::mem::replace(&mut self.step, Step::Done) {
Step::Encoding { read } => match input.as_mut() {
None if read == 0 => {
self.step = Step::Encoding { read };
if out.len == 0 {
break;
}
return ControlFlow::Break(Ok(()));
}
None => Step::Flushing,
Some(([], _)) => Step::Finishing,
Some((input, taken)) => match self.encode(input, out) {
Ok(n) => {
**taken += n;
self.step = Step::Encoding {
read: read.saturating_add(n),
};
break;
}
Err(error) => Step::Failed(error),
},
},
Step::Flushing => match self.flush(out) {
Ok(true) => {
self.step = Step::Encoding { read: 0 };
break;
}
Ok(false) => Step::Flushing,
Err(error) => Step::Failed(error),
},
Step::Finishing => match self.finish(out) {
Ok(true) => Step::Done,
Ok(false) => Step::Finishing,
Err(error) => Step::Failed(error),
},
Step::Done => return ControlFlow::Break(Ok(())),
Step::Failed(error) => return ControlFlow::Break(Err(error)),
};
if let Step::Failed(_) = self.step {
if out.len > 0 {
return ControlFlow::Break(Ok(()));
}
continue;
}
if out.is_full() {
return ControlFlow::Break(Ok(()));
}
}
if out.is_full() {
ControlFlow::Break(Ok(()))
} else {
ControlFlow::Continue(())
}
}
fn encode(&mut self, input: &[u8], out: &mut Out) -> io::Result<usize> {
let mut taken = 0;
loop {
match self.part {
Part::Header(_) => self.write_header(out),
Part::Deflate => {
self.flushed = false;
let rest = &input[taken..];
let (status, n) = out.deflate(&mut self.deflate, rest, FlushCompress::None)?;
match status {
Status::Ok => {}
Status::StreamEnd => {
return Err(io::Error::other("the deflate stream ended early"));
}
Status::BufError => return Err(io::Error::other("unexpected BufError")),
}
self.crc.update(&rest[..n]);
taken += n;
}
Part::Footer(..) | Part::Done => {
return Err(io::Error::other("encode after complete"));
}
}
if taken == input.len() || out.is_full() {
return Ok(taken);
}
}
}
fn flush(&mut self, out: &mut Out) -> io::Result<bool> {
loop {
let done = match self.part {
Part::Header(_) => {
self.write_header(out);
false
}
Part::Deflate => self.flush_deflate(out)?,
Part::Footer(..) => self.write_footer(out),
Part::Done => true,
};
if done {
return Ok(true);
}
if out.is_full() {
return Ok(false);
}
}
}
fn flush_deflate(&mut self, out: &mut Out) -> io::Result<bool> {
if self.flushed {
return Ok(true);
}
out.deflate(&mut self.deflate, &[], FlushCompress::Sync)?;
loop {
let before = out.len;
out.deflate(&mut self.deflate, &[], FlushCompress::None)?;
if out.len == before {
break;
}
}
self.flushed = !out.is_full();
Ok(self.flushed)
}
fn finish(&mut self, out: &mut Out) -> io::Result<bool> {
loop {
match self.part {
Part::Header(_) => self.write_header(out),
Part::Deflate => {
self.flushed = false;
let (status, _) = out.deflate(&mut self.deflate, &[], FlushCompress::Finish)?;
match status {
Status::Ok => {}
Status::StreamEnd => {
let mut footer = [0; 8];
footer[..4].copy_from_slice(&self.crc.sum().to_le_bytes());
footer[4..].copy_from_slice(&self.crc.amount().to_le_bytes());
self.part = Part::Footer(footer, 0);
}
Status::BufError => return Err(io::Error::other("unexpected BufError")),
}
}
Part::Footer(..) => {
self.write_footer(out);
}
Part::Done => {}
}
if let Part::Done = self.part {
return Ok(true);
}
if out.is_full() {
return Ok(false);
}
}
}
fn write_header(&mut self, out: &mut Out) {
if let Part::Header(written) = &mut self.part {
*written += out.copy(HEADER.get(*written..).unwrap_or_default());
if *written == HEADER.len() {
self.part = Part::Deflate;
}
}
}
fn write_footer(&mut self, out: &mut Out) -> bool {
if let Part::Footer(footer, written) = &mut self.part {
*written += out.copy(footer.get(*written..).unwrap_or_default());
if *written == footer.len() {
self.part = Part::Done;
return true;
}
return false;
}
matches!(self.part, Part::Done)
}
}