1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#![allow(unused_imports)]
use super::{body::BodyInner, CompressionBody};
use crate::compression::predicate::Predicate;
use crate::compression_utils::WrapBody;
use crate::content_encoding::Encoding;
use futures_util::ready;
use http::{header, HeaderMap, HeaderValue, Response};
use http_body::Body;
use pin_project_lite::pin_project;
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
pin_project! {
#[derive(Debug)]
pub struct ResponseFuture<F, P> {
#[pin]
pub(crate) inner: F,
pub(crate) encoding: Encoding,
pub(crate) predicate: P
}
}
impl<F, B, E, P> Future for ResponseFuture<F, P>
where
F: Future<Output = Result<Response<B>, E>>,
B: Body,
P: Predicate,
{
type Output = Result<Response<CompressionBody<B>>, E>;
#[allow(unreachable_code, unused_mut, unused_variables)]
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let res = ready!(self.as_mut().project().inner.poll(cx)?);
let should_compress = !res.headers().contains_key(header::CONTENT_ENCODING)
&& self.predicate.should_compress(&res);
let (mut parts, body) = res.into_parts();
let body = match (should_compress, self.encoding) {
(false, _) | (_, Encoding::Identity) => {
return Poll::Ready(Ok(Response::from_parts(
parts,
CompressionBody::new(BodyInner::identity(body)),
)))
}
#[cfg(feature = "compression-gzip")]
(_, Encoding::Gzip) => CompressionBody::new(BodyInner::gzip(WrapBody::new(body))),
#[cfg(feature = "compression-deflate")]
(_, Encoding::Deflate) => CompressionBody::new(BodyInner::deflate(WrapBody::new(body))),
#[cfg(feature = "compression-br")]
(_, Encoding::Brotli) => CompressionBody::new(BodyInner::brotli(WrapBody::new(body))),
#[cfg(feature = "fs")]
(true, _) => {
return Poll::Ready(Ok(Response::from_parts(
parts,
CompressionBody::new(BodyInner::identity(body)),
)));
}
};
parts.headers.remove(header::CONTENT_LENGTH);
parts
.headers
.insert(header::CONTENT_ENCODING, self.encoding.into_header_value());
let res = Response::from_parts(parts, body);
Poll::Ready(Ok(res))
}
}