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
use crate::signature::SignedRequest;
#[cfg(feature = "encoding")]
use crate::signature::SignedRequestPayload;
#[cfg(feature = "encoding")]
use flate2::{write::GzEncoder, Compression};
#[cfg(feature = "encoding")]
use std::io::Write;
pub const DEFAULT_GZIP_COMPRESSION_LEVEL: u32 = 6;
#[derive(Debug, Clone)]
pub enum ContentEncoding {
Identity,
#[cfg(feature = "encoding")]
Gzip(Option<usize>, u32),
}
impl Default for ContentEncoding {
fn default() -> Self {
ContentEncoding::Identity
}
}
impl ContentEncoding {
#[allow(warnings)]
pub fn encode(&self, request: &mut SignedRequest) {
match self {
ContentEncoding::Identity => {
return;
}
#[cfg(feature = "encoding")]
ContentEncoding::Gzip(min_payload_size, level) => {
match request.payload {
None => return,
Some(SignedRequestPayload::Buffer(ref payload)) => {
if let Some(min_payload_size) = &min_payload_size {
if payload.len() < *min_payload_size {
return;
}
}
let mut encoder =
GzEncoder::new(Vec::<u8>::new(), Compression::new(*level));
encoder
.write_all(payload)
.expect("Request payload was not written to encoder.");
let payload_compressed =
encoder.finish().expect("Failed to finish compression.");
if payload.len() < payload_compressed.len() {
return;
}
let payload_compressed = bytes::Bytes::from(payload_compressed);
request.payload = Some(SignedRequestPayload::Buffer(payload_compressed));
}
Some(SignedRequestPayload::Stream(ref stream)) => {
return;
}
};
request.add_header("Content-Encoding", "gzip");
}
}
}
}