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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use bytes::serialize::*;
use bytes::varnum::*;
use rand::distributions::Distribution;
use rand::distributions::Standard;
use rand::seq::SliceRandom;
use rand::thread_rng;
use rand::Rng;
use std;
use std::collections::HashSet;
use std::io::{Cursor, Read, Write};
const BROTLI_BUFFER_SIZE: usize = 4096;
const BROTLI_QUALITY: u32 = 11;
const BROTLI_LG_WINDOW_SIZE: u32 = 20;
const LZW_MIN_CODE_SIZE: u8 = 8;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Compression {
Identity,
Gzip,
Deflate,
Brotli,
Lzw,
}
impl Distribution<Compression> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Compression {
use self::Compression::*;
let choices = [
Identity, Gzip,
Brotli,
];
choices.choose(rng).unwrap().clone()
}
}
#[derive(Clone, Debug)]
pub struct CompressionResult {
pub before_bytes: usize,
pub after_bytes: usize,
pub algorithms: HashSet<Compression>,
}
impl Compression {
pub fn name(&self) -> &str {
use self::Compression::*;
match *self {
Identity => "Identity",
Gzip => "Gzip",
Deflate => "Deflate",
Brotli => "Brotli",
Lzw => "Lzw",
}
}
pub fn code(&self) -> &str {
use self::Compression::*;
match *self {
Identity => "identity",
Gzip => "gzip",
Deflate => "deflate",
Brotli => "br",
Lzw => "lzw",
}
}
pub fn parse(name: Option<&str>) -> Option<Compression> {
let result = match name {
None | Some("identity") => Compression::Identity,
Some("lzw") => Compression::Lzw,
Some("br") => Compression::Brotli,
Some("gzip") => Compression::Gzip,
Some("deflate") => Compression::Deflate,
Some("random") => thread_rng().gen(),
Some(_) => {
return None;
}
};
Some(result)
}
pub fn values() -> Box<[Self]> {
use self::Compression::*;
Box::new([
Identity, Gzip, Deflate, Brotli,
])
}
pub fn is_compressed(&self) -> bool {
if let Compression::Identity = *self {
true
} else {
false
}
}
pub fn compress<W: Write>(
&self,
data: &[u8],
out: &mut W,
) -> Result<CompressionResult, std::io::Error> {
let before_bytes = data.len();
let after_bytes = match *self {
Compression::Identity => {
out.write_all(b"identity;")?;
out.write_varnum(data.len() as u32)?;
out.write_all(data)?;
data.len()
}
Compression::Gzip => {
out.write_all(b"gzip;")?;
let buffer = Vec::with_capacity(data.len());
let mut encoder =
flate2::write::GzEncoder::new(buffer, flate2::Compression::best());
encoder.write_all(data)?;
let buffer = encoder.finish()?;
out.write_varnum(buffer.len() as u32)?;
out.write_all(&buffer)?;
buffer.len()
}
Compression::Deflate => {
out.write_all(b"deflate;")?;
let buffer = Vec::with_capacity(data.len());
let mut encoder =
flate2::write::ZlibEncoder::new(buffer, flate2::Compression::best());
encoder.write(data)?;
let buffer = encoder.finish()?;
out.write_varnum(buffer.len() as u32)?;
out.write_all(&buffer)?;
buffer.len()
}
Compression::Brotli => {
out.write_all(b"br;")?;
let mut buffer = Vec::with_capacity(data.len());
{
let mut encoder = brotli::CompressorWriter::new(
&mut buffer,
BROTLI_BUFFER_SIZE,
BROTLI_QUALITY,
BROTLI_LG_WINDOW_SIZE,
);
encoder.write(data)?;
}
out.write_varnum(buffer.len() as u32)?;
out.write_all(&buffer)?;
buffer.len()
}
Compression::Lzw => {
out.write_all(b"compress;")?;
let mut buffer = Vec::with_capacity(data.len());
{
let writer = lzw::LsbWriter::new(&mut buffer);
let mut encoder = lzw::Encoder::new(writer, LZW_MIN_CODE_SIZE)?;
encoder.encode_bytes(data)?;
}
out.write_varnum(buffer.len() as u32)?;
out.write_all(&buffer)?;
buffer.len()
}
};
Ok(CompressionResult {
before_bytes,
after_bytes,
algorithms: [self.clone()].iter().cloned().collect(),
})
}
pub fn decompress<R: Read, T>(
inp: &mut R,
deserializer: &T,
) -> Result<T::Target, std::io::Error>
where
T: Deserializer,
{
const MAX_LENGTH: usize = 32;
let mut header = Vec::with_capacity(MAX_LENGTH);
let mut found = false;
for _ in 0..MAX_LENGTH {
let mut buf = [0];
inp.read_exact(&mut buf)?;
if buf[0] != b';' {
header.push(buf[0]);
} else {
found = true;
break;
}
}
if !found {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Invalid compression header",
));
}
let compression = if &header == b"identity" {
Compression::Identity
} else if &header == b"gzip" {
Compression::Gzip
} else if &header == b"deflate" {
Compression::Deflate
} else if &header == b"br" {
Compression::Brotli
} else if &header == b"compress" {
Compression::Lzw
} else {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Invalid compression header",
));
};
let mut byte_len = 0;
inp.read_varnum_to(&mut byte_len)?;
let mut compressed_bytes = Vec::with_capacity(byte_len as usize);
unsafe { compressed_bytes.set_len(byte_len as usize) };
inp.read_exact(&mut compressed_bytes)?;
let decompressed_bytes = match compression {
Compression::Identity => compressed_bytes,
Compression::Gzip => {
let mut decoder = flate2::read::GzDecoder::new(Cursor::new(&compressed_bytes));
let mut buf = Vec::with_capacity(1024);
decoder.read_to_end(&mut buf)?;
buf
}
Compression::Deflate => {
let mut decoder = flate2::read::ZlibDecoder::new(Cursor::new(&compressed_bytes));
let mut buf = Vec::with_capacity(1024);
decoder.read_to_end(&mut buf)?;
buf
}
Compression::Brotli => {
let mut decoder =
brotli::Decompressor::new(Cursor::new(&compressed_bytes), BROTLI_BUFFER_SIZE);
let mut buf = Vec::with_capacity(1024);
decoder.read_to_end(&mut buf)?;
buf
}
Compression::Lzw => {
let reader = lzw::LsbReader::new();
let mut decoder = lzw::Decoder::new(reader, LZW_MIN_CODE_SIZE);
let (_, data) = decoder.decode_bytes(&compressed_bytes)?;
let mut buf = Vec::with_capacity(data.len());
buf.extend_from_slice(data);
buf
}
};
let value = deserializer.read(&mut Cursor::new(decompressed_bytes))?;
Ok(value)
}
}